Comparing Java to Other Languages
Superficially, Java looks a lot like many of the programming languages that preceded it. For example, here's the classic Hello, World! program written in the C programming language:
main()
{
Printf("Hello, World!");
}
This program simply displays the text “Hello, World!” on the computer's console. Here's the same program (almost) written in Java:
public class HelloApp
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}
Although the Java version is a bit more verbose, the two have several similarities:
-
Both require that each executable statement end with a semicolon.
-
Both use braces ({}) to mark blocks of code.
-
Both use a routine called main as the main entry point for the program.
There are many other similarities besides these that aren't evident in this simple example.
However, these two trivial examples bring the major difference between C and Java front and center: Java is inherently object-oriented. Object-oriented programming rears its ugly head even in this simple example:
-
In Java, even the simplest program is a class, so you have to provide a line that declares the name of the class. In this example, the class is named HelloApp. HelloApp has a method named main, which the Java Virtual Machine automatically calls when a program is run.
-
In the C example, printf is a library function you call to print information to the console. In Java, you use the PrintStream class to write information to the console. PrintStream? There's no PrintStream in this program! Wait a minute-yes, there is. Every Java program has available to it a PrintStream object that writes information to the console. You can get this PrintStream object by calling the out method of another class, named System. Thus, System.out gets the PrintStream object that writes to the console. The PrintStream class, in turn, has a method named println that writes a line to the console. So System.out.println really does two things, in the following order:
-
It uses the out field of the System class to get a PrintStream object.
-
It calls the println method of that object to write a line to the console.
Confusing? You bet. It will all make sense when you read about object-oriented programming in Book III, Chapter 1.
-
-
void looks familiar. Although it isn't shown in the C example, you could have coded void on the main function declaration to indicate that the main function doesn't return a value. void has the same meaning in Java. But static? What does that mean? That, too, is evidence of Java's object orientation. It's a bit early to explain what it means in this chapter, but you can find out in Book II, Chapter 7.
No comments:
Post a Comment