Next: Classes
Up: Java
Previous: Java
Contents
Index
We'll jump right into a simple program:
//file Hello.java
public class Hello {
public static void main(String[] args) {
String name = args[0];
int age = Integer.parseInt(args[1]);
if(args.length != 2) {
System.out.println("Usage: Hello name age");
System.exit(1);
}
System.out.println("Hello " + name + ". You are "
+ age + " years old.");
}
}
Compiling this program involves
javac Hello.java
which creates a class file, and then
java Hello Harry 44
runs the executable. There are a few things worth noting
about this example:
- The program is wrapped inside of a class definition;
- A new type of basic variable - the String (an array
of characters) - is available, with the command-line arguments
captured as an array of strings;
- Printing out to standard output involves the
System.out.println command, which prints a newline
character at the end, with individual components to be
printed joined with the + character;
- The Integer.parseInt(string) command can be
used to convert a string to an integer;
- Generally, variables in Java can be declared
when introduced, as compared to C/C++, which generally
likes all variables declared near the beginning of a routine.
Note also the use of args.length to check for the
length of the args array. This reminds us of an
object.method syntax call to invoke a method, and
indeed that is the case here - as one gets deeper into
Java, one finds that many fundamental entities one
works with have an underlying class structure.
Next: Classes
Up: Java
Previous: Java
Contents
Index