Open In App

Java Programming Basics

Last Updated : 20 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Java is a class-based, object-oriented programming language that is designed to be secure and portable. Its core principle is “Write Once, Run Anywhere” (WORA), meaning Java code can run on any device or operating system that has a Java Virtual Machine (JVM).

Java Development Environment:

To run Java on your machine, you first need to set up the Java environment properly. This includes configuring the required environment variables (such as PATH and JAVA_HOME).

You can refer to Setting up Environment Variables For Java article for a step-by-step guide on setting up Java environment variables.

The development environment of Java consists of three components mainly:

  1. JVM (Java Virtual Machine): JVM is the engine that runs Java programs. It converts Java bytecode (compiled code) into machine code (understandable by the OS).
  2. JRE (Java Runtime Environment): JRE = JVM + Libraries + Other components needed to run Java applications.
  3. JDK (Java Development Kit): JDK = JRE + Development Tools. It is required for developing Java applications.

Java Basic Syntax:

Before writing complex programs, it is important to understand the basic syntax of Java. The syntax defines the rules and structure of how Java code is written and executed. Every Java program is built using classes, methods, and statements.

Example:

Java
public class HelloWorld {
    public static void main(String[] args)
    {
        System.out.println("Hello, World");
    }
}

Output
Hello, World

Explanation:

  • public class HelloWorld: Defines a class named HelloWorld.
  • public static void main(String[] args): The entry point of the program; execution starts here.
  • System.out.println("Hello, World"): Prints the text "Hello, World" followed by a new line.

To learn Java syntax in depth and understand how this Hello World program runs, you may refer to this article: Java Hello World Program

Comments in Java:

Comments in Java are notes written inside the code that are ignored by the compiler. They are used to make the code more understandable and maintainable.

Example:

Java
public class CommentsExample {
    public static void main(String[] args) {
        // This is a single-line comment
        System.out.println("Hello, World"); // Comment at end of line

        /*
         * This is a multi-line comment
         * It can span across multiple lines
         */
        int x = 10;  // Variable declaration

        /**
         * This is a documentation comment (Javadoc)
         * It is used to generate documentation for methods, classes, etc.
         */
        System.out.println("Value of x: " + x);
    }
}

To know more about comments and it's types, you may refer to this article: Java Comments

Data Types in Java:

In Java, data types specify the type of values a variable can hold. They define the size, range and nature of data stored in memory. Java has two main categories of data types:

  1. Primitive: byte, short, int, long, float, double, char, boolean
  2. Non-Primitive: String, Arrays, Classes, Interfaces, Objects
Java
public class DataTypesDemo {
    public static void main(String[] args) {

        // -------- Primitive Data Types --------
        byte b = 100;              // 1 byte
        short s = 30000;           // 2 bytes
        int i = 100000;            // 4 bytes
        long l = 10000000000L;     // 8 bytes

        float f = 3.14f;           // 4 bytes
        double d = 3.14159265359;  // 8 bytes

        char c = 'A';              // 2 bytes (Unicode character)
        boolean flag = true;       // 1 bit

        // -------- Non-Primitive Data Types --------
        String str = "Hello, Java"; // String (class in Java)
        int[] arr = {1, 2, 3, 4, 5}; // Array
        Integer wrapperInt = Integer.valueOf(50); // Wrapper class example
        StringBuilder sb = new StringBuilder("Java"); // Class object

        // -------- Output --------
        System.out.println("byte: " + b);
        System.out.println("short: " + s);
        System.out.println("int: " + i);
        System.out.println("long: " + l);
        System.out.println("float: " + f);
        System.out.println("double: " + d);
        System.out.println("char: " + c);
        System.out.println("boolean: " + flag);

        System.out.println("String: " + str);
        System.out.print("Array: ");
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();

        System.out.println("Wrapper Integer: " + wrapperInt);
        System.out.println("StringBuilder: " + sb);
    }
}

Output
byte: 100
short: 30000
int: 100000
long: 10000000000
float: 3.14
double: 3.14159265359
char: A
boolean: true
String: Hello, Java
Array: 1 2 3 4 5 
Wrapper Integer: 50
StringBuilder: Java

To know Data Types and it's categories in more detail, you may refer to this article: Java Data Types

Variables in Java:

Variables are containers to store data in memory. Each variable has a name, type and value. It is the basic unit of storage in a program. Java has 4 types of variables.

  • Local Variables: Declared inside a method, constructor, or block. Accessible only within that block.
  • Instance Variables: Declared inside a class but outside any method. Each object of the class has its own copy.
  • Static Variables: Declared with the static keyword inside a class. Shared by all objects of the class.
  • Final Variables: Declared with final keyword. Value cannot be changed once assigned.
Java
public class VariablesDemo {

    // Instance variable (belongs to each object)
    int instanceVar = 10;

    // Static variable (shared across all objects of the class)
    static String staticVar = "I am static";

    public void showVariables() {
        // Local variable (declared inside a method)
        int localVar = 5;

        System.out.println("Instance Variable: " + instanceVar);
        System.out.println("Static Variable: " + staticVar);
        System.out.println("Local Variable: " + localVar);
    }

    public static void main(String[] args) {
        // Creating object
        VariablesDemo obj1 = new VariablesDemo();
        obj1.showVariables();

        // Accessing static variable directly using class name
        System.out.println("Accessing Static Variable via class: " + VariablesDemo.staticVar);
    }
}

Output
Instance Variable: 10
Static Variable: I am static
Local Variable: 5
Accessing Static Variable via class: I am static

Explanation:

  • Local Variable: Declared inside methods, constructors, or blocks.
  • Instance Variable: Declared inside the class but outside methods, each object gets its own copy.
  • Static Variable: Declared with static, shared among all objects of the class.

To know more about variables, you may refer to this article: Java Variables

Keywords in Java:

Keywords are reserved words in Java that have a predefined meaning. They cannot be used as variable names, class names or identifiers.

Examples: new, package, private, protected, public, return, short, static, etc.

To know all keywords in Java, you may refer to this article: Java Keywords

Operators in Java:

Operators are symbols that perform specific operations on one or more operands (variables or values). They are used to perform calculations, comparisons, logical operations and manipulate data.

They are basically of 7 types:

  • Arithmetic Operators: +, -, *, /, %
  • Relational Operators: ==, !=, >, <, >=, <=
  • Logical Operators: &&, ||, !
  • Assignment Operators: =, +=, -=, *=, /=, %=
  • Unary Operators: +, -, ++, --, !
  • Ternary Operator: condition ? value_if_true : value_if_false
  • Bitwise Operators: &, |, ^, ~, <<, >>, >>>
Java
public class SimpleOperatorsDemo {
    public static void main(String[] args) {
        int a = 10, b = 3;

        // Arithmetic Operators
        System.out.println("a + b = " + (a + b));  // Addition
        System.out.println("a - b = " + (a - b));  // Subtraction

        // Relational Operator
        System.out.println("a > b ? " + (a > b));  // Greater than

        // Logical Operator
        boolean x = true, y = false;
        System.out.println("x && y = " + (x && y));  // Logical AND

        // Assignment Operator
        a += 5;  // a = a + 5
        System.out.println("a after += 5 : " + a);

        // Ternary Operator
        int max = (a > b) ? a : b;
        System.out.println("Maximum = " + max);
    }
}

Output
a + b = 13
a - b = 7
a > b ? true
x && y = false
a after += 5 : 15
Maximum = 15

To learn about Operators in Java, you may refer to this article: Java Operators

Decision Making (Control Statements) in Java:

Decision-making (or control statements) are used to execute different blocks of code based on certain conditions. They allow a Java program to choose a path of execution depending on whether a condition is true or false.

Examples:

  • if: Executes a block if a condition is true.
  • if-else: Chooses between two blocks based on a condition.
  • if-else if-else: Tests multiple conditions sequentially.
  • switch: Selects one block from multiple options based on a variable’s value.
Java
public class DecisionMakingDemo {
    public static void main(String[] args) {
        int number = 10;

        // if statement
        if (number > 0) {
            System.out.println("The number is positive.");
        }

        // if-else statement
        if (number % 2 == 0) {
            System.out.println("The number is even.");
        } else {
            System.out.println("The number is odd.");
        }

        // if-else-if ladder
        if (number < 0) {
            System.out.println("The number is negative.");
        } else if (number == 0) {
            System.out.println("The number is zero.");
        } else {
            System.out.println("The number is positive.");
        }

        // switch statement
        int day = 3;
        switch (day) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            default:
                System.out.println("Other day");
        }
    }
}

Output
The number is positive.
The number is even.
The number is positive.
Wednesday

Explanation:

  • if: checks if a number is positive.
  • if-else: checks if the number is even or odd.
  • if-else-if: checks whether the number is negative, zero, or positive.
  • switch-case: prints the day of the week based on the value of day.

Loops in Java:

Loops are control statements in Java that allow a block of code to be executed repeatedly as long as a specified condition is true. They help in reducing code repetition.

There are 4 types of loops in Java.

  • for: Used when the number of iterations is known.
  • while: Used when the number of iterations is not known in advance, condition checked before each iteration.
  • do-while: Similar to while loop, but condition is checked after executing the block (executes at least once).
  • for-each: Used to iterate over arrays and collections.
Java
public class LoopsDemo {
    public static void main(String[] args) {

        // 1. For loop
        System.out.println("For Loop:");
        for (int i = 1; i <= 5; i++) {
            System.out.println("i = " + i);
        }

        // 2. While loop
        System.out.println("\nWhile Loop:");
        int j = 1;
        while (j <= 5) {
            System.out.println("j = " + j);
            j++;
        }

        // 3. Do-While loop
        System.out.println("\nDo-While Loop:");
        int k = 1;
        do {
            System.out.println("k = " + k);
            k++;
        } while (k <= 5);

        // 4. Enhanced For Loop (for-each loop)
        System.out.println("\nEnhanced For Loop:");
        int[] numbers = {10, 20, 30, 40, 50};
        for (int num : numbers) {
            System.out.println("num = " + num);
        }
    }
}

Output
For Loop:
i = 1
i = 2
i = 3
i = 4
i = 5

While Loop:
j = 1
j = 2
j = 3
j = 4
j = 5

Do-While Loop:
k = 1
k = 2
k = 3
k = 4
k = 5

Enhanced For Loop:
num = 10
num = 20
num = 30
num = 40
num = 50

To know Loops in Java in detail, you may refer to this article: Java Loops


Article Tags :
Practice Tags :

Similar Reads