Algo Infinity Verse

Start Your Journey With Java Programming Beginner-Friendly Concepts, Code & Practice

|
0 Topics
0 Examples
0 Exercises

Learn Java

Master the fundamentals of Java with clear explanations and hands-on examples

0 / 11 topics completed
01

Introduction to Java

Java is a high-level, object-oriented programming language developed by Sun Microsystems (now Oracle) and first released in 1995. It follows the principle of "Write Once, Run Anywhere" (WORA), meaning compiled Java code runs on any platform that supports the Java Virtual Machine (JVM).

Why Learn Java?

  • Platform Independent – Runs on any device with a JVM
  • Object-Oriented – Encourages reusable, modular code
  • Massive Ecosystem – Spring, Android, Hibernate, and more
  • Industry Standard – Used by 90% of Fortune 500 companies
  • Strong Typing – Catches errors at compile time

Your first Java program is the classic "Hello, World!":

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

Every Java application needs a main method — it's the entry point where the program starts executing. The class name must match the filename (HelloWorld.java).

02

Installation & Setup

To write and run Java code, you need the Java Development Kit (JDK) and a text editor or IDE. The JDK includes the compiler (javac), runtime (java), and libraries.

Installing the JDK

Download the latest JDK from oracle.com/java or use an open-source build like OpenJDK. Version 17 LTS or 21 LTS is recommended for beginners.

Bash
# Verify your Java installation
java -version
javac -version

Choosing an IDE

  • IntelliJ IDEA Community – Free, feature-rich, recommended for beginners
  • Eclipse – Free, widely used in industry
  • VS Code – Lightweight with Java extension pack
Bash
# Compile and run a Java program
javac HelloWorld.java    # compiles to HelloWorld.class
java HelloWorld          # runs the compiled bytecode

Java is a compiled language: you write .java source files, compile them to .class bytecode with javac, and run the bytecode with java on the JVM.

03

Variables & Data Types

In Java, every variable must have a declared type. Java is statically typed — once you declare a variable's type, it cannot hold a different type of value.

Java
String name = "Alice";    // Text
int age = 25;                // Whole number
double height = 5.7;         // Decimal number
boolean isStudent = true;    // true / false
char grade = 'A';            // Single character

System.out.println(name);
System.out.println(age);
Output
Alice
25
Type Size Example Description
byte8-bit127Small integer
int32-bit42Whole number
long64-bit100LLarge integer
float32-bit3.14fSingle precision decimal
double64-bit3.14159Double precision decimal
char16-bit'A'Single Unicode character
boolean1-bittrue/falseLogical value
💡

Java also has reference types like String, arrays, and objects. Unlike primitives, reference types store a reference (memory address) to the actual data.

Practice: Variables & Data Types

Create variables of different primitive types and print them:

  1. Create an int variable score with value 95
  2. Create a double variable gpa with value 3.85
  3. Create a String variable city with value "New York"
  4. Create a boolean variable passed set to true
  5. Print each variable using System.out.println()
Java
int score = 95;
double gpa = 3.85;
String city = "New York";
boolean passed = true;

System.out.println("Score: " + score);
System.out.println("GPA: " + gpa);
System.out.println("City: " + city);
System.out.println("Passed: " + passed);
04

Input & Output

Java provides System.out.println() for output and the Scanner class for reading user input.

System.out — Displaying Output

System.out.println() prints text followed by a newline. Use System.out.print() to print without a newline.

Java
String name = "Alice";
int age = 25;

System.out.println("My name is " + name + " and I am " + age + " years old.");
System.out.printf("Name: %s | Age: %d%n", name, age);
Output
My name is Alice and I am 25 years old.
Name: Alice | Age: 25

Scanner — Reading User Input

The Scanner class reads input from the console. Import it from java.util.

Java
import java.util.Scanner;

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

        System.out.print("What is your name? ");
        String name = sc.nextLine();

        System.out.print("How old are you? ");
        int age = sc.nextInt();

        System.out.println("Hello, " + name + "! In 10 years you will be " + (age + 10) + ".");
        sc.close();
    }
}
⚠️

Always call sc.close() to release the scanner resource. nextLine() reads a whole line; nextInt() reads an integer. Be careful about mixing them — nextInt() leaves a newline that nextLine() will consume!

Practice: Input & Output

Write a program that asks the user for their name and favorite color, then prints a greeting.

  1. Import java.util.Scanner
  2. Ask for name and favorite color using nextLine()
  3. Print: "Hello {name}, your favorite color is {color}!"
Java
import java.util.Scanner;

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

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

        System.out.print("Enter your favorite color: ");
        String color = sc.nextLine();

        System.out.println("Hello " + name + ", your favorite color is " + color + "!");
        sc.close();
    }
}
05

Operators

Operators perform operations on variables and values. Java supports arithmetic, assignment, comparison, logical, and more.

Category Operators Example
Arithmetic+ - * / %10 + 5 → 15
Assignment= += -= *= /=x += 5
Comparison== != < > <= >=10 > 5 → true
Logical&& || !true && false → false
Unary++ -- !i++
Java
int a = 10;
int b = 5;

// Arithmetic
int sum = a + b;
int product = a * b;
int remainder = a % b;

// Comparison & Logical
boolean isGreater = a > b;
boolean bothPositive = (a > 0) && (b > 0);

System.out.println("Sum: " + sum);
System.out.println("Product: " + product);
System.out.println("Remainder: " + remainder);
System.out.println("Is a > b? " + isGreater);
System.out.println("Both positive? " + bothPositive);
Output
Sum: 15
Product: 50
Remainder: 0
Is a > b? true
Both positive? true
Practice: Operators

Calculate the area and perimeter of a rectangle with width 8 and length 12.

  1. Create int variables width and length
  2. Calculate area = width * length
  3. Calculate perimeter = 2 * (width + length)
  4. Print both results
Java
int width = 8;
int length = 12;
int area = width * length;
int perimeter = 2 * (width + length);

System.out.println("Area: " + area);
System.out.println("Perimeter: " + perimeter);
06

Conditional Statements

Conditionals let your program make decisions. Java supports if, else if, else, and switch statements.

Java
int score = 85;
char grade;

if (score >= 90) {
    grade = 'A';
} else if (score >= 80) {
    grade = 'B';
} else if (score >= 70) {
    grade = 'C';
} else {
    grade = 'F';
}

System.out.println("Score: " + score + " → Grade: " + grade);
Output
Score: 85 → Grade: B

switch Statement

The switch statement is useful when checking a variable against many specific values.

Java
int day = 3;
String dayName;

switch (day) {
    case 1:  dayName = "Monday";    break;
    case 2:  dayName = "Tuesday";   break;
    case 3:  dayName = "Wednesday"; break;
    case 4:  dayName = "Thursday";  break;
    case 5:  dayName = "Friday";    break;
    default: dayName = "Weekend";
}

System.out.println(dayName);
Output
Wednesday
Practice: Conditionals

Write a program that reads a number and prints whether it is positive, negative, or zero.

  1. Use Scanner to read an integer
  2. Use if/else if/else to check the number
  3. Print the result
Java
import java.util.Scanner;

public class CheckNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        if (num > 0) {
            System.out.println("Positive");
        } else if (num < 0) {
            System.out.println("Negative");
        } else {
            System.out.println("Zero");
        }
        sc.close();
    }
}
07

Loops (for, while, do-while)

Loops let you repeat a block of code. Java has three loop types: for, while, and do-while.

for Loop

Use for when you know how many times to iterate.

Java
// Count from 0 to 4
for (int i = 0; i < 5; i++) {
    System.out.println("Count: " + i);
}

// Enhanced for-loop (for-each)
String[] fruits = {"apple", "banana", "cherry"};
for (String fruit : fruits) {
    System.out.println(fruit);
}
Output
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
apple
banana
cherry

while & do-while Loops

while checks the condition first; do-while runs the body at least once.

Java
// while loop
int count = 0;
while (count < 5) {
    System.out.println("While: " + count);
    count++;
}

// do-while loop
int num = 0;
do {
    System.out.println("Do-while: " + num);
    num++;
} while (num < 5);
⚠️

Always ensure your loop condition eventually becomes false to avoid infinite loops. Use break to exit early and continue to skip the current iteration.

Practice: Loops

Write two programs:

  1. Use a for loop to print all even numbers from 2 to 20
  2. Use a while loop to calculate the sum of numbers from 1 to 100
Java
// Even numbers 2-20
for (int i = 2; i <= 20; i += 2) {
    System.out.println(i);
}

// Sum of 1 to 100
int sum = 0;
int n = 1;
while (n <= 100) {
    sum += n;
    n++;
}
System.out.println("Sum: " + sum);
08

Methods

Methods (also called functions) are reusable blocks of code. They help you avoid repetition and organize your program into logical pieces.

Java
public class MethodExamples {

    // Method with parameters and return value
    public static int add(int a, int b) {
        return a + b;
    }

    // Void method (no return value)
    public static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }

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

        greet("Alice");
    }
}
Output
Sum: 15
Hello, Alice!

Method Overloading

Java allows multiple methods with the same name as long as parameters differ (number, type, or order).

Java
public static int multiply(int a, int b) {
    return a * b;
}

public static double multiply(double a, double b) {
    return a * b;
}

// Usage
System.out.println(multiply(5, 3));         // 15
System.out.println(multiply(2.5, 4.0));     // 10.0
Practice: Methods
  1. Write a method isEven(int n) that returns true if n is even
  2. Write a method factorial(int n) that returns the factorial of n
  3. Write a method reverseString(String s) that returns the reversed string
Java
public static boolean isEven(int n) {
    return n % 2 == 0;
}

public static int factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}

public static String reverseString(String s) {
    return new StringBuilder(s).reverse().toString();
}

System.out.println(isEven(4));               // true
System.out.println(factorial(5));            // 120
System.out.println(reverseString("hello")); // olleh
09

Arrays & Strings

Arrays store multiple values of the same type. Strings represent text and come with many built-in methods.

Arrays — Fixed-Size Collections

Arrays in Java have a fixed length. You can create them with new or with curly braces.

Java
// Creating arrays
int[] numbers = new int[5];         // [0, 0, 0, 0, 0]
String[] fruits = {"apple", "banana", "cherry"};

// Access and modify
numbers[0] = 10;
System.out.println(numbers[0]);     // 10
System.out.println(fruits[1]);      // banana
System.out.println("Length: " + fruits.length);

String Methods

Strings in Java are objects with many useful methods.

Java
String text = "Hello, Java!";

System.out.println(text.length());             // 12
System.out.println(text.toUpperCase());        // HELLO, JAVA!
System.out.println(text.toLowerCase());        // hello, java!
System.out.println(text.substring(7));         // Java!
System.out.println(text.replace("Java", "World")); // Hello, World!
System.out.println(text.contains("Java"));     // true
Practice: Arrays & Strings
  1. Create an array of 5 integers and calculate their sum using a for loop
  2. Write code to count how many vowels are in a given string
Java
// Sum of array
int[] nums = {10, 20, 30, 40, 50};
int sum = 0;
for (int n : nums) {
    sum += n;
}
System.out.println("Sum: " + sum);

// Count vowels
String str = "hello world";
int vowels = 0;
for (char c : str.toCharArray()) {
    if ("aeiou".indexOf(c) != -1) {
        vowels++;
    }
}
System.out.println("Vowels: " + vowels);
10

Classes & Objects

A class is a blueprint for creating objects. An object is an instance of a class with its own state (fields) and behavior (methods).

Java
// Define a class
class Student {
    String name;
    int age;

    // Constructor
    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    void introduce() {
        System.out.println("Hi, I'm " + name + " and I'm " + age + " years old.");
    }
}

// Create objects
Student alice = new Student("Alice", 20);
Student bob = new Student("Bob", 22);

alice.introduce();
bob.introduce();
Output
Hi, I'm Alice and I'm 20 years old.
Hi, I'm Bob and I'm 22 years old.
💡

this refers to the current object's fields. Constructors have the same name as the class and no return type. The new keyword creates an object in memory.

Practice: Classes & Objects

Create a Book class with fields title, author, and year. Add a constructor and a method displayInfo() that prints the book details. Then create two book objects.

Java
class Book {
    String title;
    String author;
    int year;

    Book(String title, String author, int year) {
        this.title = title;
        this.author = author;
        this.year = year;
    }

    void displayInfo() {
        System.out.println("\"" + title + "\" by " + author + " (" + year + ")");
    }
}

// Usage
Book book1 = new Book("1984", "George Orwell", 1949);
Book book2 = new Book("To Kill a Mockingbird", "Harper Lee", 1960);
book1.displayInfo();
book2.displayInfo();
11

Basic Object-Oriented Programming

Java is built around Object-Oriented Programming (OOP). The four main pillars are: Encapsulation, Inheritance, Polymorphism, and Abstraction.

1. Encapsulation

Bundle data and methods together, and restrict direct access to fields using private with public getters/setters.

Java
class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() { return name; }
    public int getAge() { return age; }
    public void setAge(int age) {
        if (age > 0) this.age = age;
    }
}

2. Inheritance

Create a new class based on an existing one using the extends keyword. The child class inherits fields and methods from the parent.

Java
// Parent class
class Animal {
    String name;
    Animal(String name) { this.name = name; }
    void speak() { System.out.println(name + " makes a sound"); }
}

// Child class
class Dog extends Animal {
    Dog(String name) { super(name); }

    @Override
    void speak() { System.out.println(name + " barks!"); }
}

// Polymorphism
Animal a = new Dog("Buddy");
a.speak();  // Buddy barks! (runtime polymorphism)
Output
Buddy barks!

3. Polymorphism & Abstraction

  • Polymorphism – Same method name, different behavior (method overriding & overloading)
  • Abstraction – Hide implementation details using abstract classes or interfaces
Java
// Abstract class
abstract class Shape {
    abstract double area();
}

class Circle extends Shape {
    double radius;
    Circle(double r) { radius = r; }

    @Override
    double area() { return Math.PI * radius * radius; }
}

class Rectangle extends Shape {
    double w, h;
    Rectangle(double w, double h) { this.w = w; this.h = h; }

    @Override
    double area() { return w * h; }
}

// Polymorphism in action
Shape[] shapes = {new Circle(5), new Rectangle(4, 6)};
for (Shape s : shapes) {
    System.out.println(s.area());
}
Output
78.53981633974483
24.0
Practice: OOP Concepts

Create a Vehicle base class and a Car subclass:

  1. Vehicle has a brand field and a method honk()
  2. Car extends Vehicle with an additional model field
  3. Override honk() in Car to print a car-specific sound
  4. Create a Car object and call its methods
Java
class Vehicle {
    String brand;
    Vehicle(String brand) { this.brand = brand; }
    void honk() { System.out.println(brand + " goes beep beep!"); }
}

class Car extends Vehicle {
    String model;
    Car(String brand, String model) {
        super(brand);
        this.model = model;
    }
    @Override
    void honk() { System.out.println(brand + " " + model + " goes HONK HONK!"); }
}

// Usage
Car myCar = new Car("Toyota", "Camry");
myCar.honk();  // Toyota Camry goes HONK HONK!