Java Beginner Guide
Build a strong Java foundation from zero with 20 beginner lessons. Learn variables, strings, loops, arrays, classes, methods, and more — each with code, exact output, and official Oracle documentation links.
Start LearningWhat is Java & The JVM
Java is a compiled, object-oriented language. You write .java source files, the compiler turns them into bytecode (.class files), and the Java Virtual Machine (JVM) runs that bytecode on any platform. This is why Java's motto is 'Write Once, Run Anywhere'.
public class Main {
public static void main(String[] args) {
System.out.println("Hello from Java!");
}
}
Setting Up: JDK, IDE & Hello World
To write Java you need the JDK (Java Development Kit). You can code in any text editor or an IDE like IntelliJ IDEA or Eclipse. The smallest runnable program is a class with a main method — the famous 'Hello World'.
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Variables & Data Types
Java is statically typed — every variable must declare its type. The main primitive types are int (whole numbers), double (decimals), char (single character), boolean (true/false), and the object type String (text).
public class Main {
public static void main(String[] args) {
int age = 25;
double price = 19.99;
char grade = 'A';
boolean isStudent = true;
String name = "Ali";
System.out.println(name + " is " + age + " years old.");
}
}
Operators
Java operators work like math. Arithmetic operators (+, -, *, /, %) do calculations. Relational operators (==, !=, >, <) compare values. Logical operators (&&, ||, !) combine boolean conditions.
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 3;
System.out.println(a + b);
System.out.println(a / b);
System.out.println(a % b);
System.out.println(a > b);
System.out.println(a == 10 && b == 3);
}
}
Strings & String Methods
String is Java's most-used class. It has many built-in methods: length() returns the character count, toUpperCase() and toLowerCase() change case, and charAt() gets a character at an index.
public class Main {
public static void main(String[] args) {
String text = "Hello Java";
System.out.println(text.length());
System.out.println(text.toUpperCase());
System.out.println(text.charAt(0));
System.out.println(text.substring(0, 5));
}
}
Taking Input with Scanner
The Scanner class reads user input from the keyboard. You create a Scanner object, then use methods like nextLine() for text and nextInt() for numbers. Scanner lives in java.util, so it must be imported.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.println("Hello, " + name);
sc.close();
}
}
Conditionals: if/else & switch
if and else let your program make decisions. switch compares one value against several cases. Both control which code block runs based on conditions.
public class Main {
public static void main(String[] args) {
int score = 85;
if (score >= 90) {
System.out.println("A");
} else if (score >= 70) {
System.out.println("B");
} else {
System.out.println("C");
}
}
}
Loops: for, while, do-while
Loops repeat code. for is used when you know the count. while repeats while a condition is true. do-while always runs at least once because the condition is checked after the body.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
Arrays: Basics
An array stores multiple values of the same type in one variable. Arrays have a fixed length set at creation, and elements are accessed by index starting from 0.
public class Main {
public static void main(String[] args) {
int[] nums = {10, 20, 30, 40};
System.out.println(nums.length);
System.out.println(nums[0]);
System.out.println(nums[3]);
}
}
ArrayList (Dynamic Array)
Unlike regular arrays, ArrayList can grow and shrink. It is part of java.util and provides methods like add(), get(), and size(). ArrayList only stores objects, not primitives directly.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Ali");
names.add("Sara");
System.out.println(names.size());
System.out.println(names.get(0));
}
}
Methods
Methods are reusable blocks of code inside a class. A method has a return type, a name, and optional parameters. void means the method returns nothing.
public class Main {
static void greet(String name) {
System.out.println("Hello, " + name);
}
public static void main(String[] args) {
greet("Ali");
greet("Sara");
}
}
Method Parameters & Return
Parameters pass data into a method. The return keyword sends a value back to the caller. The return type in the method signature must match the returned value's type.
public class Main {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(5, 3);
System.out.println(result);
}
}
Classes & Objects
A class is a blueprint. An object is an instance of that class. Classes define fields (data) and methods (behavior). You create objects with the new keyword.
class Car {
String brand;
int year;
void info() {
System.out.println(brand + " " + year);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.brand = "Toyota";
myCar.year = 2020;
myCar.info();
}
}
Constructors
A constructor initializes an object when it is created. It has the same name as the class and no return type. Constructors can accept parameters to set initial field values.
class Person {
String name;
int age;
Person(String n, int a) {
name = n;
age = a;
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person("Ali", 25);
System.out.println(p.name + " " + p.age);
}
}
Access Modifiers (public, private)
Access modifiers control visibility. public means accessible from anywhere. private means only accessible inside the same class. This is the foundation of encapsulation — hiding internal data.
class BankAccount {
private double balance;
void deposit(double amount) {
balance += amount;
}
double getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.deposit(100);
System.out.println(acc.getBalance());
}
}
Getters & Setters
Getters and setters are methods that read and modify private fields. They give controlled access to data, allowing validation before a value is set. This is a core Java convention.
class Student {
private String name;
public String getName() {
return name;
}
public void setName(String n) {
if (n.length() > 0) {
name = n;
}
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.setName("Ali");
System.out.println(s.getName());
}
}
Static vs Instance Members
Instance members belong to each object. Static members belong to the class itself and are shared by all objects. You access static members with the class name, and instance members with an object.
class Counter {
static int count = 0;
int instanceCount = 0;
void increment() {
count++;
instanceCount++;
}
}
public class Main {
public static void main(String[] args) {
Counter a = new Counter();
Counter b = new Counter();
a.increment();
b.increment();
System.out.println("Static: " + Counter.count);
System.out.println("Instance A: " + a.instanceCount);
System.out.println("Instance B: " + b.instanceCount);
}
}
Wrapper Classes
Each primitive type has a wrapper class: int → Integer, double → Double, char → Character, boolean → Boolean. Wrappers let primitives be used where objects are required, like in ArrayList, and provide utility methods like parseInt().
public class Main {
public static void main(String[] args) {
String text = "42";
int num = Integer.parseInt(text);
Integer obj = num;
System.out.println(num + 10);
System.out.println(obj.toString());
}
}
Type Casting
Casting converts one type to another. Widening (int to double) happens automatically. Narrowing (double to int) requires an explicit cast because data may be lost.
public class Main {
public static void main(String[] args) {
int a = 10;
double b = a;
double c = 9.99;
int d = (int) c;
System.out.println(b);
System.out.println(d);
}
}
Beginner Recap + Mini Projects
You now know Java basics, variables, operators, strings, input, conditionals, loops, arrays, ArrayList, methods, classes, constructors, access modifiers, getters/setters, static members, wrappers, and casting. Apply them in three mini projects: (1) Calculator, (2) Even/Odd Checker, (3) Simple Grade Calculator.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
if (n % 2 == 0) {
System.out.println(n + " is even");
} else {
System.out.println(n + " is odd");
}
sc.close();
}
}
Java Beginner Projects
Apply variables, loops, conditionals, Scanner, and methods. Click each project to open its full guide.
About this project
The computer picks a secret number from 1 to 100. You get 7 attempts to find it. After each guess, the program tells you whether to go higher or lower.
What you'll practice
Step-by-step: How it works
Random.nextInt(100) + 1generates a secret number from 1 to 100.- A
whileloop runs while attempts remain. - Each turn reads a guess using
Scanner.nextInt(). - If the guess is low, the program says "too low"; if high, "too high".
- The loop breaks when the guess matches the secret number.
- If attempts run out, the secret number is revealed.
import java.util.Random;
import java.util.Scanner;
public class NumberGuessing {
public static void main(String[] args) {
Random random = new Random();
Scanner sc = new Scanner(System.in);
int secret = random.nextInt(100) + 1;
int attempts = 7;
System.out.println("Guess the secret number between 1 and 100.");
System.out.println("You have " + attempts + " attempts.\n");
while (attempts > 0) {
System.out.print("Your guess: ");
int guess = sc.nextInt();
attempts--;
if (guess == secret) {
System.out.println("\nCorrect! The secret number is " + secret + ".");
break;
} else if (guess < secret) {
System.out.println("Too low. " + attempts + " attempt(s) left.\n");
} else {
System.out.println("Too high. " + attempts + " attempt(s) left.\n");
}
}
if (attempts == 0) {
System.out.println("Out of attempts! The secret number was " + secret + ".");
}
sc.close();
}
}
About this project
Convert temperatures between Celsius and Fahrenheit. The user picks a direction and enters a value, then the program calculates and prints the result.
What you'll practice
Step-by-step: How it works
- The user picks a direction: C to F or F to C.
Scanner.nextDouble()reads the temperature.- A
switchruns the correct conversion method. - Each method returns the converted value.
printf()prints the result with two decimal places.
import java.util.Scanner;
public class TemperatureConverter {
static double cToF(double c) {
return (c * 9 / 5) + 32;
}
static double fToC(double f) {
return (f - 32) * 5 / 9;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Temperature Converter");
System.out.println("1. Celsius to Fahrenheit");
System.out.println("2. Fahrenheit to Celsius");
System.out.print("Choose (1 or 2): ");
int choice = sc.nextInt();
System.out.print("Enter temperature: ");
double temp = sc.nextDouble();
switch (choice) {
case 1:
System.out.printf("%.2f C = %.2f F%n", temp, cToF(temp));
break;
case 2:
System.out.printf("%.2f F = %.2f C%n", temp, fToC(temp));
break;
default:
System.out.println("Invalid choice.");
}
sc.close();
}
}
About this project
Build a simple calculator that takes two numbers and an operator (+, -, *, /), then prints the result. It handles division by zero with an error message.
What you'll practice
Step-by-step: How it works
- Two numbers and a char operator are read from the user.
- A
switchperforms the matching operation. - Division checks for zero before calculating to avoid an error.
- The result is printed using
printf(). - An invalid operator shows an error message.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
double a = sc.nextDouble();
System.out.print("Enter second number: ");
double b = sc.nextDouble();
System.out.print("Enter operator (+, -, *, /): ");
char op = sc.next().charAt(0);
switch (op) {
case '+':
System.out.printf("%.2f + %.2f = %.2f%n", a, b, a + b);
break;
case '-':
System.out.printf("%.2f - %.2f = %.2f%n", a, b, a - b);
break;
case '*':
System.out.printf("%.2f * %.2f = %.2f%n", a, b, a * b);
break;
case '/':
if (b != 0) {
System.out.printf("%.2f / %.2f = %.2f%n", a, b, a / b);
} else {
System.out.println("Error: Cannot divide by zero.");
}
break;
default:
System.out.println("Invalid operator.");
}
sc.close();
}
}
Beginner Capstone Project
Put everything together — variables, arrays, loops, methods, and classes — in one complete project.
About this project
Build a grade calculator that takes multiple subjects, stores them in an array, calculates the average, and prints a letter grade (A, B, C, D, F) plus pass/fail status.
What you'll practice
Step-by-step: How it works
- The user enters how many subjects and each score.
- Scores are stored in an array.
- A loop sums all scores.
- The average is calculated by dividing the sum by the count.
- Conditionals convert the average into a letter grade.
- The grade and pass/fail status are printed.
import java.util.Scanner;
public class GradeCalculator {
static String getGrade(double avg) {
if (avg >= 90) return "A";
else if (avg >= 80) return "B";
else if (avg >= 70) return "C";
else if (avg >= 60) return "D";
else return "F";
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many subjects? ");
int count = sc.nextInt();
double[] scores = new double[count];
double sum = 0;
for (int i = 0; i < count; i++) {
System.out.print("Enter score for subject " + (i + 1) + ": ");
scores[i] = sc.nextDouble();
sum += scores[i];
}
double average = sum / count;
String grade = getGrade(average);
System.out.printf("%nAverage: %.2f%n", average);
System.out.println("Grade: " + grade);
System.out.println(average >= 60 ? "Result: PASS" : "Result: FAIL");
sc.close();
}
}