40 Basic Java Tutorials
1. Hello World Program
The "Hello World" program is the simplest way to start with Java, printing a message to the console.
Example: Printing "Hello, World!"
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Hello, World!
Note: The main method is the starting point. System.out.println displays text.
2. Variables and Data Types
Variables store data like numbers or text. Java uses types like int, double, and String.
Example: Declaring variables.
public class Variables {
public static void main(String[] args) {
int age = 25;
double height = 5.8;
String name = "Alice";
System.out.println(name + " is " + age + " years old and " + height + " feet tall.");
}
}
Alice is 25 years old and 5.8 feet tall.
Note: Specify the data type before the variable name. Use int for whole numbers, double for decimals.
3. Basic Input/Output
Use Scanner to read user input and System.out.println to display output.
Example: Reading a user's name.
import java.util.Scanner;
public class InputOutput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
}
}
Enter your name:
Bob
Hello, Bob!
Note: Import java.util.Scanner. Use nextLine() for text and nextInt() for numbers.
4. Arithmetic Operations
Java supports basic math operations: addition (+), subtraction (-), multiplication (*), and division (/).
Example: Performing calculations.
public class Arithmetic {
public static void main(String[] args) {
int a = 10;
int b = 2;
System.out.println("Sum: " + (a + b));
System.out.println("Difference: " + (a - b));
System.out.println("Product: " + (a * b));
System.out.println("Quotient: " + (a / b));
}
}
Sum: 12
Difference: 8
Product: 20
Quotient: 5
Note: Avoid division by zero. Use doubles for decimal results.
5. If-Else Statements
If-else statements control program flow based on conditions.
Example: Checking if a number is positive.
public class IfElse {
public static void main(String[] args) {
int num = 7;
if (num > 0) {
System.out.println("Number is positive.");
} else {
System.out.println("Number is not positive.");
}
}
}
Number is positive.
Note: Use else if for multiple conditions. Conditions must evaluate to true or false.
6. Switch Case
Switch case selects a code block based on a variable's value.
Example: Choosing a day.
public class SwitchCase {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 4:
System.out.println("Thursday");
break;
default:
System.out.println("Other day");
}
}
}
Thursday
Note: Use break to exit each case. Default handles unmatched cases.
7. For Loop
For loops repeat code a specific number of times.
Example: Printing numbers 1 to 5.
public class ForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
1
2
3
4
5
Note: For loops have initialization, condition, and update parts. Ideal for known iterations.
8. While Loop
While loops repeat code while a condition is true.
Example: Counting down from 4.
public class WhileLoop {
public static void main(String[] args) {
int count = 4;
while (count > 0) {
System.out.println(count);
count--;
}
}
}
4
3
2
1
Note: Ensure the condition becomes false to avoid infinite loops.
9. Arrays
Arrays store multiple values of the same type in a single variable.
Example: Storing and printing numbers.
public class Arrays {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4};
for (int num : numbers) {
System.out.println(num);
}
}
}
1
2
3
4
Note: Arrays have a fixed size. Use for-each loops for easy iteration.
10. Methods
Methods are reusable code blocks that perform specific tasks.
Example: A method to add numbers.
public class Methods {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int sum = add(5, 3);
System.out.println("Sum: " + sum);
}
}
Sum: 8
Note: Methods can return values. Use 'static' for methods not tied to objects.
11. Classes and Objects
Classes define blueprints for objects, which hold data and behavior.
Example: Creating a simple class.
public class Car {
String color = "Blue";
public static void main(String[] args) {
Car car = new Car();
System.out.println("Car color: " + car.color);
}
}
Car color: Blue
Note: Use 'new' to create objects. Classes can have fields and methods.
12. Constructors
Constructors initialize objects and have the same name as the class.
Example: Using a constructor.
public class Student {
String name;
Student(String n) {
name = n;
}
public static void main(String[] args) {
Student student = new Student("Emma");
System.out.println("Student: " + student.name);
}
}
Student: Emma
Note: Constructors have no return type and are called with 'new'.
13. String Operations
Strings store text and have methods like length() and toUpperCase().
Example: Basic string operations.
public class StringOps {
public static void main(String[] args) {
String text = "Hello";
System.out.println("Length: " + text.length());
System.out.println("Uppercase: " + text.toUpperCase());
}
}
Length: 5
Uppercase: HELLO
Note: Strings are immutable. Use + for concatenation or methods for new strings.
14. ArrayList Basics
ArrayList is a resizable array for dynamic data storage.
Example: Adding elements to an ArrayList.
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
System.out.println("Names: " + names);
}
}
Names: [Alice, Bob]
Note: Import java.util.ArrayList. Use add() and remove() for dynamic lists.
15. Exception Handling
Try-catch blocks handle errors to prevent crashes.
Example: Handling division by zero.
public class Exceptions {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
}
}
Cannot divide by zero!
Note: Use try for risky code and catch for error handling.
16. File Reading
Java reads files using classes like Scanner.
Example: Reading a text file.
import java.io.File;
import java.util.Scanner;
public class FileReading {
public static void main(String[] args) {
try {
File file = new File("input.txt");
Scanner scanner = new Scanner(file);
System.out.println("File content: " + scanner.nextLine());
scanner.close();
} catch (Exception e) {
System.out.println("Error reading file.");
}
}
}
File content: [First line of file]
Note: Close files after reading. Use try-catch for file errors.
17. File Writing
Java writes to files using classes like FileWriter.
Example: Writing to a file.
import java.io.FileWriter;
public class FileWriting {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, Java!");
writer.close();
System.out.println("Wrote to file.");
} catch (Exception e) {
System.out.println("Error writing to file.");
}
}
}
Wrote to file.
Note: Close FileWriter to save changes. Use try-catch for errors.
18. Basic Inheritance
Inheritance lets a class inherit properties and methods from another class.
Example: A subclass inheriting a method.
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
}
}
This animal eats food.
Note: Use 'extends' for inheritance. Subclasses inherit public members.
19. Method Overloading
Method overloading allows multiple methods with the same name but different parameters.
Example: Overloading a method to add numbers.
public class Overloading {
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
System.out.println("Int sum: " + add(3, 4));
System.out.println("Double sum: " + add(3.5, 4.5));
}
}
Int sum: 7
Double sum: 8.0
Note: Java selects the method based on parameter types.
20. Simple Calculator Project
A calculator project combines input, arithmetic, and control flow.
Example: Basic calculator with user input.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter two numbers: ");
double num1 = scanner.nextDouble();
double num2 = scanner.nextDouble();
System.out.println("Enter operation (+, -, *, /): ");
char op = scanner.next().charAt(0);
double result;
switch (op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
System.out.println("Invalid operation!");
return;
}
System.out.println("Result: " + result);
}
}
Enter two numbers:
10 5
Enter operation (+, -, *, /): +
Result: 15.0
Note: This project uses Scanner and switch for a practical application.
21. Do-While Loop
Do-while loops run at least once and continue while a condition is true.
Example: Printing numbers 1 to 3.
public class DoWhileLoop {
public static void main(String[] args) {
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 3);
}
}
1
2
3
Note: The loop body executes before checking the condition.
22. Break and Continue
Break exits a loop, and continue skips to the next iteration.
Example: Using break and continue.
public class BreakContinue {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
if (i == 5) break;
System.out.println(i);
}
}
}
1
2
4
Note: Continue skips the current iteration, break stops the loop.
23. Nested Loops
Nested loops are loops inside loops, useful for patterns.
Example: Printing a triangle pattern.
public class NestedLoops {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
*
* *
* * *
Note: The inner loop runs fully for each outer loop iteration.
24. Boolean Operations
Boolean operations use && (and), || (or), and ! (not) for conditions.
Example: Combining conditions.
public class BooleanOps {
public static void main(String[] args) {
int age = 20;
boolean hasPermit = true;
if (age >= 16 && hasPermit) {
System.out.println("Can drive.");
} else {
System.out.println("Cannot drive.");
}
}
}
Can drive.
Note: && needs both true, || needs one true, ! flips the value.
25. Math Class
The Math class provides methods for calculations like square root or max.
Example: Using Math methods.
public class MathClass {
public static void main(String[] args) {
double num = 25;
System.out.println("Square root: " + Math.sqrt(num));
System.out.println("Max: " + Math.max(10, 20));
}
}
Square root: 5.0
Max: 20
Note: Math is in java.lang, no import needed. Use Math.round() for rounding.
26. Random Numbers
The Random class generates random numbers.
Example: Generating a random number.
import java.util.Random;
public class RandomNumbers {
public static void main(String[] args) {
Random random = new Random();
int num = random.nextInt(10) + 1; // 1 to 10
System.out.println("Random number: " + num);
}
}
Random number: [1-10]
Note: Import java.util.Random. Add 1 to shift range (e.g., 0-9 to 1-10).
27. Method Parameters
Methods can take parameters to process different inputs.
Example: A method with parameters.
public class Parameters {
public static void printInfo(String name, int age) {
System.out.println(name + " is " + age + " years old.");
}
public static void main(String[] args) {
printInfo("Tom", 22);
}
}
Tom is 22 years old.
Note: Parameters act like variables inside the method.
28. Static Variables
Static variables belong to the class and are shared across all objects.
Example: Counting objects with a static variable.
public class StaticVar {
static int count = 0;
StaticVar() {
count++;
}
public static void main(String[] args) {
new StaticVar();
new StaticVar();
System.out.println("Objects created: " + count);
}
}
Objects created: 2
Note: Static variables are accessed without creating objects.
29. Access Modifiers
Access modifiers (public, private, protected) control access to class members.
Example: Using private with a getter.
public class AccessModifiers {
private String secret = "Hidden";
public String getSecret() {
return secret;
}
public static void main(String[] args) {
AccessModifiers obj = new AccessModifiers();
System.out.println("Secret: " + obj.getSecret());
}
}
Secret: Hidden
Note: Private restricts access to the class. Use getters for access.
30. Encapsulation
Encapsulation hides data using private fields and public methods.
Example: Encapsulating a class.
public class Encapsulation {
private int balance;
public void setBalance(int b) {
if (b >= 0) balance = b;
}
public int getBalance() {
return balance;
}
public static void main(String[] args) {
Encapsulation account = new Encapsulation();
account.setBalance(200);
System.out.println("Balance: " + account.getBalance());
}
}
Balance: 200
Note: Encapsulation ensures controlled data access.
31. This Keyword
The 'this' keyword refers to the current object, useful for distinguishing fields.
Example: Using 'this' in a constructor.
public class ThisKeyword {
String name;
ThisKeyword(String name) {
this.name = name;
}
public static void main(String[] args) {
ThisKeyword obj = new ThisKeyword("Sam");
System.out.println("Name: " + obj.name);
}
}
Name: Sam
Note: Use 'this' to avoid confusion between fields and parameters.
32. Method Overriding
Method overriding lets a subclass redefine a parent class method.
Example: Overriding a method.
class Animal {
void sound() {
System.out.println("Generic sound");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Meow");
}
public static void main(String[] args) {
Cat cat = new Cat();
cat.sound();
}
}
Meow
Note: Use the same method signature to override.
33. Abstract Classes
Abstract classes can't be instantiated and may have abstract methods.
Example: Using an abstract class.
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle");
}
public static void main(String[] args) {
Circle circle = new Circle();
circle.draw();
}
}
Drawing a circle
Note: Subclasses must implement abstract methods.
34. Interfaces
Interfaces define methods that classes must implement.
Example: Implementing an interface.
interface Printable {
void print();
}
class Document implements Printable {
public void print() {
System.out.println("Printing document");
}
public static void main(String[] args) {
Document doc = new Document();
doc.print();
}
}
Printing document
Note: Use 'implements' for interfaces. Methods must be public.
35. Packages
Packages organize classes into namespaces.
Example: Using a package.
package mypackage;
public class MyClass {
public static void main(String[] args) {
System.out.println("This is in mypackage.");
}
}
This is in mypackage.
Note: Use 'package' at the file's top. Import other packages with 'import'.
36. Enum Types
Enums define a fixed set of constants.
Example: Using an enum.
public class EnumDemo {
enum Color { RED, BLUE, GREEN }
public static void main(String[] args) {
Color color = Color.BLUE;
System.out.println("Color: " + color);
}
}
Color: BLUE
Note: Enums are great for predefined values like days or colors.
37. StringBuilder
StringBuilder is used for efficient, mutable string operations.
Example: Building a string.
public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("Hi").append(" Java");
System.out.println(sb.toString());
}
}
Hi Java
Note: Use StringBuilder for faster string manipulation, especially in loops.
38. Date and Time
LocalDate handles dates in Java.
Example: Getting the current date.
import java.time.LocalDate;
public class DateTime {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
System.out.println("Current date: " + date);
}
}
Current date: [Today's date]
Note: Import java.time.LocalDate. Use LocalDateTime for date and time.
39. HashMap Basics
HashMap stores key-value pairs for quick lookup.
Example: Using a HashMap.
import java.util.HashMap;
public class HashMapDemo {
public static void main(String[] args) {
HashMap grades = new HashMap<>();
grades.put("Alice", 95);
grades.put("Bob", 80);
System.out.println("Bob's grade: " + grades.get("Bob"));
}
}
Bob's grade: 80
Note: Import java.util.HashMap. Use put() to add and get() to retrieve.
40. Number Guessing Game
A number guessing game combines input, loops, and conditions for an interactive project.
Example: Guessing a random number.
import java.util.Random;
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
Random random = new Random();
int number = random.nextInt(10) + 1;
Scanner scanner = new Scanner(System.in);
System.out.println("Guess a number (1-10): ");
int guess;
do {
guess = scanner.nextInt();
if (guess < number) {
System.out.println("Too low! Try again: ");
} else if (guess > number) {
System.out.println("Too high! Try again: ");
}
} while (guess != number);
System.out.println("Correct! The number was " + number);
}
}
Guess a number (1-10):
5
Too low! Try again:
7
Correct! The number was 7
Note: This project uses Random, Scanner, and loops for a fun game.