Structure of a Java Program

Naming Java source and compiled code
Concepts
Simple HalloWorld Program
Program with methods (function and procedure)

 

Naming Java source and compiled code

Java souce has extension java

Java compiled code has extension class

The file name for the source code must be the same as the name for the public class. E.g. in the first example below, both the public class and the source code
must be named Example1_HalloWorld.java

When the source is compiled, the resulting bytecode is automatically named Example1_HalloWorld.java.class.

Click here to se how to compile and run a java program

 

Concepts

final class A class from which no other class cam be derived (The class can't be sub-classed)
final <variabel> A variable which is declared as final, can not be changed. This is the same as a constant i other languages
main method Every Java application must contain a main method whose signature looks like this: public static void main(String[] args)
static field A static field does not change from one instance of the class to another
static method Static methods belong to a class, and do not operate on any instance of the class. This means that you can use the without creating an instance of a class
   

 

 

 

Simple HalloWorld Program

public class Example1_HalloWorld {

        public static void main(String[] args) {
                System.out.print("Hallo World");
        }
}

This program prints "Hallo World" to the console

public class : You have to create a class: The class source shoeld be saved in a in a file width the same name as the class an with extension java.
When the class has ben compiled, the bit code (The executable program) is saved in a file named <class-name>.class

public static void main: To run the class, you must have a method named main().

 

Program with methods (function and procedure)

public class Example2_CallingAFunction {
   //Method that returns a value (Function)
   private static long addOne (long number)
   { long newNumber;
     newNumber = number + 1;
     return newNumber;           
   }
   //Method that does not return a value (Procedure)
   private static void printResult(long result)
   {
        System.out.println(result);
   } 
        
        
    public static void main(String[] args) {
        long    result;
        long i;
        i = 3;
        result = addOne(i);
        printResult(i);
          
                
    }
}

 

 

 

 

 

 

Converted from CHM to HTML with chm2web Standard 2.7 (unicode)