Is it possible to combine programming languages

programming-languages

I've been programming for a while, I've written some rudimentary programs, and I want to keep learning. I've reached that point where you just don't know what to learn next, and I'd like to ask a question for my own curiosity.

The question, in a nutshell, is if you can combine multiple programming languages into 1 result? For example, can this code be possible?

<html>
cout << "Hello world!";
</html>

or

import java.util.Scanner;
cout << "Insert a number from 1 to 10";
Scanner n = new Scanner(System.in);
System.out.println("The value you entered was" +n.newLine());

This feels like a silly question but I can't possible know if it's possible or not, so that's why I'm asking it. In this question I notice he is using Python code in html code, if my above example is not possible, what did he do?

Best Answer

You first example is sort of possible. Usually such things happen in PHP (and other related web-programming languages) like this:

<HTML>
<?PHP
call_some_php_function(1,2,"a","b"); /* This is may return nothing, a text string, or actual HTML markup code */
?>
</HTML>

Some important points to note about this example:

  • HTML is NOT a progamming language, it is a markup language.
  • The PHP and HTML and not executed/interpreted in the same place: PHP code is executed by a PHP interpreter running on the server and the result is "injected" into the surrounding HTML. Then that whole blob is sent to the client/browser which renders the complete HTML.

Your second example looks like some sort of mash-up of C++ and Java. It's possible to have compiled modules written in different languages talk to each other, but to combine Java and C++ in the same source file would be extremely confusing and difficult: how would the compiler know which statements are Java and which are C++?

I suppose in theory you could write a special compiler/pre-processor with "language" indicators such as:

Java
{
    import java.util.Scanner;
}
C++
{
   cout << "Insert a number from 1 to 10";
}
Java
{
    Scanner n = new Scanner(System.in); //Actually, this line *could* be a C++ line - it's hard for me to tell just by looking at it.
    System.out.println("The value you entered was" +n.newLine());
}

But I'm honestly not sure you'd gain anything useful by doing this.

Also, how would this hybrid language environment handle language features which are incompatible between the two?