Show List

Sample Java Program

A Java program contains one or more classes. Here is a simple Java program to add two numbers. In the program, value of the two numbers are given. Program calculates the sum and then displays on the screen. Few things to notice: 

  • Every line of code in Java must be inside a class. In the example below the class name is AddNumber. Class name should start with uppercase letter.
  • A class may contain variables, methods and constructors. In the example below  num1, num2 and sum are variables, main, calculateSum and printSum are methods.
  • Constructors are special methods that have same name as the class name and are used to initialize the class valiables. In the example below AddNumber is a constructor. This constructor is used to assign value to variables num1 and num2.
  • Methods are collection of statements that perform some specific task and may return the result to the caller. calculateSum method in the example below calculates sum by adding two numbers. printSum method prints the statement showing the sum.
  • Object is an instance of a Java class. Objects have behavior of their class. In the example below obj is the object of class AddNumber. This object is then used to call the methods calculateSum and printSum.
  • main method with signature public static void main(String[] args) is the entry point of the java program. This method is first called when the program is executed.
  • System.out.println is used to print an argument passed to it on the console.
  • Comments are used to explain Java code and to make it more readable. These are not executed by the compiler. In the example below the statements starting // are comments.
public class AddNumber {

// two integer variables num1 and num2
// and a variable "sum" to store the result
int num1, num2 , sum;

AddNumber(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}

public static void main(String[] args) {
AddNumber obj = new AddNumber(5, 2);
obj.calculateSum();
obj.printSum();
}

private void calculateSum() {
//calculating the sum of num1 and num2 and
//storing the result in the variable sum
sum = num1 + num2;
}

private void printSum() {
//printing the sum
System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum);
}
}

To run the program in IDE, create a new project and a class file with name same as class name "AddNumber" provided in the java code. Click on the run button in the IDE to run the program. Follow the video guide below for steps.

Output:
Sum of 5 and 2 is: 7Process finished with exit code 0

Video guide:

    Leave a Comment


  • captcha text