JAVA PROGRAMMING FUNDAMENTALS
WEEK 1: INTRODUCTION TO JAVA & PROGRAMMING
FUNDAMENTALS
1.1 What is Programming?
Programming is the process of creating a set of instructions that tell a computer how
to perform a task. Think of it like giving someone a recipe to cook a meal - you provide
step-by-step instructions that must be followed exactly.
Key Concepts:
Algorithm: A step-by-step procedure for solving a problem
Program: A set of instructions written in a programming language
Syntax: The rules that define the structure of a programming language
Logic: The reasoning used to solve problems programmatically
1.2 What is Java?
Java is a high-level, object-oriented programming language developed by Sun
Microsystems (now owned by Oracle) in 1995. It follows the principle "Write Once, Run
Anywhere" (WORA).
Key Features of Java:
Feature Description
Platform Java code compiles to bytecode, which runs on any system with a Java Virtual
Independent Machine (JVM)
Object-Oriented Everything in Java is organized around objects and classes
Secure Built-in security features for network applications
Robust Strong memory management and error handling
Feature Description
Simple Clean syntax similar to C++ but without complex features
Multithreaded Supports multiple tasks running simultaneously
Java Versions:
Java SE (Standard Edition) - For desktop applications
Java EE (Enterprise Edition) - For enterprise applications
Java ME (Micro Edition) - For mobile and embedded devices
1.3 Java Program Structure
java
// Comments start with two slashes
/* Multi-line comments
can span multiple lines */
// 1. Package declaration (optional)
package [Link];
// 2. Import statements (optional)
import [Link];
// 3. Class declaration - EVERY Java program must have a class
public class MyFirstProgram {
// 4. Main method - Entry point of EVERY Java program
public static void main(String[] args) {
// 5. Code statements
[Link]("Hello, World!");
}
}
Components Explained:
Component Description Example
Package Organizes related classes package [Link];
Import Brings in other classes import [Link].*;
Class Blueprint for objects public class MyClass
Main Method Program entry point public static void main(String[] args)
Statements Instructions to execute [Link]("Hi");
1.4 Understanding the Hello World Program
java
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Line-by-Line Explanation:
Line Code Explanation
Defines a class named HelloWorld (must match
1 public class HelloWorld
filename)
public static void main(String[]
2 The main method where program starts
args)
3 [Link]("Hello, World!"); Prints text to the console
4 } Closes the main method
5 } Closes the class
Note: The String[] args parameter allows the program to accept command-line
arguments.
1.5 Setting Up Your Development Environment
Required Software:
Software Description Download Link
JDK Java Development Kit [Link]/java/technologies/downloads/
IDE Integrated Development Environment Choose one below
Popular IDEs for Java:
IDE Features Best For
Eclipse Free, widely used, powerful features Beginners and professionals
IntelliJ IDEA Popular choice, community edition is free Modern development
VS Code Lightweight with Java extensions Quick editing and development
Steps to Create Your First Java Program:
1. Install JDK (Java Development Kit)
o Download from Oracle website
o Set JAVA_HOME environment variable
o Add Java to PATH
2. Install an IDE
o Download and install your chosen IDE
o Configure JDK location
3. Create a new project
o File → New → Java Project
o Name your project
4. Create a new class
o Right-click src → New → Class
o Name it (must match filename)
5. Write your code
o Type the Hello World program
6. Compile and Run
o Click Run button or use shortcut
1.6 Java Naming Conventions
Type Convention Example
Classes PascalCase StudentRecord, BankAccount
Methods camelCase calculateGrade(), getStudentName()
Variables camelCase studentName, totalMarks
Constants UPPER_CASE MAX_VALUE, PI, MIN_AGE
Packages lowercase [Link], [Link]
Why Follow Conventions?
Readability: Makes code easier to read
Professionalism: Shows you follow industry standards
Teamwork: Everyone uses the same style
Maintenance: Easier to update and debug
1.7 Basic Syntax Rules
java
// 1. Case Sensitivity
int number = 5;
int Number = 10; // Different variable!
// 2. Semicolons
[Link]("Hello"); // Semicolon required
// 3. Braces { }
if (condition) {
// Code block
}
// 4. Indentation
public class Example {
public static void main(String[] args) {
[Link]("Indented properly");
}
}
WEEK 2: VARIABLES, DATA TYPES & OPERATORS
2.1 Variables in Java
A variable is a container that stores data. Think of it as a labeled box where you can put
things.
Variable Declaration Syntax:
java
dataType variableName = value;
Variable Rules:
Rule Example
Must start with letter, $, or _ $price, _value, name
Can contain letters, digits, $, _ student123, my$value
Cannot use reserved keywords int int = 5; ❌
Case sensitive name ≠ Name
Types of Variables:
Type Scope Example
Local Within method only int x = 10;
Instance Within class (object) String name;
Static Shared by all objects static int count;
Variable Declaration Examples:
java
// Declaration and initialization
int age = 20; // Integer
String name = "Sierra Leone"; // String (text)
double price = 49.99; // Decimal number
boolean isActive = true; // True/False
char grade = 'A'; // Single character
long population = 8000000L; // Large integer
float temperature = 25.5f; // Smaller decimal
// Declaration only
int count;
String message;
// Assignment later
count = 100;
message = "Hello";
2.2 Primitive Data Types
Java has 8 primitive data types (store simple values):
Integer Types:
Data Type Size Range Example
byte 1 byte -128 to 127 byte b = 100;
short 2 bytes -32,768 to 32,767 short s = 30000;
Data Type Size Range Example
int 4 bytes -2³¹ to 2³¹-1 int i = 1000;
long 8 bytes -2⁶³ to 2⁶³-1 long l = 100000L;
Decimal (Floating-Point) Types:
Data Type Size Precision Example
float 4 bytes 6-7 decimal digits float f = 3.14f;
double 8 bytes 15-16 decimal digits double d = 3.14159;
Character and Boolean Types:
Data Type Size Values Example
char 2 bytes 0 to 65,535 (Unicode) char c = 'A';
boolean 1 bit true or false boolean b = true;
Choosing the Right Data Type:
java
// For counting items - use int
int students = 30;
// For prices and money - use double
double price = 199.99;
// For yes/no questions - use boolean
boolean isPassed = true;
// For single characters - use char
char initial = 'J';
// For large numbers - use long
long worldPopulation = 8000000000L;
2.3 Non-Primitive Data Types (Reference Types)
Reference types store references (memory addresses) to objects.
Common Reference Types:
Type Description Example
String Sequence of characters String name = "John";
Arrays Collection of similar items int[] numbers = {1,2,3};
Classes User-defined blueprints Student s = new Student();
Interfaces Abstract types List list = new ArrayList();
String Examples:
java
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName; // "John Doe"
String empty = ""; // Empty string
String nullStr = null; // No string object
2.4 Type Casting
Converting one data type to another.
Implicit Casting (Automatic - Widening):
java
// From smaller to larger - automatic
int num = 100;
long longNum = num; // int → long (automatic)
double doubleNum = num; // int → double (automatic)
// Example
int intValue = 10;
double doubleValue = intValue; // 10.0
[Link](doubleValue); // 10.0
Explicit Casting (Manual - Narrowing):
java
// From larger to smaller - manual
double price = 99.99;
int intPrice = (int) price; // double → int (loses .99)
// Example
double doubleValue = 10.5;
int intValue = (int) doubleValue; // 10 (loses .5)
[Link](intValue); // 10
Type Conversion Table:
From To Method
int double Automatic (implicit)
double int Manual (explicit) - (int)
int String [Link]() or "" +
String int [Link]()
double String [Link]()
String double [Link]()
2.5 Input and Output
Getting User Input (Scanner):
java
import [Link]; // Import the Scanner class
Scanner scanner = new Scanner([Link]); // Create Scanner object
[Link]("Enter your name: ");
String name = [Link](); // Read full line
[Link]("Enter your age: ");
int age = [Link](); // Read integer
[Link]("Enter your GPA: ");
double gpa = [Link](); // Read decimal
[Link]("Are you a student? (true/false): ");
boolean isStudent = [Link](); // Read boolean
[Link](); // Close scanner when done
Output to Console:
java
// Print without newline
[Link]("Hello ");
[Link]("World");
// Output: Hello World
// Print with newline
[Link]("Hello");
[Link]("World");
// Output: Hello
// World
// Formatted output (printf)
[Link]("Name: %s, Age: %d, GPA: %.2f%n", name, age, gpa);
// Output: Name: John, Age: 20, GPA: 3.75
// Different format specifiers:
// %s - String
// %d - Integer
// %f - Float/Double
// %n - Newline
// %.2f - Float with 2 decimal places
Common Scanner Methods:
Method Description Example
next() Read a word String word = [Link]();
nextLine() Read a full line String line = [Link]();
Method Description Example
nextInt() Read an integer int num = [Link]();
nextDouble() Read a double double d = [Link]();
nextBoolean() Read a boolean boolean b = [Link]();
hasNext() Check for more input if ([Link]())
2.6 Operators in Java
Arithmetic Operators:
Operator Name Example Result
+ Addition a + b Sum of a and b
- Subtraction a - b Difference of a and b
* Multiplication a * b Product of a and b
/ Division a / b Quotient of a and b
% Modulus (Remainder) a % b Remainder after division
Arithmetic Examples:
java
int a = 10, b = 3;
[Link]("Addition: " + (a + b)); // 13
[Link]("Subtraction: " + (a - b)); // 7
[Link]("Multiplication: " + (a * b)); // 30
[Link]("Division: " + (a / b)); // 3 (integer division)
[Link]("Modulus: " + (a % b)); // 1 (remainder)
// Division with decimals
[Link]("Division (double): " + (10.0 / 3)); // 3.333...
Comparison (Relational) Operators:
Operator Name Example Result
== Equal to a == b true if equal
!= Not equal a != b true if not equal
> Greater than a > b true if a greater than b
< Less than a < b true if a less than b
>= Greater or equal a >= b true if a ≥ b
<= Less or equal a <= b true if a ≤ b
Comparison Examples:
java
int x = 5, y = 10;
[Link](x == y); // false
[Link](x != y); // true
[Link](x < y); // true
[Link](x > y); // false
[Link](x <= y); // true
[Link](x >= y); // false
Logical Operators:
Operator Name Description Example
&& AND Both true → true age >= 18 && hasID
|| OR At least one true → true isWeekend || isHoliday
! NOT Reverses value !isRaining
Logical Examples:
java
int age = 20;
boolean hasID = true;
// AND: Both conditions true
[Link](age >= 18 && hasID); // true
// AND: One condition false
[Link](age >= 21 && hasID); // false
// OR: One condition true
[Link](age < 18 || age > 65); // false
// OR: Both conditions false
[Link](age < 18 || hasID == false); // false
// NOT: Reverses value
boolean isRaining = true;
[Link](!isRaining); // false
Assignment Operators:
Operator Name Example Equivalent
= Assignment a = 5 a = 5
+= Add and assign a += 5 a = a + 5
-= Subtract and assign a -= 5 a = a - 5
*= Multiply and assign a *= 5 a = a * 5
/= Divide and assign a /= 5 a = a / 5
%= Modulus and assign a %= 5 a = a % 5
Increment/Decrement Operators:
Operator Name Example Effect
++ Increment i++ or ++i i = i + 1
Operator Name Example Effect
-- Decrement i-- or --i i = i - 1
Important Difference:
java
int x = 5;
[Link](x++); // Prints 5, then x becomes 6
[Link](x); // Prints 6
int y = 5;
[Link](++y); // y becomes 6, then prints 6
[Link](y); // Prints 6
2.7 String Operations
String Methods:
java
String text = "Hello World";
// Length
int length = [Link](); // 11
// Character at position
char first = [Link](0); // 'H'
char last = [Link]([Link]() - 1); // 'd'
// Case conversion
String upper = [Link](); // "HELLO WORLD"
String lower = [Link](); // "hello world"
// Checking content
boolean contains = [Link]("World"); // true
boolean startsWith = [Link]("Hello"); // true
boolean endsWith = [Link]("World"); // true
// Finding index
int index = [Link]('o'); // 4 (first 'o')
int lastIndex = [Link]('o'); // 7 (last 'o')
// Substring
String sub = [Link](6); // "World"
String sub2 = [Link](0, 5); // "Hello"
// Trimming
String withSpaces = " Hello ";
String trimmed = [Link](); // "Hello"
// Replacing
String replaced = [Link]('o', 'a'); // "Hella Warld"
String replacedAll = [Link]("World", "Java"); // "Hello Java"
String Comparison (Very Important!):
java
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
// WRONG: Using == compares memory addresses
[Link](s1 == s2); // true (both point to same literal)
[Link](s1 == s3); // false (different objects)
// CORRECT: Using equals() compares content
[Link]([Link](s2)); // true
[Link]([Link](s3)); // true
// Ignore case comparison
[Link]([Link]("hello")); // true
// Compare lexicographically
int comparison = [Link]("Hello"); // 0 (equal)
int compareTo = [Link]("Apple"); // positive (s1 > "Apple")
int compareTo2 = [Link]("Zebra"); // negative (s1 < "Zebra")
String Concatenation:
java
// Using + operator
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName; // "John Doe"
// Using concat() method
String fullName2 = [Link](" ").concat(lastName); // "John Doe"
// Using StringBuilder (more efficient for many concatenations)
StringBuilder sb = new StringBuilder();
[Link](firstName);
[Link](" ");
[Link](lastName);
String fullName3 = [Link](); // "John Doe"
WEEK 3: CONTROL STRUCTURES - IF/ELSE & SWITCH
3.1 Boolean Expressions and Logical Operators
A boolean expression evaluates to either true or false.
Creating Boolean Expressions:
java
int age = 18;
boolean isAdult = age >= 18; // true
boolean isSenior = age >= 65; // false
boolean canVote = isAdult && !isSenior; // true
boolean isTeenager = age >= 13 && age <= 19; // true
boolean isWorkingAge = age >= 18 && age < 65; // true
Truth Tables:
A B A && B A || B !A
true true true true false
true false false true false
false true false true true
false false false false true
3.2 If Statements
Simple If Statement:
java
if (condition) {
// Code executes if condition is true
}
Examples:
java
int marks = 75;
if (marks >= 50) {
[Link]("You passed!");
}
// Single statement (braces optional but recommended)
if (marks >= 50)
[Link]("You passed!"); // Works but not recommended
3.3 If-Else Statement
java
if (condition) {
// Code executes if condition is true
} else {
// Code executes if condition is false
}
Examples:
java
int temperature = 30;
if (temperature > 25) {
[Link]("It's hot!");
} else {
[Link]("It's cool!");
}
// Output: It's hot!
Example - Pass/Fail:
java
int score = 65;
if (score >= 50) {
[Link]("Congratulations! You passed.");
} else {
[Link]("Sorry, you failed.");
}
3.4 If-Else-If Ladder
java
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else if (condition3) {
// Code if condition3 is true
} else {
// Code if all conditions are false
}
Example - Grade Calculator:
java
int score = 85;
char grade;
if (score >= 90) {
grade = 'A';
[Link]("Excellent!");
} else if (score >= 80) {
grade = 'B';
[Link]("Good job!");
} else if (score >= 70) {
grade = 'C';
[Link]("Fair");
} else if (score >= 60) {
grade = 'D';
[Link]("Below average");
} else {
grade = 'F';
[Link]("Failed");
}
[Link]("Your grade is: " + grade);
// Output: Good job! Your grade is: B
Example - Ticket Price:
java
int age = 25;
double price;
if (age < 12) {
price = 5.00; // Child price
} else if (age < 18) {
price = 8.00; // Teen price
} else if (age < 60) {
price = 12.00; // Adult price
} else {
price = 6.00; // Senior price
}
[Link]("Ticket price: $" + price);
3.5 Nested If Statements
java
if (condition1) {
if (condition2) {
// Code when both conditions are true
} else {
// Code when condition1 true, condition2 false
}
} else {
// Code when condition1 false
}
Example - Club Entry:
java
int age = 18;
boolean hasID = true;
boolean isVIP = false;
if (age >= 18) {
if (hasID) {
if (isVIP) {
[Link]("Welcome to the VIP section!");
} else {
[Link]("Welcome to the club!");
}
} else {
[Link]("You need an ID!");
}
} else {
[Link]("You are too young!");
}
Example - Student Discount:
java
boolean isStudent = true;
boolean hasStudentID = true;
boolean isWeekend = false;
if (isStudent) {
if (hasStudentID) {
if (isWeekend) {
[Link]("Student discount available on weekends!");
} else {
[Link]("Student discount available today!");
}
} else {
[Link]("Please show your student ID.");
}
} else {
[Link]("Student discount not available.");
}
3.6 Switch Statement
The switch statement is an alternative to multiple if-else conditions when checking a
single variable against multiple values.
Syntax:
java
switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
// More cases...
default:
// Code if no case matches
}
Example - Day of Week:
java
int dayOfWeek = 3;
String dayName;
switch (dayOfWeek) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
[Link]("Day: " + dayName);
// Output: Day: Wednesday
Example - Month Name:
java
int month = 6;
String monthName;
switch (month) {
case 1: monthName = "January"; break;
case 2: monthName = "February"; break;
case 3: monthName = "March"; break;
case 4: monthName = "April"; break;
case 5: monthName = "May"; break;
case 6: monthName = "June"; break;
case 7: monthName = "July"; break;
case 8: monthName = "August"; break;
case 9: monthName = "September"; break;
case 10: monthName = "October"; break;
case 11: monthName = "November"; break;
case 12: monthName = "December"; break;
default: monthName = "Invalid month";
}
[Link]("Month: " + monthName);
3.7 Switch with Strings (Java 7+)
java
String meal = "breakfast";
switch ([Link]()) { // Convert to lowercase for consistency
case "breakfast":
[Link]("Time for some tea and bread!");
break;
case "lunch":
[Link]("Time for rice and stew!");
break;
case "dinner":
[Link]("Time for fufu and soup!");
break;
default:
[Link]("Not a meal time");
}
Example - User Role:
java
String role = "admin";
switch (role) {
case "admin":
[Link]("Full access granted.");
break;
case "manager":
[Link]("Limited access granted.");
break;
case "user":
[Link]("Read-only access.");
break;
default:
[Link]("No access.");
}
Switch Without Break (Fall-through):
java
int day = 3;
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
[Link]("Weekday");
break;
case 6:
case 7:
[Link]("Weekend");
break;
default:
[Link]("Invalid day");
}
// Output: Weekday
3.8 Best Practices for Conditionals
1. Keep Conditions Simple:
java
// BAD: Complex condition
if (age >= 18 && age <= 65 && hasID && !isSuspended) {
// Code
}
// GOOD: Break down into variables
boolean isAdult = age >= 18;
boolean isNotSenior = age <= 65;
boolean hasValidID = hasID;
boolean isNotSuspended = !isSuspended;
if (isAdult && isNotSenior && hasValidID && isNotSuspended) {
// Code
}
2. Use Meaningful Variable Names:
java
// BAD
int a = 85;
if (a >= 50) {
// Code
}
// GOOD
int studentScore = 85;
if (studentScore >= 50) {
// Code
}
3. Handle All Cases:
java
// BAD - Missing else
if (score >= 50) {
[Link]("Passed");
}
// What about scores below 50?
// GOOD - Include else
if (score >= 50) {
[Link]("Passed");
} else {
[Link]("Failed");
}
4. Avoid Deep Nesting:
java
// BAD - Too deep nesting
if (condition1) {
if (condition2) {
if (condition3) {
if (condition4) {
// Code
}
}
}
}
// GOOD - Use return or combine conditions
if (!condition1) return;
if (!condition2) return;
if (!condition3) return;
if (condition4) {
// Code
}
5. Use Braces {} Always:
java
// BAD - No braces (error-prone)
if (score >= 50)
[Link]("Passed");
[Link]("Good job!"); // This always executes!
// GOOD - Always use braces
if (score >= 50) {
[Link]("Passed");
[Link]("Good job!");
}
WEEK 4: LOOPS - FOR, WHILE & DO-WHILE
4.1 Introduction to Loops
Loops allow us to repeat a block of code multiple times.
Three Types of Loops:
Loop When to Use Syntax
For When you know how many times to repeat for (init; condition; update) { }
While When you don't know how many times while (condition) { }
Do-While When you need at least one execution do { } while (condition);
4.2 For Loop
Syntax:
java
for (initialization; condition; update) {
// Code to repeat
}
Flow:
1. Initialization executes once at the start
2. Condition is checked
3. If true, execute code block
4. Update executes
5. Return to step 2
Example - Print 1 to 10:
java
for (int i = 1; i <= 10; i++) {
[Link](i);
}
// Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Example - Countdown:
java
for (int i = 10; i > 0; i--) {
[Link]("Countdown: " + i);
}
[Link]("Blast off!");
// Output: Countdown: 10, 9, 8, ... 1, Blast off!
Example - Even Numbers:
java
for (int i = 2; i <= 20; i += 2) {
[Link](i + " ");
}
// Output: 2 4 6 8 10 12 14 16 18 20
Example - Sum of Numbers:
java
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i; // sum = sum + i
}
[Link]("Sum of 1 to 100: " + sum); // 5050
4.3 While Loop
Syntax:
java
while (condition) {
// Code to repeat
}
Example - Sum Until Zero:
java
Scanner scanner = new Scanner([Link]);
int sum = 0;
int number;
[Link]("Enter numbers to sum (0 to stop):");
number = [Link]();
while (number != 0) {
sum = sum + number;
number = [Link]();
}
[Link]("Total sum: " + sum);
Example - Guessing Game:
java
import [Link];
import [Link];
Random rand = new Random();
int secretNumber = [Link](100) + 1; // 1 to 100
int guess = 0;
int attempts = 0;
Scanner scanner = new Scanner([Link]);
[Link]("Guess a number between 1 and 100:");
while (guess != secretNumber) {
guess = [Link]();
attempts++;
if (guess < secretNumber) {
[Link]("Too low! Try again.");
} else if (guess > secretNumber) {
[Link]("Too high! Try again.");
}
}
[Link]("Correct! You took " + attempts + " attempts.");
Example - Password Check:
java
String password = "java123";
String input = "";
Scanner scanner = new Scanner([Link]);
while () {
[Link]("Enter password: ");
input = [Link]();
if () {
[Link]("Wrong password. Try again.");
}
}
[Link]("Access granted!");
4.4 Do-While Loop
Syntax:
java
do {
// Code to repeat
} while (condition);
Key Difference: The code block executes at least once, even if the condition is false.
Example - Menu System:
java
Scanner scanner = new Scanner([Link]);
int choice;
do {
[Link]("\n=== MENU ===");
[Link]("1. Add");
[Link]("2. Subtract");
[Link]("3. Multiply");
[Link]("4. Exit");
[Link]("Choose an option: ");
choice = [Link]();
if (choice == 1) {
[Link]("Enter first number: ");
double a = [Link]();
[Link]("Enter second number: ");
double b = [Link]();
[Link]("Result: " + (a + b));
} else if (choice == 2) {
[Link]("Enter first number: ");
double a = [Link]();
[Link]("Enter second number: ");
double b = [Link]();
[Link]("Result: " + (a - b));
} else if (choice == 3) {
[Link]("Enter first number: ");
double a = [Link]();
[Link]("Enter second number: ");
double b = [Link]();
[Link]("Result: " + (a * b));
} else if (choice != 4) {
[Link]("Invalid choice. Try again.");
}
} while (choice != 4);
[Link]("Goodbye!");
Example - Input Validation:
java
Scanner scanner = new Scanner([Link]);
int age;
do {
[Link]("Enter your age (must be 0-120): ");
age = [Link]();
if (age < 0 || age > 120) {
[Link]("Invalid age. Please enter a valid age.");
}
} while (age < 0 || age > 120);
[Link]("Valid age: " + age);
Example - ATM Menu:
java
Scanner scanner = new Scanner([Link]);
double balance = 1000.00;
int option;
do {
[Link]("\n=== ATM MENU ===");
[Link]("1. Check Balance");
[Link]("2. Deposit");
[Link]("3. Withdraw");
[Link]("4. Exit");
[Link]("Choose an option: ");
option = [Link]();
switch (option) {
case 1:
[Link]("Balance: $" + balance);
break;
case 2:
[Link]("Enter amount to deposit: $");
double deposit = [Link]();
balance += deposit;
[Link]("New balance: $" + balance);
break;
case 3:
[Link]("Enter amount to withdraw: $");
double withdraw = [Link]();
if (withdraw > balance) {
[Link]("Insufficient funds!");
} else {
balance -= withdraw;
[Link]("New balance: $" + balance);
}
break;
case 4:
[Link]("Thank you for using our ATM!");
break;
default:
[Link]("Invalid option!");
}
} while (option != 4);
4.5 Nested Loops
A nested loop is a loop inside another loop. The inner loop completes all its iterations
for each single iteration of the outer loop.
Example - Multiplication Table:
java
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
[Link]("%4d", i * j);
}
[Link](); // New line after each row
}
Output:
text
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Example - Clock Display:
java
for (int hour = 0; hour < 24; hour++) {
for (int minute = 0; minute < 60; minute++) {
[Link]("%02d:%02d%n", hour, minute);
}
}
// Prints all times from 00:00 to 23:59
Example - 2D Grid:
java
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
[Link]("(R" + row + "C" + col + ") ");
}
[Link]();
}
Output:
text
(R1C1) (R1C2) (R1C3)
(R2C1) (R2C2) (R2C3)
(R3C1) (R3C2) (R3C3)
4.6 Loop Control Statements
Break Statement:
Exits the loop immediately.
java
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Loop stops at 5
}
[Link](i);
}
// Output: 1, 2, 3, 4
Continue Statement:
Skips the current iteration and continues.
java
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
[Link](i);
}
// Output: 1, 3, 5, 7, 9
Return Statement:
Exits the entire method.
java
public static void findFirstEven(int[] numbers) {
for (int i = 0; i < [Link]; i++) {
if (numbers[i] % 2 == 0) {
[Link]("First even number: " + numbers[i]);
return; // Exit method when found
}
}
[Link]("No even number found.");
}
Nested Loops with Break:
java
// Find position of first negative number in 2D array
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (array[i][j] < 0) {
[Link]("Found at (" + i + "," + j + ")");
return; // Exits all loops
}
}
}
Labeled Break:
java
outerLoop:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break outerLoop; // Breaks outer loop
}
[Link]("i=" + i + ", j=" + j);
}
}
// Output: i=1,j=1 i=1,j=2 i=1,j=3 i=2,j=1
4.7 Pattern Printing with Nested Loops
Triangle Pattern:
java
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
[Link]("* ");
}
[Link]();
}
Output:
text
*
* *
* * *
* * * *
* * * * *
Inverted Triangle:
java
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
[Link]("* ");
}
[Link]();
}
Output:
text
* * * * *
* * * *
* * *
* *
*
Right Triangle with Spaces:
java
for (int i = 1; i <= 5; i++) {
// Print spaces
for (int j = 1; j <= 5 - i; j++) {
[Link](" ");
}
// Print stars
for (int k = 1; k <= i; k++) {
[Link]("* ");
}
[Link]();
}
Output:
text
*
* *
* * *
* * * *
* * * * *
Number Pyramid:
java
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
[Link](j + " ");
}
[Link]();
}
Output:
text
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Diamond Pattern:
java
int rows = 5;
// Upper half
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
[Link](" ");
}
for (int k = 1; k <= 2 * i - 1; k++) {
[Link]("* ");
}
[Link]();
}
// Lower half
for (int i = rows - 1; i >= 1; i--) {
for (int j = 1; j <= rows - i; j++) {
[Link](" ");
}
for (int k = 1; k <= 2 * i - 1; k++) {
[Link]("* ");
}
[Link]();
}
4.8 Common Loop Applications
1. Finding Maximum:
java
int[] numbers = {23, 45, 12, 67, 34};
int max = numbers[0];
for (int i = 1; i < [Link]; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
[Link]("Maximum: " + max); // 67
2. Finding Minimum:
java
int[] numbers = {23, 45, 12, 67, 34};
int min = numbers[0];
for (int i = 1; i < [Link]; i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
[Link]("Minimum: " + min); // 12
3. Sum and Average:
java
int[] scores = {85, 90, 78, 92, 88};
int sum = 0;
for (int i = 0; i < [Link]; i++) {
sum += scores[i];
}
double average = (double) sum / [Link];
[Link]("Sum: " + sum); // 433
[Link]("Average: " + average); // 86.6
4. Factorial Calculation:
java
int number = 5;
int factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
[Link](number + "! = " + factorial); // 5! = 120
5. Prime Number Check:
java
int num = 17;
boolean isPrime = true;
if (num <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
[Link](num + " is prime: " + isPrime); // true
6. Reverse a Number:
java
int number = 12345;
int reversed = 0;
while (number != 0) {
int digit = number % 10;
reversed = reversed * 10 + digit;
number = number / 10;
}
[Link]("Reversed: " + reversed); // 54321
7. Sum of Digits:
java
int number = 12345;
int sum = 0;
while (number != 0) {
sum += number % 10;
number = number / 10;
}
[Link]("Sum of digits: " + sum); // 15
8. Fibonacci Sequence:
java
int n = 10;
int first = 0, second = 1;
[Link]("Fibonacci sequence: ");
for (int i = 1; i <= n; i++) {
[Link](first + " ");
int next = first + second;
first = second;
second = next;
}
// Output: 0 1 1 2 3 5 8 13 21 34
SAMPLE QUESTIONS
SECTION A: OBJECTIVE QUESTIONS (Multiple Choice)
Variables & Data Types
1. What is the size of an int variable in Java?
A) 1 byte
B) 2 bytes
C) 4 bytes ✓
D) 8 bytes
2. Which of the following is NOT a primitive data type?
A) int
B) double
C) String ✓
D) boolean
3. What will be the output of this code?
java
int x = 5;
double y = x;
[Link](y);
A) 5.0 ✓
B) 5
C) Error
D) 5.5
4. Which statement correctly declares a constant in Java?
A) const int MAX = 100;
B) final int MAX = 100; ✓
C) static int MAX = 100;
D) constant int MAX = 100;
5. What is the result of: 10 % 3?
A) 3
B) 1 ✓
C) 0
D) 10
6. Which of the following is a valid variable name in Java?
A) 2ndNumber
B) myVariable ✓
C) class
D) my-variable
7. What is the default value of a boolean variable?
A) true
B) false ✓
C) null
D) 0
8. Which operator is used for multiplication?
A) x
B) *
C) .
D) **
9. What does the instanceof operator do?
A) Creates a new instance
B) Checks if an object is an instance of a class ✓
C) Compares two objects
D) Returns the class name
10. What is the range of the byte data type?
A) 0 to 255
B) -128 to 127 ✓
C) -32768 to 32767
D) -2³¹ to 2³¹-1
Control Structures
11. What will this code print?
java
int x = 5;
if (x > 5) {
[Link]("A");
} else if (x == 5) {
[Link]("B");
} else {
[Link]("C");
}
A) A
B) B ✓
C) C
D) ABC
12. Which operator is used for logical AND?
A) &
B) &&
C) and
D) both A and B ✓
13. What is the default case in a switch statement used for?
A) To handle all cases
B) To execute when no case matches ✓
C) To break out of the switch
D) To provide a default value
14. Which of these is a valid if-else statement?
A) if (x > 5) y = 10; else y = 20;
B) if (x > 5) { y = 10; } else { y = 20; }
C) Both A and B ✓
D) Neither
15. What will this code print?
java
int num = 10;
if (num > 5 || num < 15) {
[Link]("True");
} else {
[Link]("False");
}
A) True ✓
B) False
C) Error
D) Nothing
16. What is the output of this code?
java
int x = 2;
if (x == 1) {
[Link]("One");
} else if (x == 2) {
[Link]("Two");
} else {
[Link]("Other");
}
A) One
B) Two ✓
C) Other
D) Error
17. In a switch statement, what happens if you omit the break keyword?
A) The switch exits
B) Execution continues to the next case ✓
C) A compile error occurs
D) The default case executes
18. Which is NOT a valid comparison operator?
A) ==
B) !=
C) <>
D) >=
19. What will this code print?
java
int a = 5, b = 10;
if (a++ > 5 && b-- < 10) {
[Link]("Both");
} else {
[Link]("Not both");
}
A) Both
B) Not both ✓
C) Error
D) Nothing
20. What is the output of this code?
java
int score = 75;
if (score >= 70) {
[Link]("C");
} else if (score >= 80) {
[Link]("B");
} else if (score >= 90) {
[Link]("A");
}
A) C ✓
B) B
C) A
D) Nothing
Loops
21. How many times does this loop execute?
java
for (int i = 0; i < 5; i++) {
[Link](i);
}
A) 4
B) 5 ✓
C) 6
D) Infinite
22. What is the output of this code?
java
int i = 0;
while (i < 3) {
[Link](i + " ");
i++;
}
A) 0 1 2 ✓
B) 0 1 2 3
C) 1 2 3
D) Infinite loop
23. Which loop guarantees at least one execution?
A) for loop
B) while loop
C) do-while loop ✓
D) All of the above
24. What does break do in a loop?
A) Skips one iteration
B) Exits the loop completely ✓
C) Restarts the loop
D) Does nothing
25. What is the output of this code?
java
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= i; j++) {
[Link]("*");
}
[Link]();
}
A)
text
*
**
***
✓
B)
text
***
**
*
C)
text
**
***
****
D)
text
*
*
*
26. What will this code print?
java
for (int i = 0; i < 5; i++) {
if (i == 2) continue;
[Link](i + " ");
}
A) 0 1 2 3 4
B) 0 1 3 4 ✓
C) 0 1 2 3
D) 1 2 3 4
27. What is the correct syntax for a do-while loop?
A) do { } while (condition); ✓
B) do while (condition) { }
C) do { } while condition
D) while (condition) do { }
28. What does this nested loop print?
java
for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 2; j++) {
[Link](i + "," + j + " ");
}
}
A) 1,1 1,2 2,1 2,2 ✓
B) 1,1 2,1 1,2 2,2
C) 1,1 1,2 1,3 2,1
D) 2,2 1,1 2,1 1,2
29. What is the output of this code?
java
int x = 3;
switch (x) {
case 1: [Link]("A"); break;
case 2: [Link]("B");
case 3: [Link]("C");
case 4: [Link]("D");
}
A) A
B) B C D
C) C D ✓
D) C
30. What is the output?
java
int i = 0;
do {
[Link](i + " ");
i++;
} while (i < 3);
A) 0 1 2 ✓
B) 0 1 2 3
C) 1 2 3
D) 0 1
SECTION B: THEORY QUESTIONS
Basic Concepts
1. Explain the difference between [Link]() and [Link]().
Answer:
[Link]() prints text without moving to a new line
[Link]() prints text and moves to a new line after
Example:
java
[Link]("Hello ");
[Link]("World");
// Output: Hello World
[Link]("Hello ");
[Link]("World");
// Output: Hello
// World
2. What is a variable? How do you declare and initialize a variable in Java?
Answer:
A variable is a container that stores data in memory. To declare a variable, specify its
data type and name. To initialize it, assign a value using the assignment operator (=).
Syntax:
java
dataType variableName = value;
Examples:
java
int age = 25; // Declaration and initialization
String name = "Sierra"; // String variable
double price = 99.99; // Double variable
boolean passed = true; // Boolean variable
3. What are the primitive data types in Java? List them with examples.
Answer:
Java has 8 primitive data types:
Type Example Description
byte byte b = 100; Small integer (-128 to 127)
Type Example Description
short short s = 30000; Medium integer
int int i = 1000; Standard integer
long long l = 100000L; Large integer
float float f = 3.14f; Small decimal
double double d = 3.14159; Standard decimal
char char c = 'A'; Single character
boolean boolean b = true; True or false
4. What is the difference between implicit and explicit type casting?
Answer:
Implicit Casting (Automatic):
Happens when converting a smaller data type to a larger one
No data loss occurs
Compiler handles it automatically
java
int num = 100;
double doubleNum = num; // int to double (automatic)
Explicit Casting (Manual):
Happens when converting a larger data type to a smaller one
May lose data
Programmer must specify the cast
java
double price = 99.99;
int intPrice = (int) price; // double to int (manual, loses .99)
5. Explain the differences between if-else and switch statements.
Answer:
Feature if-else switch
Purpose Tests conditions (boolean) Tests equality against multiple values
Data Types Any boolean expression int, char, String (Java 7+), enums
Syntax Can be complex Cleaner, more readable
Fall-through Not applicable Can happen without break
Use Case Complex conditions Multiple exact value checks
Example - if-else:
java
if (score >= 90) grade = 'A';
else if (score >= 80) grade = 'B';
else if (score >= 70) grade = 'C';
else grade = 'F';
Example - switch:
java
switch (day) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
default: dayName = "Invalid";
}
6. What are the three types of loops in Java? When would you use each?
Answer:
1. For Loop: Use when you know the exact number of iterations
java
for (int i = 0; i < 10; i++) {
[Link](i); // Executes 10 times
}
// Use: Arrays, counters, known ranges
2. While Loop: Use when iterations depend on a condition
java
int num = 0;
while (num != 0) {
num = [Link](); // Runs until user enters 0
}
// Use: User input validation, reading until condition met
3. Do-While Loop: Use when you need at least one execution
java
do {
[Link]("Menu");
choice = [Link]();
} while (choice != 4);
// Use: Menu systems, user prompts
7. Explain the difference between break and continue in loops.
Answer:
Break:
Exits the loop immediately
Control moves to the first statement after the loop
java
for (int i = 0; i < 10; i++) {
if (i == 5) break;
[Link](i); // Prints 0-4 only
}
Continue:
Skips the rest of the current iteration
Continues with the next iteration
java
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) continue;
[Link](i); // Prints odd numbers: 1,3,5,7,9
}
8. What is a nested loop? Provide a real-world example.
Answer:
A nested loop is a loop inside another loop. The inner loop completes all its iterations
for each iteration of the outer loop.
Real-world Example - Multiplication Table:
java
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
[Link](i * j + "\t");
}
[Link](); // New line after each row
}
// Creates a 10x10 multiplication table
Other real-world applications:
Creating a seating chart for a classroom
Processing data in a spreadsheet (rows and columns)
Grid-based games (chess, tic-tac-toe)
Displaying time tables (hours and minutes)
Operators and Expressions
9. Explain the different arithmetic operators in Java with examples.
Answer:
Operator Name Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 10 / 3 3 (integer division)
% Modulus 10 % 3 1 (remainder)
Example Program:
java
int a = 10, b = 3;
[Link]("Addition: " + (a + b)); // 13
[Link]("Division: " + (a / b)); // 3 (integer division)
[Link]("Modulus: " + (a % b)); // 1
[Link]("Division (double): " + (10.0 / 3)); // 3.333...
10. What are logical operators? Provide examples.
Answer:
Logical operators are used to combine multiple boolean expressions.
Operator Name Truth Table Example
&& AND Both true → true age >= 18 && hasID
|| OR At least one true → true isWeekend || isHoliday
! NOT Reverses value !isRaining
Examples:
java
int age = 20;
boolean hasID = true;
// AND: Both conditions must be true
if (age >= 18 && hasID) {
[Link]("Can enter club"); // true
}
// OR: At least one condition true
if (age < 18 || age > 65) {
[Link]("Eligible for discount");
}
// NOT: Reverses condition
boolean isRaining = false;
if (!isRaining) {
[Link]("Go outside!"); // true
}
Strings
11. What is a String in Java? How do you declare and manipulate strings?
Answer:
A String is a sequence of characters. Unlike primitive types, String is a class (reference
type).
Declaration and Initialization:
java
String name = "John Doe";
String empty = ""; // Empty string
String nullString = null; // No value
Common String Methods:
java
String text = "Hello World";
int length = [Link](); // 11
char first = [Link](0); // 'H'
String upper = [Link](); // "HELLO WORLD"
String lower = [Link](); // "hello world"
boolean contains = [Link]("World"); // true
int index = [Link]('o'); // 4
// String comparison (IMPORTANT!)
String s1 = "Hello";
String s2 = "Hello";
boolean equal = [Link](s2); // true
boolean ignoreCase = [Link]("hello"); // true
12. How do you read input from the user in Java?
Answer:
Use the Scanner class to read user input.
Basic Scanner Setup:
java
import [Link]; // Import first
Scanner scanner = new Scanner([Link]);
// Reading different types
[Link]("Enter your name: ");
String name = [Link](); // Read full line
[Link]("Enter your age: ");
int age = [Link](); // Read integer
[Link]("Enter your GPA: ");
double gpa = [Link](); // Read decimal
[Link](); // Close when done
Common Scanner Methods:
next() - Read a word
nextLine() - Read a full line
nextInt() - Read an integer
nextDouble() - Read a double
nextBoolean() - Read a boolean
hasNext() - Check if there's more input
SECTION C: PRACTICAL CODING PROBLEMS
Problem 1: Simple Calculator
Scenario:
Write a Java program that asks the user for two numbers and an operation (+, -, *, /)
and displays the result.
Requirements:
Use Scanner to get user input
Use if-else or switch for operations
Handle division by zero
Sample Run:
text
Enter first number: 10
Enter second number: 5
Enter operation (+, -, *, /): +
Result: 10 + 5 = 15
Sample Solution:
java
import [Link];
public class SimpleCalculator {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter first number: ");
double num1 = [Link]();
[Link]("Enter second number: ");
double num2 = [Link]();
[Link]("Enter operation (+, -, *, /): ");
char operation = [Link]().charAt(0);
double result = 0;
boolean valid = true;
switch (operation) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
[Link]("Error: Cannot divide by zero!");
valid = false;
}
break;
default:
[Link]("Invalid operation!");
valid = false;
}
if (valid) {
[Link]("Result: " + num1 + " " + operation + " " + num2 + " =
" + result);
}
[Link]();
}
}
Problem 2: Grade Calculator
Scenario:
Write a program that calculates a student's final grade based on test scores.
Requirements:
Accept 4 test scores from user
Calculate average
Assign letter grade
Display results
Sample Run:
text
Enter test scores:
Test 1: 95
Test 2: 87
Test 3: 92
Test 4: 78
Average: 88.0
Grade: B
Excellent!
Sample Solution:
java
import [Link];
public class GradeCalculator {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter test scores:");
[Link]("Test 1: ");
double test1 = [Link]();
[Link]("Test 2: ");
double test2 = [Link]();
[Link]("Test 3: ");
double test3 = [Link]();
[Link]("Test 4: ");
double test4 = [Link]();
double average = (test1 + test2 + test3 + test4) / 4.0;
char grade;
String message;
if (average >= 90) {
grade = 'A';
message = "Excellent!";
} else if (average >= 80) {
grade = 'B';
message = "Good job!";
} else if (average >= 70) {
grade = 'C';
message = "Fair";
} else if (average >= 60) {
grade = 'D';
message = "Below average";
} else {
grade = 'F';
message = "Failed";
}
[Link]("\nAverage: " + average);
[Link]("Grade: " + grade);
[Link](message);
[Link]();
}
}
Problem 3: Multiplication Table
Scenario:
Write a program that generates a multiplication table.
Requirements:
Ask user for a number
Print multiplication table from 1 to 10
Bonus: Print 10x10 table
Sample Run:
text
Enter a number: 7
Multiplication table for 7:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
Sample Solution:
java
import [Link];
public class MultiplicationTable {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
[Link]("\nMultiplication table for " + number + ":");
for (int i = 1; i <= 10; i++) {
[Link](number + " x " + i + " = " + (number * i));
}
// Bonus: 10x10 table
[Link]("\n10x10 Multiplication Table:");
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
[Link]("%4d", i * j);
}
[Link]();
}
[Link]();
}
}
Problem 4: Number Guessing Game
Scenario:
Write a program that generates a random number and lets the user guess it.
Requirements:
Generate random number between 1-100
Let user guess until correct
Give hints (Too high/Too low)
Count attempts
Sample Run:
text
Guess a number between 1 and 100:
50
Too low! Try again.
75
Too high! Try again.
62
Too low! Try again.
68
Correct! You took 4 attempts.
Sample Solution:
java
import [Link];
import [Link];
public class GuessingGame {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
Random rand = new Random();
int secretNumber = [Link](100) + 1;
int guess