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
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 classHelloWorld {
public static voidmain(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 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:
Create an int variable score with value 95
Create a double variable gpa with value 3.85
Create a String variable city with value "New York"
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
importjava.util.Scanner;
public classGreeting {
public static voidmain(String[] args) {
Scanner sc = newScanner(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.
Import java.util.Scanner
Ask for name and favorite color using nextLine()
Print: "Hello {name}, your favorite color is {color}!"
Java
importjava.util.Scanner;
public classGreeting {
public static voidmain(String[] args) {
Scanner sc = newScanner(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;
// Arithmeticint sum = a + b;
int product = a * b;
int remainder = a % b;
// Comparison & Logicalboolean 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.
Create int variables width and length
Calculate area = width * length
Calculate perimeter = 2 * (width + length)
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.
while checks the condition first; do-while runs the body at least once.
Java
// while loopint count = 0;
while (count < 5) {
System.out.println("While: " + count);
count++;
}
// do-while loopint 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:
Use a for loop to print all even numbers from 2 to 20
Use a while loop to calculate the sum of numbers from 1 to 100
Java
// Even numbers 2-20for (int i = 2; i <= 20; i += 2) {
System.out.println(i);
}
// Sum of 1 to 100int 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 classMethodExamples {
// Method with parameters and return valuepublic static intadd(int a, int b) {
return a + b;
}
// Void method (no return value)public static voidgreet(String name) {
System.out.println("Hello, " + name + "!");
}
public static voidmain(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 intmultiply(int a, int b) {
return a * b;
}
public static doublemultiply(double a, double b) {
return a * b;
}
// UsageSystem.out.println(multiply(5, 3)); // 15System.out.println(multiply(2.5, 4.0)); // 10.0
Practice: Methods
Write a method isEven(int n) that returns true if n is even
Write a method factorial(int n) that returns the factorial of n
Write a method reverseString(String s) that returns the reversed string
Java
public static booleanisEven(int n) {
return n % 2 == 0;
}
public static intfactorial(int n) {
if (n <= 1) return1;
return n * factorial(n - 1);
}
public staticStringreverseString(String s) {
returnnewStringBuilder(s).reverse().toString();
}
System.out.println(isEven(4)); // trueSystem.out.println(factorial(5)); // 120System.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.
Create an array of 5 integers and calculate their sum using a for loop
Write code to count how many vowels are in a given string
Java
// Sum of arrayint[] nums = {10, 20, 30, 40, 50};
int sum = 0;
for (int n : nums) {
sum += n;
}
System.out.println("Sum: " + sum);
// Count vowelsString 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 classclassStudent {
String name;
int age;
// ConstructorStudent(String name, int age) {
this.name = name;
this.age = age;
}
voidintroduce() {
System.out.println("Hi, I'm " + name + " and I'm " + age + " years old.");
}
}
// Create objectsStudent alice = newStudent("Alice", 20);
Student bob = newStudent("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
classBook {
String title;
String author;
int year;
Book(String title, String author, int year) {
this.title = title;
this.author = author;
this.year = year;
}
voiddisplayInfo() {
System.out.println("\"" + title + "\" by " + author + " (" + year + ")");
}
}
// UsageBook book1 = newBook("1984", "George Orwell", 1949);
Book book2 = newBook("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.