Home / Java / Java Basics: Part 2 - Building on Your Foundation

Java Basics: Part 2 - Building on Your Foundation

Java Basics: Part 2 - Building on Your Foundation

Great job getting comfortable with the basics! Now that you understand classes, variables, and simple control flow, let's dive deeper into more advanced concepts that will make your Java programs much more powerful.

Arrays - Storing Multiple Values

Arrays allow you to store multiple values of the same type in one place:

public class Arrays {
    public static void main(String[] args) {
        // Creating an array of integers
        int[] numbers = {1, 2, 3, 4, 5};
        
        // Alternative way to create arrays
        String[] names = new String[3];
        names[0] = "Alice";
        names[1] = "Bob";
        names[2] = "Charlie";
        
        // Accessing array elements (arrays start at index 0)
        System.out.println("First number: " + numbers[0]);     // 1
        System.out.println("Second name: " + names[1]);       // Bob
        
        // Loop through an array
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Number at index " + i + ": " + numbers[i]);
        }
    }
}

Object-Oriented Programming - Classes and Objects

Java is object-oriented, which means everything revolves around objects:

// Creating a class (blueprint for an object)
public class Student {
    // Fields (variables that belong to the class)
    String name;
    int age;
    double gpa;
    
    // Constructor - special method to create objects
    public Student(String name, int age, double gpa) {
        this.name = name;
        this.age = age;
        this.gpa = gpa;
    }
    
    // Methods (functions that belong to the class)
    public void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("GPA: " + gpa);
    }
    
    public boolean isHonorStudent() {
        return gpa >= 3.5;
    }
}

// Using the Student class
public class StudentExample {
    public static void main(String[] args) {
        // Creating objects (instances) of the Student class
        Student student1 = new Student("Alice", 20, 3.8);
        Student student2 = new Student("Bob", 19, 3.2);
        
        // Using methods on our objects
        student1.displayInfo();
        System.out.println("Is honor student? " + student1.isHonorStudent());
    }
}

Method Overloading and More

You can have multiple methods with the same name but different parameters:

public class Calculator {
    
    // Adding two numbers
    public int add(int a, int b) {
        return a + b;
    }
    
    // Adding three numbers
    public int add(int a, int b, int c) {
        return a + b + c;
    }
    
    // Adding decimal numbers
    public double add(double a, double b) {
        return a + b;
    }
    
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        
        System.out.println(calc.add(5, 3));          // Uses first method: 8
        System.out.println(calc.add(2, 4, 6));      // Uses second method: 12
        System.out.println(calc.add(2.5, 3.7));     // Uses third method: 6.2
    }
}

Enhanced Control Flow with Switch Statements

Switch statements are cleaner than multiple if-else conditions:

public class GradeCalculator {
    public static void main(String[] args) {
        int score = 85;
        String grade;
        
        // Traditional if-else approach
        if (score >= 90) {
            grade = "A";
        } else if (score >= 80) {
            grade = "B";
        } else if (score >= 70) {
            grade = "C";
        } else {
            grade = "D";
        }
        
        // Switch statement approach
        switch (score / 10) {   // Dividing by 10 gives us the tens digit
            case 10:
            case 9:
                grade = "A";
                break;
            case 8:
                grade = "B";
                break;
            case 7:
                grade = "C";
                break;
            default:
                grade = "D";
        }
        
        System.out.println("Grade: " + grade);
    }
}

Working with Strings More Effectively

String methods are incredibly useful for text processing:

public class StringMethods {
    public static void main(String[] args) {
        String message = "Hello World!";
        
        // Useful string operations
        System.out.println("Length: " + message.length());           // 12
        System.out.println("Uppercase: " + message.toUpperCase());   // HELLO WORLD!
        System.out.println("Lowercase: " + message.toLowerCase());   // hello world!
        System.out.println("Contains 'World': " + message.contains("World")); // true
        
        // Finding positions
        int position = message.indexOf('W');  // Returns 6 (position of W)
        System.out.println("Position of 'W': " + position);
        
        // Substrings
        String substring = message.substring(0, 5);  // Gets first 5 characters: "Hello"
        System.out.println("Substring: " + substring);
    }
}

More Loop Variations

Java offers different loop types for various situations:

public class LoopTypes {
    public static void main(String[] args) {
        // Traditional for loop (you've seen this already)
        System.out.println("Traditional for:");
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
        
        // Enhanced for loop (for-each) - great for arrays
        int[] numbers = {1, 2, 3, 4, 5};
        System.out.println("Enhanced for:");
        for (int number : numbers) {
            System.out.println(number);
        }
        
        // While loop - continue while condition is true
        System.out.println("While loop:");
        int count = 1;
        while (count <= 5) {
            System.out.println(count);
            count++;
        }
        
        // Do-while loop - executes at least once
        System.out.println("Do-while loop:");
        int counter = 1;
        do {
            System.out.println(counter);
            counter++;
        } while (counter <= 3);  // Will run 3 times even though condition is false after first iteration
    }
}

Error Handling with Try-Catch

Your programs can handle errors gracefully:

public class ExceptionHandling {
    public static void main(String[] args) {
        try {
            int result = divide(10, 0);  // This will cause an error
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide by zero!");
        }
        
        // You can also have multiple catches
        try {
            int[] array = new int[3];
            array[5] = 10;  // This will cause an error
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index out of bounds");
        } catch (Exception e) {
            System.out.println("Some other error occurred");
        }
    }
    
    public static int divide(int a, int b) {
        return a / b;
    }
}

Practical Example: A Simple Banking Program

Let's put everything together in one comprehensive example:

import java.util.Scanner;

public class BankAccount {
    private String accountHolder;  // Private fields (encapsulation)
    private double balance;
    
    public BankAccount(String holder, double initialBalance) {
        this.accountHolder = holder;
        this.balance = initialBalance;
    }
    
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("Deposited: $" + amount);
        } else {
            System.out.println("Deposit amount must be positive");
        }
    }
    
    public boolean withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("Withdrawn: $" + amount);
            return true;
        } else if (amount > balance) {
            System.out.println("Insufficient funds");
            return false;
        } else {
            System.out.println("Withdrawal amount must be positive");
            return false;
        }
    }
    
    public void displayBalance() {
        System.out.println("Account holder: " + accountHolder);
        System.out.println("Current balance: $" + balance);
    }
    
    public static void main(String[] args) {
        // Create a bank account
        BankAccount myAccount = new BankAccount("Alice Johnson", 1000.0);
        
        // Display initial balance
        myAccount.displayBalance();
        
        // Make some transactions
        myAccount.deposit(500.0);
        myAccount.withdraw(200.0);
        myAccount.withdraw(1500.0);  // This should fail
        
        // Show final balance
        myAccount.displayBalance();
    }
}

Key Concepts You've Mastered

Congratulations! By now you should understand:

  1. Variables and Data Types - How to store different kinds of information
  2. Control Flow - Making decisions and repeating actions with if/else, switch, for, while loops
  3. Methods - Creating reusable code blocks that can take parameters and return values
  4. Arrays - Storing multiple similar items together
  5. Object-Oriented Programming - Using classes to create objects with properties and behaviors
  6. String Manipulation - Working effectively with text data
  7. Error Handling - Making your programs more robust

What's Next?

With these skills, you're ready to tackle more complex programming concepts like:

  • File handling (reading/writing files)
  • Collections (Lists, Maps, Sets)
  • Inheritance and polymorphism
  • Working with external libraries
  • Building complete applications step by step

Keep practicing by creating small programs that solve real problems - whether it's a calculator, todo list, or simple game. Each program you build will reinforce these concepts and make them second nature.

Remember: Every expert was once a beginner, so keep exploring and don't be afraid to experiment!