Basic Java Program

Basic Java Program

This is a simple program that prints Hello World on screen. Most programmers write the Hello World program as their first program.

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}
Show Output
Info

Note: Don’t forget to save your java file with the .java extension. The filename must match the class name. If a class name is Main, then the filename must be Main.java, if class name is School, then the file name must be School.java.

Basic Java Program Explained

  • Every code that runs in Java must be inside a class.
  • A class should always start with an uppercase first letter.
  • The name of the java file must match the class name.
  • public static void main(String[] args) means main function. Our program starts with main function.
  • System.out.println(“Hello World”); prints Hello World on Screen.
  • The curly braces {} mark the beginning and the end of a block of code.
  • Each code statement must end with a semicolon.

Work 1: Write a program to print your name in Java.

Java Program For Basic Calculation

This program performs basic calculation like addition, subtraction, multiplication, and division.

public class Main {
    public static void main(String[] args) {
        System.out.println("This is my first java program");
        int num1 = 10;
        int num2 = 20;

        int sum = num1 + num2;
        int diff = num1- num2;
        int mul = num1 * num2;
        int div = num1 / num2;

        System.out.println("The sum is "+sum);
        System.out.println("The diff "+diff);
        System.out.println("The mul is "+mul);
        System.out.println("The div is "+div);
    }
}
Show Output

Points To Remember

  • You don’t need the double quotes to output numbers.
  • System.out.println() prints the output on the screen.
  • In Java, each statement must end with a semicolon.

Challenge

  • Create a java program to print sum of three numbers.