Introduction
Java is one of the oldest and most popular programming languages in the world. It is a general-purpose programming language, which means you can do with it everything... well, maybe not everything, but almost everything :)
With Java, you can do Android Mobile Development, Enterprise Applications, Web Applications, Big Data Technologies, Cloud-Based Applications, Financial Services, Scientific Applications, Game Development, Internet of Things (IoT), and other stuff... In this tutorial, you'll learn Java fundamentals and build practical projects along the way.
What you'll learn:
- Java basics and syntax
- Object-Oriented Programming concepts
- Working with collections and data structures
- File handling and exception management
- Building a real-world console application
Prerequisites: Basic computer literacy. No prior programming experience required!
Part 1: Setting Up Your Java Environment
Installing Java Development Kit (JDK)
- Download the latest JDK from Oracle or OpenJDK
- Install and verify by opening terminal/command prompt:
java -version
javac -version
Choosing an IDE
Go with one of these:
- IntelliJ IDEA Community Edition (beginner-friendly and my favorite!)
- Eclipse (lightweight)
- VS Code with Java extensions (if you're already familiar with VS Code)
Part 2: Your First Java Program
Let's start now with the classic "Hello, World!" program:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Breaking it down:
-
public class HelloWorld- Defines a class named HelloWorld -
public static void main(String[] args)- The entry point of every Java program -
System.out.println()- Prints text to the console
To run:
- Save as
HelloWorld.java - Compile:
javac HelloWorld.java - Run:
java HelloWorld
Part 3: Java Fundamentals
Variables and Data Types
Java is statically typed, meaning you must declare variable types:
public class DataTypes {
public static void main(String[] args) {
// Primitive types
int age = 25;
double price = 19.99;
boolean isActive = true;
char grade = 'A';
// String (reference type)
String name = "Alice";
// Printing variables
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Price: $" + price);
}
}
Common data types:
-
int- integers (whole numbers) -
double- decimal numbers -
boolean- true/false -
char- single character -
String- text
Operators
public class Operators {
public static void main(String[] args) {
int a = 10, b = 3;
// Arithmetic operators
System.out.println("Addition: " + (a + b)); // 13
System.out.println("Subtraction: " + (a - b)); // 7
System.out.println("Multiplication: " + (a * b)); // 30
System.out.println("Division: " + (a / b)); // 3
System.out.println("Modulus: " + (a % b)); // 1
// Comparison operators
System.out.println("Is equal: " + (a == b)); // false
System.out.println("Is greater: " + (a > b)); // true
// Logical operators
boolean x = true, y = false;
System.out.println("AND: " + (x && y)); // false
System.out.println("OR: " + (x || y)); // true
System.out.println("NOT: " + (!x)); // false
}
}
Part 4: Control Flow
If-Else Statements
public class ControlFlow {
public static void main(String[] args) {
int score = 85;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}
}
}
Loops
public class Loops {
public static void main(String[] args) {
// For loop
System.out.println("For loop:");
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
// While loop
System.out.println("\nWhile loop:");
int j = 1;
while (j <= 5) {
System.out.println("Count: " + j);
j++;
}
// Enhanced for loop (for arrays)
System.out.println("\nEnhanced for loop:");
String[] fruits = {"Apple", "Banana", "Orange"};
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
Switch Statement
public class SwitchExample {
public static void main(String[] args) {
String day = "Monday";
switch (day) {
case "Monday":
System.out.println("Start of the work week!");
break;
case "Friday":
System.out.println("Almost weekend!");
break;
case "Saturday":
case "Sunday":
System.out.println("Weekend!");
break;
default:
System.out.println("Midweek day");
}
}
}
Part 5: Methods and Functions
Methods help organize code into reusable blocks:
public class Methods {
// Method with no parameters and no return value
public static void greet() {
System.out.println("Hello!");
}
// Method with parameters
public static void greetUser(String name) {
System.out.println("Hello, " + name + "!");
}
// Method with return value
public static int add(int a, int b) {
return a + b;
}
// Method with multiple parameters and return value
public static double calculateArea(double length, double width) {
return length * width;
}
public static void main(String[] args) {
greet();
greetUser("Alice");
int sum = add(5, 3);
System.out.println("Sum: " + sum);
double area = calculateArea(5.5, 3.2);
System.out.println("Area: " + area);
}
}
Part 6: Object-Oriented Programming (OOP)
Classes and Objects
Java is an object-oriented language. Everything revolves around objects:
// Define a class
class Car {
// Properties (fields)
String brand;
String model;
int year;
// Constructor
public Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}
// Method
public void displayInfo() {
System.out.println(year + " " + brand + " " + model);
}
public void honk() {
System.out.println("Beep beep!");
}
}
public class OOPExample {
public static void main(String[] args) {
// Create objects
Car car1 = new Car("Toyota", "Camry", 2023);
Car car2 = new Car("Honda", "Civic", 2022);
// Use objects
car1.displayInfo();
car1.honk();
car2.displayInfo();
}
}
Encapsulation (Getters and Setters)
class BankAccount {
// Private fields (encapsulated)
private String accountNumber;
private double balance;
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
// Getter methods
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
// Setter with validation
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: $" + amount);
} else {
System.out.println("Invalid deposit amount");
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
} else {
System.out.println("Invalid withdrawal amount");
}
}
}
public class EncapsulationDemo {
public static void main(String[] args) {
BankAccount account = new BankAccount("123456", 1000.0);
System.out.println("Balance: $" + account.getBalance());
account.deposit(500);
account.withdraw(200);
System.out.println("Final balance: $" + account.getBalance());
}
}
Inheritance
// Parent class
class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " is eating");
}
public void sleep() {
System.out.println(name + " is sleeping");
}
}
// Child class
class Dog extends Animal {
public Dog(String name) {
super(name); // Call parent constructor
}
public void bark() {
System.out.println(name + " says: Woof!");
}
}
class Cat extends Animal {
public Cat(String name) {
super(name);
}
public void meow() {
System.out.println(name + " says: Meow!");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
Dog dog = new Dog("Buddy");
dog.eat();
dog.bark();
Cat cat = new Cat("Whiskers");
cat.sleep();
cat.meow();
}
}
Polymorphism
class Shape {
public void draw() {
System.out.println("Drawing a shape");
}
public double getArea() {
return 0;
}
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing a circle");
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
@Override
public double getArea() {
return width * height;
}
}
public class PolymorphismDemo {
public static void main(String[] args) {
// Polymorphism: treating different objects through same interface
Shape[] shapes = {
new Circle(5),
new Rectangle(4, 6),
new Circle(3)
};
for (Shape shape : shapes) {
shape.draw();
System.out.println("Area: " + shape.getArea());
System.out.println();
}
}
}
Part 7: Arrays and Collections
Arrays
public class ArraysDemo {
public static void main(String[] args) {
// Declare and initialize array
int[] numbers = {1, 2, 3, 4, 5};
// Access elements
System.out.println("First element: " + numbers[0]);
// Array length
System.out.println("Length: " + numbers.length);
// Iterate through array
for (int i = 0; i < numbers.length; i++) {
System.out.println("numbers[" + i + "] = " + numbers[i]);
}
// 2D array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("Element at [1][2]: " + matrix[1][2]); // 6
}
}
ArrayList
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
// Create ArrayList
ArrayList<String> fruits = new ArrayList<>();
// Add elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// Access elements
System.out.println("First fruit: " + fruits.get(0));
// Size
System.out.println("Size: " + fruits.size());
// Iterate
for (String fruit : fruits) {
System.out.println(fruit);
}
// Remove element
fruits.remove("Banana");
// Check if contains
if (fruits.contains("Apple")) {
System.out.println("We have apples!");
}
}
}
HashMap
import java.util.HashMap;
public class HashMapDemo {
public static void main(String[] args) {
// Create HashMap
HashMap<String, Integer> scores = new HashMap<>();
// Add key-value pairs
scores.put("Alice", 95);
scores.put("Bob", 87);
scores.put("Charlie", 92);
// Get value by key
System.out.println("Alice's score: " + scores.get("Alice"));
// Iterate through HashMap
for (String name : scores.keySet()) {
System.out.println(name + ": " + scores.get(name));
}
// Check if key exists
if (scores.containsKey("Bob")) {
System.out.println("Bob is in the system");
}
}
}
Part 8: Exception Handling
public class ExceptionHandling {
public static void main(String[] args) {
// Try-catch block
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
}
// Multiple catch blocks
try {
String text = null;
System.out.println(text.length());
} catch (NullPointerException e) {
System.out.println("Error: Null reference!");
} catch (Exception e) {
System.out.println("Some other error occurred");
} finally {
System.out.println("This always executes");
}
}
public static int divide(int a, int b) {
return a / b;
}
}
Custom Exceptions
// Custom exception class
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
class BankAccountAdvanced {
private double balance;
public BankAccountAdvanced(double balance) {
this.balance = balance;
}
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(
"Insufficient funds. Balance: $" + balance + ", Requested: $" + amount
);
}
balance -= amount;
System.out.println("Withdrawn: $" + amount);
}
public double getBalance() {
return balance;
}
}
public class CustomExceptionDemo {
public static void main(String[] args) {
BankAccountAdvanced account = new BankAccountAdvanced(100);
try {
account.withdraw(150);
} catch (InsufficientFundsException e) {
System.out.println("Transaction failed: " + e.getMessage());
}
}
}
Part 9: File Handling
import java.io.*;
import java.util.Scanner;
public class FileHandling {
// Writing to a file
public static void writeToFile(String filename, String content) {
try {
FileWriter writer = new FileWriter(filename);
writer.write(content);
writer.close();
System.out.println("Successfully wrote to file");
} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
}
}
// Reading from a file
public static void readFromFile(String filename) {
try {
File file = new File(filename);
Scanner reader = new Scanner(file);
while (reader.hasNextLine()) {
String line = reader.nextLine();
System.out.println(line);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
public static void main(String[] args) {
String filename = "example.txt";
// Write to file
writeToFile(filename, "Hello, Java!\nThis is file handling in action.");
// Read from file
System.out.println("Reading from file:");
readFromFile(filename);
}
}
Part 10: Real-World Project - Task Manager Application
Let's build a complete console-based task manager:
import java.util.ArrayList;
import java.util.Scanner;
class Task {
private String title;
private String description;
private boolean completed;
public Task(String title, String description) {
this.title = title;
this.description = description;
this.completed = false;
}
public String getTitle() { return title; }
public String getDescription() { return description; }
public boolean isCompleted() { return completed; }
public void setCompleted(boolean completed) {
this.completed = completed;
}
@Override
public String toString() {
String status = completed ? "[✓]" : "[ ]";
return status + " " + title + " - " + description;
}
}
class TaskManager {
private ArrayList<Task> tasks;
public TaskManager() {
tasks = new ArrayList<>();
}
public void addTask(String title, String description) {
tasks.add(new Task(title, description));
System.out.println("Task added successfully!");
}
public void listTasks() {
if (tasks.isEmpty()) {
System.out.println("No tasks found.");
return;
}
System.out.println("\n===== YOUR TASKS =====");
for (int i = 0; i < tasks.size(); i++) {
System.out.println((i + 1) + ". " + tasks.get(i));
}
System.out.println("======================\n");
}
public void completeTask(int index) {
if (index >= 0 && index < tasks.size()) {
tasks.get(index).setCompleted(true);
System.out.println("Task marked as complete!");
} else {
System.out.println("Invalid task number.");
}
}
public void deleteTask(int index) {
if (index >= 0 && index < tasks.size()) {
tasks.remove(index);
System.out.println("Task deleted!");
} else {
System.out.println("Invalid task number.");
}
}
}
public class TaskManagerApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
TaskManager manager = new TaskManager();
boolean running = true;
System.out.println("===== TASK MANAGER =====");
while (running) {
System.out.println("\nOptions:");
System.out.println("1. Add Task");
System.out.println("2. List Tasks");
System.out.println("3. Complete Task");
System.out.println("4. Delete Task");
System.out.println("5. Exit");
System.out.print("Choose an option: ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (choice) {
case 1:
System.out.print("Enter task title: ");
String title = scanner.nextLine();
System.out.print("Enter task description: ");
String description = scanner.nextLine();
manager.addTask(title, description);
break;
case 2:
manager.listTasks();
break;
case 3:
manager.listTasks();
System.out.print("Enter task number to complete: ");
int completeIndex = scanner.nextInt() - 1;
manager.completeTask(completeIndex);
break;
case 4:
manager.listTasks();
System.out.print("Enter task number to delete: ");
int deleteIndex = scanner.nextInt() - 1;
manager.deleteTask(deleteIndex);
break;
case 5:
System.out.println("Goodbye!");
running = false;
break;
default:
System.out.println("Invalid option. Try again.");
}
}
scanner.close();
}
}
Best Practices and Tips
1. Naming Conventions
- Classes: Use PascalCase (e.g., MyClass, BankAccount)
- Methods and variables: Use camelCase (e.g., calculateTotal, userName)
- Constants: Use UPPER_SNAKE_CASE (e.g., MAX_SIZE, DEFAULT_VALUE)
2. Code Organization
- One public class per file
- File name must match the public class name
- Use packages to organize related classes
3. Comments and Documentation
/**
* Calculates the factorial of a number
* @param n the number to calculate factorial for
* @return the factorial of n
*/
public static long factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
4. Always Use Try-With-Resources
// Good practice - automatically closes resources
try (Scanner scanner = new Scanner(new File("data.txt"))) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
What's Next?
Now that you've learned Java fundamentals, here are some paths to explore:
- Web Development: Learn Spring Boot for building web applications
- Android Development: Create mobile apps with Android Studio
- Data Structures & Algorithms: Deepen your problem-solving skills
- Design Patterns: Learn common solutions to recurring problems
- Testing: Explore JUnit for unit testing
Recommended Resources
- Official Java Documentation: docs.oracle.com/javase
- Practice coding: LeetCode, HackerRank, Codewars
- Java communities: r/learnjava, Stack Overflow
Conclusion
Congratulations! You've learned Java from the basics to building a real application. The key to mastering Java is practice, practice, practice, and practice. Try building your own projects. Start with small ones and go up in size. Also, open an account on GitHub (Free!) and put all your learning and projects there for everybody to see! Don't forget to contribute to open-source, and keep coding every day.
What will you build with Java? Drop a comment below and share your projects!
Happy coding! ☕
If you found this tutorial helpful, please give it a ❤️ and follow for more programming tutorials!
About the Author
Deividas Strole is a Full-Stack Developer based in California, specializing in Java, Spring Boot, JavaScript, React, SQL, and AI-driven development. He writes about software engineering, modern full-stack development, and digital marketing strategies.
Connect with me:
Top comments (0)