Java Mastery Guide
Complete guide from beginner to enterprise level
The Complete Java Mastery Guide
A comprehensive journey through Java fundamentals, OOP concepts, and enterprise development patterns.
Understanding Java: The Enterprise Workhorse
Java is a robust, object-oriented programming language designed for building enterprise-scale applications. Created by James Gosling at Sun Microsystems in 1995, Java's "write once, run anywhere" philosophy revolutionized software development by enabling cross-platform compatibility through the Java Virtual Machine (JVM).
Java is known for its strong typing, automatic memory management (garbage collection), and extensive ecosystem. It powers everything from Android mobile apps to large-scale enterprise systems, web applications, and big data technologies.
Enterprise Power: Over 90% of Fortune 500 companies use Java for their backend systems. Java's stability and scalability make it ideal for mission-critical applications.
1. Java Basics & Syntax
Hello World: Your First Java Program
// HelloWorld.java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); System.out.println("Welcome to Java Programming!"); } } // Compile and run: // javac HelloWorld.java // java HelloWorld
Variables and Data Types
public class VariablesExample { public static void main(String[] args) { // Primitive data types byte age = 25; // 8-bit integer short year = 2024; // 16-bit integer int population = 8000000; // 32-bit integer long distance = 123456789L; // 64-bit integer float price = 19.99f; // 32-bit floating point double salary = 75000.50; // 64-bit floating point char grade = 'A'; // Single character boolean isJavaFun = true; // true or false // Reference data types String name = "John Doe"; // String object int[] numbers = {1, 2, 3, 4, 5}; // Array System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Grade: " + grade); } }
Operators and Expressions
public class OperatorsExample { public static void main(String[] args) { int a = 10, b = 3; // Arithmetic operators System.out.println("a + b = " + (a + b)); // 13 System.out.println("a - b = " + (a - b)); // 7 System.out.println("a * b = " + (a * b)); // 30 System.out.println("a / b = " + (a / b)); // 3 System.out.println("a % b = " + (a % b)); // 1 // Comparison operators System.out.println("a == b: " + (a == b)); // false System.out.println("a != b: " + (a != b)); // true System.out.println("a > b: " + (a > b)); // true // Logical operators boolean x = true, y = false; System.out.println("x && y: " + (x && y)); // false System.out.println("x || y: " + (x || y)); // true System.out.println("!x: " + (!x)); // false // Assignment operators int c = 5; c += 3; // c = c + 3 System.out.println("c after += 3: " + c); // 8 } }
Control Flow: Conditionals and Loops
public class ControlFlow { public static void main(String[] args) { int score = 85; // If-else if-else statement 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"); } // Switch statement String day = "Monday"; switch (day) { case "Monday": System.out.println("Start of work week"); break; case "Friday": System.out.println("Weekend is coming!"); break; default: System.out.println("Regular day"); } // For loop System.out.println("Counting 1 to 5:"); for (int i = 1; i <= 5; i++) { System.out.println("Count: " + i); } // While loop int count = 1; System.out.println("While loop:"); while (count <= 3) { System.out.println("Count: " + count); count++; } // Enhanced for loop (for arrays/collections) int[] numbers = {10, 20, 30, 40, 50}; System.out.println("Enhanced for loop:"); for (int number : numbers) { System.out.println("Number: " + number); } } }
Methods: Reusable Code Blocks
public class MethodsExample { // Method with no return value public static void greet(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 public static double calculateBMI(double weight, double height) { return weight / (height * height); } // Method overloading (same name, different parameters) public static int multiply(int a, int b) { return a * b; } public static double multiply(double a, double b) { return a * b; } // Recursive method public static int factorial(int n) { if (n == 0 || n == 1) { return 1; } return n * factorial(n - 1); } public static void main(String[] args) { greet("Alice"); int sum = add(5, 3); System.out.println("5 + 3 = " + sum); double bmi = calculateBMI(68.5, 1.75); System.out.println("BMI: " + bmi); System.out.println("5 * 3 = " + multiply(5, 3)); System.out.println("5.5 * 3.2 = " + multiply(5.5, 3.2)); System.out.println("Factorial of 5: " + factorial(5)); } }
2. Object-Oriented Programming
Classes and Objects
// Student.java public class Student { // Fields (instance variables) private String name; private int age; private String major; // Constructor public Student(String name, int age, String major) { this.name = name; this.age = age; this.major = major; } // Methods public void displayInfo() { System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Major: " + major); } // Getter and Setter methods public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { if (age > 0) { this.age = age; } } } // Main.java public class Main { public static void main(String[] args) { // Creating objects Student student1 = new Student("Alice", 20, "Computer Science"); Student student2 = new Student("Bob", 22, "Mathematics"); // Using object methods student1.displayInfo(); student2.displayInfo(); // Using getters and setters student1.setAge(21); System.out.println(student1.getName() + " is now " + student1.getAge() + " years old"); } }
Inheritance and Polymorphism
// Base class class Animal { protected String name; public Animal(String name) { this.name = name; } public void makeSound() { System.out.println("Animal makes a sound"); } public void eat() { System.out.println(name + " is eating"); } } // Derived class class Dog extends Animal { private String breed; public Dog(String name, String breed) { super(name); // Call parent constructor this.breed = breed; } // Method overriding @Override public void makeSound() { System.out.println(name + " barks: Woof! Woof!"); } // Additional method public void fetch() { System.out.println(name + " is fetching the ball"); } } class Cat extends Animal { public Cat(String name) { super(name); } @Override public void makeSound() { System.out.println(name + " meows: Meow!"); } } // Main class public class InheritanceExample { public static void main(String[] args) { Animal myDog = new Dog("Buddy", "Golden Retriever"); Animal myCat = new Cat("Whiskers"); // Polymorphism in action myDog.makeSound(); // Calls Dog's makeSound myCat.makeSound(); // Calls Cat's makeSound myDog.eat(); // Calls Animal's eat method // Type casting if (myDog instanceof Dog) { Dog dog = (Dog) myDog; dog.fetch(); } } }
Abstraction and Interfaces
// Interface interface Vehicle { void start(); void stop(); double getFuelLevel(); // Default method (Java 8+) default void honk() { System.out.println("Beep beep!"); } // Static method static void displayVehicleInfo() { System.out.println("This is a vehicle interface"); } } // Abstract class abstract class AbstractVehicle implements Vehicle { protected double fuelLevel; protected boolean isRunning; public AbstractVehicle(double initialFuel) { this.fuelLevel = initialFuel; this.isRunning = false; } @Override public void start() { if (fuelLevel > 0) { isRunning = true; System.out.println("Vehicle started"); } else { System.out.println("Cannot start - out of fuel"); } } @Override public void stop() { isRunning = false; System.out.println("Vehicle stopped"); } @Override public double getFuelLevel() { return fuelLevel; } // Abstract method - must be implemented by subclasses public abstract void refuel(double amount); } // Concrete class class Car extends AbstractVehicle { private String model; public Car(String model, double initialFuel) { super(initialFuel); this.model = model; } @Override public void refuel(double amount) { fuelLevel += amount; System.out.println("Refueled " + amount + " liters"); } public void drive() { if (isRunning) { fuelLevel -= 0.1; System.out.println(model + " is driving"); } } } // Main class public class AbstractionExample { public static void main(String[] args) { Car myCar = new Car("Toyota Camry", 10.0); Vehicle.displayVehicleInfo(); // Static method call myCar.start(); myCar.drive(); myCar.honk(); // Default method myCar.stop(); System.out.println("Fuel level: " + myCar.getFuelLevel()); myCar.refuel(5.0); } }
Encapsulation and Access Modifiers
public class BankAccount { // Private fields - encapsulated data private String accountNumber; private double balance; private String accountHolder; // Public constructor public BankAccount(String accountNumber, String accountHolder, double initialBalance) { this.accountNumber = accountNumber; this.accountHolder = accountHolder; this.balance = initialBalance; } // Public methods - controlled access to private data 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 or insufficient funds"); } } public double getBalance() { return balance; } public String getAccountInfo() { return "Account: " + accountNumber + ", Holder: " + accountHolder; } // Private helper method - internal use only private void logTransaction(String type, double amount) { System.out.println("Logged: " + type + " $" + amount); } } // Main class public class EncapsulationExample { public static void main(String[] args) { BankAccount account = new BankAccount("123456", "John Doe", 1000.0); System.out.println(account.getAccountInfo()); System.out.println("Initial balance: $" + account.getBalance()); account.deposit(500.0); account.withdraw(200.0); account.withdraw(2000.0); // Should fail System.out.println("Final balance: $" + account.getBalance()); // This would cause compilation error - private access // account.balance = 1000000; // Error! // account.accountNumber = "999999"; // Error! } }
3. Collections Framework
Lists: ArrayList and LinkedList
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class ListExamples { public static void main(String[] args) { // ArrayList example List<String> arrayList = new ArrayList<>(); arrayList.add("Apple"); arrayList.add("Banana"); arrayList.add("Orange"); arrayList.add("Apple"); // Duplicates allowed System.out.println("ArrayList: " + arrayList); System.out.println("Element at index 1: " + arrayList.get(1)); System.out.println("Size: " + arrayList.size()); // LinkedList example List<Integer> linkedList = new LinkedList<>(); linkedList.add(10); linkedList.add(20); linkedList.add(30); linkedList.addFirst(5); // Add at beginning linkedList.addLast(40); // Add at end System.out.println("LinkedList: " + linkedList); // Iterating through lists System.out.println("Iterating with for-each:"); for (String fruit : arrayList) { System.out.println("Fruit: " + fruit); } System.out.println("Iterating with for loop:"); for (int i = 0; i < arrayList.size(); i++) { System.out.println("Index " + i + ": " + arrayList.get(i)); } // List operations arrayList.remove("Banana"); arrayList.set(1, "Grape"); System.out.println("Modified ArrayList: " + arrayList); // Checking list properties System.out.println("Contains 'Apple': " + arrayList.contains("Apple")); System.out.println("Is empty: " + arrayList.isEmpty()); } }
Maps: HashMap and TreeMap
import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class MapExamples { public static void main(String[] args) { // HashMap example - no guaranteed order Map<String, Integer> studentGrades = new HashMap<>(); studentGrades.put("Alice", 85); studentGrades.put("Bob", 92); studentGrades.put("Charlie", 78); studentGrades.put("Diana", 95); System.out.println("HashMap: " + studentGrades); System.out.println("Alice's grade: " + studentGrades.get("Alice")); System.out.println("Contains key 'Bob': " + studentGrades.containsKey("Bob")); // TreeMap example - sorted by keys Map<String, Integer> sortedGrades = new TreeMap<>(studentGrades); System.out.println("TreeMap (sorted): " + sortedGrades); // Iterating through maps System.out.println("All students and grades:"); for (Map.Entry<String, Integer> entry : studentGrades.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } // Just keys System.out.println("Students: " + studentGrades.keySet()); // Just values System.out.println("Grades: " + studentGrades.values()); // Map operations studentGrades.put("Alice", 90); // Update existing key studentGrades.remove("Charlie"); System.out.println("Updated HashMap: " + studentGrades); // Compute if absent studentGrades.computeIfAbsent("Eve", k -> 88); System.out.println("After computeIfAbsent: " + studentGrades); } }
Sets: HashSet and TreeSet
import java.util.HashSet; import java.util.Set; import java.util.TreeSet; public class SetExamples { public static void main(String[] args) { // HashSet example - no guaranteed order Set<String> hashSet = new HashSet<>(); hashSet.add("Apple"); hashSet.add("Banana"); hashSet.add("Orange"); hashSet.add("Apple"); // Duplicate - won't be added System.out.println("HashSet: " + hashSet); System.out.println("Size: " + hashSet.size()); System.out.println("Contains 'Banana': " + hashSet.contains("Banana")); // TreeSet example - sorted order Set<Integer> treeSet = new TreeSet<>(); treeSet.add(5); treeSet.add(2); treeSet.add(8); treeSet.add(1); treeSet.add(5); // Duplicate - won't be added System.out.println("TreeSet (sorted): " + treeSet); // Set operations Set<String> fruits1 = new HashSet<>(); fruits1.add("Apple"); fruits1.add("Banana"); fruits1.add("Orange"); Set<String> fruits2 = new HashSet<>(); fruits2.add("Banana"); fruits2.add("Grape"); fruits2.add("Mango"); // Union Set<String> union = new HashSet<>(fruits1); union.addAll(fruits2); System.out.println("Union: " + union); // Intersection Set<String> intersection = new HashSet<>(fruits1); intersection.retainAll(fruits2); System.out.println("Intersection: " + intersection); // Difference Set<String> difference = new HashSet<>(fruits1); difference.removeAll(fruits2); System.out.println("Difference (fruits1 - fruits2): " + difference); // Iterating through sets System.out.println("All fruits in union:"); for (String fruit : union) { System.out.println("Fruit: " + fruit); } } }
💻 Java Practice Projects
Beginner Level
- 1Create a Student Management System with CRUD operations
- 2Build a Simple Bank Account application with deposit/withdraw
- 3Implement a Temperature Converter between Celsius and Fahrenheit
- 4Create a Number Guessing Game with user input
- 5Build a Simple Calculator with basic arithmetic operations
Intermediate Level
- 1Develop a Library Management System with books and members
- 2Create an Employee Payroll System with inheritance
- 3Build a Shopping Cart application using Collections
- 4Implement a File Reader/Writer utility with exception handling
- 5Create a Multi-threaded Number Counter
Advanced Level
- 1Build a REST API using Spring Boot
- 2Create a Database CRUD application with JDBC
- 3Implement a Custom Collection with generics
- 4Develop a Simple Web Server using sockets
- 5Build a Dependency Injection Framework
📋 Java Quick Reference
Data Types
- •byte: 8-bit integer
- •short: 16-bit integer
- •int: 32-bit integer
- •long: 64-bit integer
- •float: 32-bit floating point
- •double: 64-bit floating point
- •char: 16-bit Unicode
- •boolean: true/false
Common Methods
- •String.length() - get string length
- •Arrays.sort() - sort array
- •List.add() - add to list
- •Map.put() - add to map
- •Set.contains() - check membership
- •System.out.println() - print output
Master Java for Enterprise Success!
Java remains one of the most sought-after skills in the software industry. Its robustness, scalability, and extensive ecosystem make it ideal for building mission-critical enterprise applications.
Continue your journey by exploring Spring Framework, microservices architecture, and cloud-native Java development to become a full-stack Java developer.