Tools
Tools: Complete Java Tutorial: From Zero to Building Real Applications
2026-02-01
0 views
admin
Introduction ## Part 1: Setting Up Your Java Environment ## Part 2: Your First Java Program ## Part 3: Java Fundamentals ## Part 4: Control Flow ## Part 5: Methods and Functions ## Part 6: Object-Oriented Programming (OOP) ## Part 7: Arrays and Collections ## Part 8: Exception Handling ## Part 9: File Handling ## Part 10: Real-World Project - Task Manager Application ## Best Practices and Tips 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. Prerequisites: Basic computer literacy. No prior programming experience required! Installing Java Development Kit (JDK) Choosing an IDE
Go with one of these: Let's start now with the classic "Hello, World!" program: Variables and Data Types
Java is statically typed, meaning you must declare variable types: Methods help organize code into reusable blocks: Classes and Objects
Java is an object-oriented language. Everything revolves around objects: Encapsulation (Getters and Setters) Let's build a complete console-based task manager: 1. Naming Conventions 3. Comments and Documentation 4. Always Use Try-With-Resources What's Next?
Now that you've learned Java fundamentals, here are some paths to explore: Recommended Resources 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! Templates let you quickly answer FAQs or store snippets for re-use. Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well For further actions, you may consider blocking this person and/or reporting abuse CODE_BLOCK:
java -version
javac -version Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
java -version
javac -version CODE_BLOCK:
java -version
javac -version CODE_BLOCK:
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); }
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); }
} CODE_BLOCK:
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); }
} CODE_BLOCK:
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); }
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
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); }
} CODE_BLOCK:
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); }
} COMMAND_BLOCK:
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 }
} Enter fullscreen mode Exit fullscreen mode COMMAND_BLOCK:
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 }
} COMMAND_BLOCK:
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 }
} CODE_BLOCK:
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"); } }
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
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"); } }
} CODE_BLOCK:
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"); } }
} CODE_BLOCK:
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); } }
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
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); } }
} CODE_BLOCK:
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); } }
} CODE_BLOCK:
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"); } }
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
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"); } }
} CODE_BLOCK:
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"); } }
} CODE_BLOCK:
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); }
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
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); }
} CODE_BLOCK:
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); }
} CODE_BLOCK:
// 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(); }
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
// 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(); }
} CODE_BLOCK:
// 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(); }
} COMMAND_BLOCK:
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()); }
} Enter fullscreen mode Exit fullscreen mode COMMAND_BLOCK:
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()); }
} COMMAND_BLOCK:
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()); }
} CODE_BLOCK:
// 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(); }
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
// 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(); }
} CODE_BLOCK:
// 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(); }
} CODE_BLOCK:
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(); } }
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
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(); } }
} CODE_BLOCK:
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(); } }
} CODE_BLOCK:
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 }
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
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 }
} CODE_BLOCK:
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 }
} COMMAND_BLOCK:
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!"); } }
} Enter fullscreen mode Exit fullscreen mode COMMAND_BLOCK:
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!"); } }
} COMMAND_BLOCK:
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!"); } }
} COMMAND_BLOCK:
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"); } }
} Enter fullscreen mode Exit fullscreen mode COMMAND_BLOCK:
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"); } }
} COMMAND_BLOCK:
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"); } }
} CODE_BLOCK:
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; }
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
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; }
} CODE_BLOCK:
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; }
} COMMAND_BLOCK:
// 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()); } }
} Enter fullscreen mode Exit fullscreen mode COMMAND_BLOCK:
// 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()); } }
} COMMAND_BLOCK:
// 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()); } }
} CODE_BLOCK:
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); }
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
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); }
} CODE_BLOCK:
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); }
} COMMAND_BLOCK:
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(); }
} Enter fullscreen mode Exit fullscreen mode COMMAND_BLOCK:
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(); }
} COMMAND_BLOCK:
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(); }
} CODE_BLOCK:
/** * 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);
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
/** * 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);
} CODE_BLOCK:
/** * 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);
} CODE_BLOCK:
// 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();
} Enter fullscreen mode Exit fullscreen mode CODE_BLOCK:
// 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();
} CODE_BLOCK:
// 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();
} - 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 - Download the latest JDK from Oracle or OpenJDK
- Install and verify by opening terminal/command prompt: - IntelliJ IDEA Community Edition (beginner-friendly and my favorite!)
- Eclipse (lightweight)
- VS Code with Java extensions (if you're already familiar with VS Code) - 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 - Save as HelloWorld.java
- Compile: javac HelloWorld.java
- Run: java HelloWorld - int - integers (whole numbers)
- double - decimal numbers
- boolean - true/false
- char - single character
- String - text - 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) - One public class per file
- File name must match the public class name
- Use packages to organize related classes - 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 - Official Java Documentation: docs.oracle.com/javase
- Practice coding: LeetCode, HackerRank, Codewars
- Java communities: r/learnjava, Stack Overflow
how-totutorialguidedev.toaiswitchgitgithub