2.1 Variables, Data Types, and Operators
At its heart, a program manipulates data. Variables are named containers that store this data. Each variable must have a data type, which tells Java what kind of data it can hold and how much memory to reserve.
Primitive Data Types
These are the most basic data types in Java:
int: For whole numbers (e.g., 10, -50, 42).double: For floating-point or decimal numbers (e.g., 3.14, -0.001).char: For single characters (e.g., 'A', '$').boolean: For true or false values.
Operators
Operators are special symbols that perform operations on variables and values.
- Arithmetic:
+(add),-(subtract),*(multiply),/(divide). - Assignment:
=(assign a value). - Comparison:
==(equal to),!=(not equal to),>(greater than),<(less than).
// Variable declaration and initialization
int age = 30;
double accountBalance = 1250.75;
char accountType = 'S'; // 'S' for Savings
boolean isActive = true;
// Using operators
double depositAmount = 500.25;
double newBalance = accountBalance + depositAmount; // newBalance is 1751.0
System.out.println("Is the new balance greater than 1500? " + (newBalance > 1500)); // Prints true
2.2 Control Structures (if, loops, switch)
Control structures dictate the flow of your program's execution. They allow you to make decisions and repeat actions.
The if-else Statement
Used to execute a block of code only if a certain condition is true.
double withdrawalAmount = 200.0;
if (accountBalance >= withdrawalAmount) {
accountBalance = accountBalance - withdrawalAmount;
System.out.println("Withdrawal successful.");
} else {
System.out.println("Insufficient funds.");
}
The for Loop
Used to repeat a block of code a specific number of times.
// Print numbers 1 through 5
for (int i = 1; i <= 5; i++) {
System.out.println("Count is: " + i);
}
The switch Statement
Allows a variable to be tested for equality against a list of values (cases).
char accountType = 'S';
switch (accountType) {
case 'S':
System.out.println("It's a Savings Account.");
break;
case 'C':
System.out.println("It's a Checking Account.");
break;
default:
System.out.println("Unknown Account Type.");
break;
}
2.3 Classes, Objects, and Methods
This is the heart of Object-Oriented Programming (OOP). It's a way of thinking about programming that models the real world.
- A Class is a blueprint or template. For our project, we can create an
Accountclass. It defines the properties (data) and behaviors (actions) that all accounts will have. - An Object is an instance of a class. While we have one
Accountclass (the blueprint), we can create manyAccountobjects from it (John's account, Jane's account), each with its own data. - Methods are functions defined inside a class that describe the behaviors of an object.
// This is the blueprint for all bank accounts
public class Account {
// Properties (data)
String accountNumber;
String accountHolderName;
double balance;
// Behaviors (methods)
public void deposit(double amount) {
if (amount > 0) {
balance = balance + amount;
System.out.println("Deposited: " + amount);
}
}
public void withdraw(double amount) {
if (amount > 0 && balance >= amount) {
balance = balance - amount;
System.out.println("Withdrew: " + amount);
} else {
System.out.println("Withdrawal failed.");
}
}
public double getBalance() {
return balance;
}
}
2.4 Constructors and Encapsulation
A constructor is a special method that is called when an object is created. Its purpose is to initialize the object's properties.
Encapsulation is a core OOP principle of bundling the data (properties) and the methods that operate on the data into a single unit (the class). We use access modifiers like private to hide the data from the outside world, and provide public methods (getters and setters) to control access. This protects the object from accidental modification and ensures data integrity.
public class Account {
// Properties are now private to protect them
private String accountNumber;
private String accountHolderName;
private double balance;
// This is a constructor to initialize a new Account object
public Account(String accountNumber, String accountHolderName, double initialDeposit) {
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = initialDeposit;
}
// Public "getter" method to safely access the balance
public double getBalance() {
return this.balance;
}
// Deposit and withdraw methods would be here...
}
2.5 Collections (List, Map, Set)
The Java Collections Framework provides powerful and efficient data structures to store groups of objects.
- List: An ordered collection. Think of a list of transactions in the order they occurred. We'll use
ArrayList. - Map: A collection of key-value pairs. Perfect for storing accounts where the account number (a
String) is the key and theAccountobject is the value. We'll useHashMap. - Set: A collection that holds only unique elements.
2.6 Exception Handling
Things can go wrong in a program. A user might enter text instead of a number, or you might try to withdraw more money than is available. An exception is an event that disrupts the normal flow of the program. We use try-catch blocks to handle these exceptions gracefully instead of letting the program crash.
try {
// Code that might cause an error
double amountToWithdraw = 5000;
if (amountToWithdraw > balance) {
// Create and "throw" our own custom exception
throw new IllegalArgumentException("Insufficient funds for withdrawal.");
}
// ... process withdrawal
} catch (IllegalArgumentException e) {
// Code to run if that specific error happens
System.out.println("Error: " + e.getMessage());
}
2.7 Mini-Project: Console Bank App
Let's put it all together! This mini-project will use everything we've learned in this module to create a simple, interactive banking application that runs in the console. It will allow a user to deposit, withdraw, and check their balance.
import java.util.Scanner;
public class ConsoleBankApp {
public static void main(String[] args) {
// Create an account object using the constructor
Account myAccount = new Account("12345", "John Doe", 1000.0);
Scanner scanner = new Scanner(System.in);
int choice = 0;
while (choice != 4) {
System.out.println("\n--- Bank Menu ---");
System.out.println("1. Check Balance");
System.out.println("2. Deposit");
System.out.println("3. Withdraw");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Your balance is: $" + myAccount.getBalance());
break;
case 2:
System.out.print("Enter amount to deposit: ");
double depositAmount = scanner.nextDouble();
myAccount.deposit(depositAmount);
break;
case 3:
System.out.print("Enter amount to withdraw: ");
double withdrawAmount = scanner.nextDouble();
myAccount.withdraw(withdrawAmount);
break;
case 4:
System.out.println("Thank you for banking with us!");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
}
scanner.close();
}
}
// Note: You also need the Account class defined earlier for this to run.