Tutorials

Home Java Tutorial

Java Tutorials

Introduction

Java is a general-purpose programming language used to build web applications, enterprise software, desktop applications, backend services, and Android applications. It is known for its object-oriented approach, strong type system, and ability to run on different platforms through the Java Virtual Machine (JVM).

These Java Tutorials for Beginners introduce programming concepts step by step, from writing your first program to understanding classes, objects, inheritance, and practical coding exercises.

Why Learn Java?

  • Understand core programming concepts.
  • Build a strong foundation in object-oriented programming.
  • Develop backend applications and software solutions.
  • Practice problem-solving through coding exercises.
  • Prepare for more advanced Java frameworks and tools.

What Is the JVM?

The Java Virtual Machine runs Java bytecode. Java source code is compiled into bytecode, which can run on a compatible JVM. This is the foundation of Java's "write once, run anywhere" approach.

Java Installation and Setup

Before starting this Java Basics Tutorial, install a Java Development Kit (JDK). The JDK includes the compiler, runtime tools, and utilities needed to develop Java programs.

Step 1: Install the JDK

Download a suitable JDK distribution, such as OpenJDK, from a trusted provider. Follow the installation instructions for your operating system.

Step 2: Choose a Code Editor

You can write Java code in a simple text editor or use an IDE such as IntelliJ IDEA, Eclipse, or Visual Studio Code with the appropriate Java extensions.

Step 3: Verify the Installation

Open a terminal or command prompt and run:

Terminal
java -version
javac -version

The commands display the installed Java runtime and compiler versions when they are correctly configured.

Your First Java Program

A common first step in learning Java is printing a message to the console. Create a file named HelloWorld.java.

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

How to Run the Program

Open the terminal in the directory containing the file:

Terminal
javac HelloWorld.java
java HelloWorld

Output:

Output
Hello, Java!

The javac command compiles the source file. The java command runs the compiled class. The filename must match the public class name.

Java Syntax and Comments

Java syntax defines how instructions, classes, and methods are written. Java statements commonly end with a semicolon, and blocks of code are enclosed in curly braces.

Example of Java Comments

Java
public class CommentsExample {
    public static void main(String[] args) {
        // This is a single-line comment

        /*
         * This is a multi-line comment.
         */

        System.out.println("Learning Java syntax");
    }
}

Comments explain code to readers and are ignored by the compiler. Java identifiers are case-sensitive, so studentName and StudentName represent different identifiers.

Java Variables and Data Types

Variables store information that a program can use. Every Java variable has a type, which determines what kind of value it can hold.

Primitive Data Types

  • int — whole numbers.
  • double — decimal numbers.
  • char — a single character.
  • boolean — true or false values.
  • long, float, byte, and short — other numeric types.
Java
public class VariablesExample {
    public static void main(String[] args) {
        String name = "Arun";
        int age = 21;
        double score = 87.5;
        char grade = 'A';
        boolean learningJava = true;

        System.out.println(name);
        System.out.println(age);
        System.out.println(score);
        System.out.println(grade);
        System.out.println(learningJava);
    }
}

String is a reference type, not a primitive data type. Java also supports arrays, classes, interfaces, and other reference types.

Java Operators

Operators perform calculations, compare values, and combine conditions. Understanding operators makes it easier to create expressions and control program behaviour.

  • Arithmetic: + - * / %
  • Comparison: == != > < >= <=
  • Logical: && || !
  • Assignment: = += -= *=
  • Increment and decrement: ++ --
Java
public class OperatorsExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 3;

        System.out.println(a + b);  // 13
        System.out.println(a - b);  // 7
        System.out.println(a * b);  // 30
        System.out.println(a / b);  // 3
        System.out.println(a % b);  // 1

        System.out.println(a > b);  // true
    }
}

When both operands of integer division are integers, Java discards the fractional part of the result.

Java Input and Output

Java provides console output through System.out.println(). To read keyboard input in beginner programs, you can use the Scanner class.

Java
import java.util.Scanner;

public class UserInputExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        System.out.println("Welcome, " + name + "!");

        scanner.close();
    }
}

The nextLine() method reads a line of text. Other Scanner methods, such as nextInt(), can read specific data types.

Conditional Statements in Java

Conditional statements allow a program to choose different actions based on whether a condition is true or false. Java supports if, else if, else, and switch.

Java
public class ConditionExample {
    public static void main(String[] args) {
        int mark = 75;

        if (mark >= 90) {
            System.out.println("Grade A");
        } else if (mark >= 60) {
            System.out.println("Pass");
        } else {
            System.out.println("Try again");
        }
    }
}

The program checks each condition in order and executes the first matching branch.

Loops in Java

Loops repeat a block of code. They are useful for processing lists of values, counting items, and automating repetitive tasks.

For Loop

Java
public class ForLoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }
}

While Loop

Java
int count = 1;

while (count <= 3) {
    System.out.println(count);
    count++;
}

Java also supports do-while loops and enhanced for loops for iterating over arrays and collections.

Arrays in Java

An array stores a fixed number of values of the same type. Array indexes start at zero, so the first element is at index 0.

Java
public class ArrayExample {
    public static void main(String[] args) {
        int[] marks = {80, 75, 92, 68};

        for (int mark : marks) {
            System.out.println(mark);
        }

        System.out.println("First mark: " + marks[0]);
    }
}

Accessing an invalid index causes an ArrayIndexOutOfBoundsException. Use the array's length property to check its size.

Strings in Java

A String represents text. Java provides methods to inspect, compare, and transform strings. String objects are immutable, meaning their contents cannot be changed after creation.

Java
public class StringExample {
    public static void main(String[] args) {
        String language = "Java Programming";

        System.out.println(language.length());
        System.out.println(language.toUpperCase());
        System.out.println(language.toLowerCase());
        System.out.println(language.contains("Java"));
        System.out.println(language.substring(0, 4));
    }
}

Use equals() to compare String contents. The == operator compares object references rather than reliably comparing text values.

Methods in Java

Methods group reusable instructions into named blocks. A method can accept parameters and return a value. Breaking programs into methods makes code easier to test and maintain.

Java
public class MethodExample {
    static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        int result = add(10, 20);
        System.out.println("Sum: " + result);
    }
}

In this example, add() receives two integer parameters and returns their sum. The static keyword allows the method to be called from the static main method without creating an object.

Java Object-Oriented Programming Tutorial

Object-oriented programming (OOP) organises software around classes and objects. It helps developers structure larger programs into components that can be reused and maintained.

Classes and Objects

A class defines the data and behaviour that its objects can have. An object is an instance of a class.

Java
class Student {
    String name;
    int age;

    void displayDetails() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

public class StudentExample {
    public static void main(String[] args) {
        Student student = new Student();

        student.name = "Priya";
        student.age = 20;

        student.displayDetails();
    }
}

Four Main OOP Concepts

  • Encapsulation: Bundling data and methods together while controlling access to an object's internal state.
  • Inheritance: Creating a class that derives behaviour and properties from another class.
  • Polymorphism: Allowing a common interface or parent type to represent different implementations.
  • Abstraction: Exposing essential operations while hiding implementation details.

Inheritance and Polymorphism in Java

Inheritance allows a subclass to extend a superclass. Polymorphism allows a superclass reference to call an overridden method on a subclass object.

Java
class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

public class InheritanceExample {
    public static void main(String[] args) {
        Animal animal = new Dog();
        animal.sound();
    }
}

Output: Dog barks. The overridden method is selected at runtime based on the actual object.

Interfaces and Abstraction

An interface defines a contract that implementing classes agree to follow. Interfaces are commonly used to separate what a component does from how it does it.

Java
interface Payment {
    void pay(double amount);
}

class CardPayment implements Payment {
    @Override
    public void pay(double amount) {
        System.out.println("Paid: " + amount);
    }
}

public class InterfaceExample {
    public static void main(String[] args) {
        Payment payment = new CardPayment();
        payment.pay(500.0);
    }
}

Interfaces are useful when different classes need to provide the same behaviour through a shared contract.

Exception Handling in Java

Exceptions represent conditions that interrupt the normal flow of a program. Java uses try, catch, and finally to handle many runtime problems.

Java
public class ExceptionExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero.");
        }
    }
}

The catch block handles the arithmetic exception so the program can respond with a helpful message instead of terminating at that statement.

Java Collections Framework

The Java Collections Framework provides data structures for storing and working with groups of objects. Common interfaces include List, Set, and Map.

Java
import java.util.ArrayList;
import java.util.List;

public class CollectionExample {
    public static void main(String[] args) {
        List languages = new ArrayList<>();

        languages.add("Java");
        languages.add("Python");
        languages.add("JavaScript");

        for (String language : languages) {
            System.out.println(language);
        }
    }
}
  • List maintains an ordered sequence and can contain duplicates.
  • Set stores unique elements.
  • Map stores key-value pairs.

Java Programming Examples

Practising small programs helps reinforce concepts from Java tutorials. Start with calculations and conditions before moving to arrays, strings, and methods.

Example 1: Check Whether a Number Is Even or Odd

Java
public class EvenOdd {
    public static void main(String[] args) {
        int number = 14;

        if (number % 2 == 0) {
            System.out.println("Even number");
        } else {
            System.out.println("Odd number");
        }
    }
}

Example 2: Find the Sum of Numbers from 1 to 10

Java
public class SumExample {
    public static void main(String[] args) {
        int sum = 0;

        for (int i = 1; i <= 10; i++) {
            sum += i;
        }

        System.out.println("Sum: " + sum);
    }
}

Example 3: Reverse a String

Java
public class ReverseString {
    public static void main(String[] args) {
        String text = "Java";
        String reversed = new StringBuilder(text)
                .reverse()
                .toString();

        System.out.println(reversed);
    }
}

Output: avaJ. Try changing the input and predicting the output before running each program.

Java Coding Exercises

Use these Java Coding Exercises to practise problem-solving. Try solving each task independently before checking a solution or searching for help.

Beginner Exercises

  1. Print your name, age, and favourite programming language.
  2. Read two numbers and display their sum, difference, and product.
  3. Check whether a number is positive, negative, or zero.
  4. Find the largest of three numbers.
  5. Print the multiplication table of a given number.
  6. Calculate the factorial of a positive integer.
  7. Count the vowels in a string.
  8. Find the largest element in an integer array.
  9. Check whether a word is a palindrome.
  10. Create a class with fields, a constructor, and a method.

Practice Example: Find the Largest Number in an Array

Java
public class LargestNumber {
    public static void main(String[] args) {
        int[] numbers = {12, 45, 7, 89, 23};
        int largest = numbers[0];

        for (int number : numbers) {
            if (number > largest) {
                largest = number;
            }
        }

        System.out.println("Largest: " + largest);
    }
}

Challenge yourself by modifying the example to find the smallest number or calculate the average of all elements.

Java Projects for Beginners

After learning the basics, apply your skills to small projects. These projects help connect variables, methods, conditions, loops, and object-oriented programming.

1. Student Grade Calculator

Accept marks for multiple subjects, calculate the average, and display a grade using conditional statements.

2. Simple Calculator

Create a calculator that performs addition, subtraction, multiplication, and division. Handle invalid operations and division by zero.

3. Number Guessing Game

Generate a random number and let the user guess it. Give hints such as "too high" or "too low" until the correct answer is found.

4. Student Management System

Create a Student class and implement options to add, display, search, and update student records. Begin with in-memory storage before exploring file or database storage.

5. Library Management System

Model books and library users with classes. Add basic operations for listing books, borrowing books, and recording returns.

Java Learning Roadmap for Beginners

Follow this learning sequence to build your Java knowledge gradually. Practise each topic before moving to the next.

  1. Step 1: Install the JDK and write simple programs.
  2. Step 2: Learn variables, data types, and operators.
  3. Step 3: Practise conditions, loops, and arrays.
  4. Step 4: Understand strings, methods, and basic debugging.
  5. Step 5: Learn classes, objects, encapsulation, and inheritance.
  6. Step 6: Practise interfaces, exception handling, and collections.
  7. Step 7: Build beginner projects and use Git for version control.
  8. Step 8: Explore databases, testing, and a Java framework when ready.

Consistent practice and building small projects are more effective than memorising code without understanding it.

Frequently Asked Questions About Java

1. Is Java suitable for beginners?

Yes. Java is suitable for beginners who want to learn programming fundamentals, structured coding, and object-oriented programming. Start with simple examples and gradually build more complex programs.

2. What should I learn first in Java?

Begin with installation, syntax, variables, data types, operators, input and output, conditional statements, and loops. Then learn arrays, methods, and object-oriented programming.

3. What is the difference between JDK and JVM?

The JDK provides tools for developing Java applications, including the compiler. The JVM executes Java bytecode. A Java runtime environment provides the runtime components needed to run applications.

4. Why is Java called platform-independent?

Java source code is compiled into bytecode that can run on compatible JVM implementations across different operating systems and hardware platforms.

5. How can I improve my Java coding skills?

Practise coding exercises regularly, read error messages carefully, debug your programs, review your code, and build projects that solve practical problems.

6. What projects can beginners build with Java?

Beginners can build a calculator, grade calculator, number guessing game, student management system, and library management system. These projects reinforce basic Java concepts.

Start Learning Java Programming

Explore Java Tutorials for Beginners, practise Java Programming Examples, and solve Java Coding Exercises to strengthen your programming fundamentals. Learn Java step by step and apply your knowledge by building practical projects.

Join Our WhatsApp Channel 💬

Join our WhatsApp community for internship updates, IT courses, placement support, and latest job opportunities.

Join Now