, ,

Sample Java Program – Basics of Java Programming

1.8 Sample Java Program

The term program refers to source code that is compiled and directly executed. The terms program and application are often used synonymously, and are so used in this book. To create a program in Java, the program must have a class that defines a method named main, which is invoked at runtime to start the execution of the program. The class with this main() method is known as the entry point of the program.

Essential Elements of a Java Program

Example 1.5 comprises three classes: Point2D, Point3D, and TestPoint3D. The public class TestPoint3D in the file TestPoint3D.java is the entry point of the program. It defines a method with the name main. The method header of this main() method must be declared as shown in the following method stub:

Click here to view code image

public static void main(String[] args)   // Method header
{ /* Implementation */ }

The main() method has public access—that is, it is accessible from any class. The keyword static means the method belongs to the class. The keyword void indicates that the method does not return any value. The parameter args is an array of strings that can be used to pass information to the main() method when execution starts.

Example 1.5 A Sample Program

Click here to view code image

// File: Point2D.java
public class Point2D {
  // Same as in Example 1.2.
}

Click here to view code image

// File: Point3D.java
public class Point3D extends Point2D {
  // Same as in Example 1.3.
}

Click here to view code image

// File: TestPoint3D.java
public class TestPoint3D {
  public static void main(String[] args) {
    Point3D p3A = new Point3D(10, 20, 30);
    System.out.println(“p3A: ” + p3A.toString());
    System.out.println(“x: ” + p3A.getX());
    System.out.println(“y: ” + p3A.getY());
    System.out.println(“z: ” + p3A.getZ());
    p3A.setX(-10); p3A.setY(-20); p3A.setZ(-30);
    System.out.println(“p3A: ” + p3A.toString());

    Point3D p3B = new Point3D(30, 20, 10);
    System.out.println(“p3B: ” + p3B.toString());
    System.out.println(“Distance between p3A and p3B: ” +
                        Point3D.distance(p3A, p3B));
    Point3D.showInfo();
  }
}

Output from the program:

Click here to view code image

p3A: (10,20,30)
x: 10
y: 20
z: 30
p3A: (-10,-20,-30)
p3B: (30,20,10)
Distance between p3A and p3B: 69.2820323027551
A 3D point represented by (x,y,z)-coordinates.

Related Posts