Site Search:

Create executable Java applications with a main method; run a Java program from the command line; including console output.

Back OCAJP

The command "java" is used to run the compiled bytecode, the .class need to be omitted in java command's parameter.

java program calls main() method to start a Java process. The JVM allocate resources for the process to run.

run a Java program
run a Java program


The following are all valid main() method signatures:
public static void main(String[] args) {}
public static void main(String args[]) {}
public static void main(String... args) {}

public access modifier allows the JVM to access the main method(), static allow JVM to call the main() method without creating an object, void return type means main don't need to return value, String[] args, String args[] or String... args are array of java program argument lists.

Remember the following rule, you should be able to recognize the OCAJP trick questions: arrays start index is 0 instead of 1, strings with spaces must be in quotes.



OCAJP>cat Class.java 
public class Class{
  public static int main(String...args) {
    System.out.println(args[0]);
    return 1;
  }
}
class Class2{}
class Class3{}
OCAJP>javac Class.java 
OCAJP>ls Class*

Class.class Class.java Class2.class Class3.class
OCAJP>java Class
Error: Main method must return a value of type void in class Class, please 
define the main method as:

   public static void main(String[] args)
OCAJP>vi Class.java 
OCAJP>cat Class.java 
public class Class{
  public static void main(String...args) {
    System.out.println(args[0]);
  }
}
class Class2{}
class Class3{}
OCAJP>javac Class.java 
OCAJP>java Class
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Class.main(Class.java:3)
OCAJP>java Class "para meter" par2
para meter




OCAJP>vi Class.java 
OCAJP>cat Class.java 
public class Class{
  public static void main(String...args) {
    System.out.println(args[0]);
  }
}
class Class2{
  public static void main(String...args) {
    System.out.println(args[0]);
  }
}
class Class3{}
OCAJP>javac Class.java 
OCAJP>ls Class*
Class.class Class.java Class2.class Class3.class
OCAJP>java Class a
a
OCAJP>java Class2 b
b


Back OCAJP