Phase 1 — Java Foundations
This phase takes you from no strong programming fundamentals to being comfortable reading and writing basic Java programs.
Chapters in this Phase
Java, JDK, JVM & Your First Program
Java Program Structure, Statements & Comments
Variables & Assignment
Primitive Data Types & Literals
Operators & Expressions
Strings & Basic Text Processing
User Input
Type Conversion & Type Casting
Boolean Logic
if,else if&elseswitchforLoopswhile&do-whileLoopsbreak,continue& Nested LoopsMethods &
returnMethod Parameters, Overloading & Varargs
Scope & Lifetime of Variables
Arrays
Multidimensional Arrays
Packages, Imports & Basic Java Organization
Basic Problem-Solving Patterns & Putting Fundamentals Together
Chapter 1 — Java, JDK, JVM & Your First Program
Question
Given below is a code snippet that:
Defines a Java class.
Defines the
mainmethod.Prints text to the console.
Demonstrates the basic structure of an executable Java program.
What should be the output of the following code?
// Define a class named Main.
class Main {
// Java starts running the program from the main method.
public static void main(String[] args) {
// Print a message to the console.
System.out.println("Hello, Java!");
// Print another message on a new line.
System.out.println("I am learning Java.");
}
}Answer
Hello, Java!
I am learning Java.Step-by-step explanation
class Maindefines a class namedMain.Java needs an entry point to know where execution should begin.
That entry point is
main.System.out.println()prints text.The first call prints
Hello, Java!.printlnmoves to the next line after printing.The second call therefore prints
I am learning Java.on the next line.
How to read the important code
System.out.println("Hello, Java!");A programmer naturally says:
"System dot out dot println, passing it the string Hello, Java."
You do not need to say:
"System open parenthesis... semicolon..."
Beginner trap
main is not an ordinary method when you're talking about starting a normal Java application. It is the program's entry point.
Key takeaway
A Java application starts execution from its
mainmethod.
Chapter 2 — Java Program Structure, Statements & Comments
Question
Given below is a code snippet that:
Uses comments.
Demonstrates statements.
Uses curly braces to define blocks.
Shows that Java executes statements in order.
Demonstrates
printlnversusprint.
What should be the output of the following code?
// The class contains the program.
class Main {
// Program execution begins here.
public static void main(String[] args) {
// Print without moving to a new line.
System.out.print("Java ");
// Print and then move to the next line.
System.out.println("programming");
// These two statements execute from top to bottom.
System.out.print("is ");
System.out.println("fun!");
}
}Answer
Java programming
is fun!Step-by-step explanation
System.out.print("Java ");printsJavabut stays on the same line.println("programming")printsprogrammingafter it.printlnthen moves to the next line.print("is ")printsis.println("fun!")printsfun!and moves to the next line.
Comments beginning with // are ignored by Java when the program runs.
How to read the important code
"Print Java without a newline."
versus:
"Print programming and then move to the next line."
Beginner trap
print() and println() are different.
print()stays on the current line.
println()prints and then moves to the next line.
Key takeaway
Java normally executes statements sequentially from top to bottom.
Chapter 3 — Variables & Assignment
Question
Given below is a code snippet that:
Declares variables.
Assigns initial values.
Changes variable values.
Uses one variable to calculate another value.
Demonstrates assignment with
=.
What should be the output of the following code?
class Main {
public static void main(String[] args) {
// Create an integer variable named price and give it 100.
int price = 100;
// Create another integer variable named quantity.
int quantity = 3;
// Calculate the total using the current variable values.
int total = price * quantity;
// Change the price variable.
price = 120;
// Calculate a new total using the new price.
total = price * quantity;
// Display the final values.
System.out.println(price);
System.out.println(quantity);
System.out.println(total);
}
}Answer
120
3
360Step-by-step explanation
pricestarts as100.quantitystarts as3.totalbecomes100 × 3, or300.price = 120changes the value stored inprice.total = price * quantityruns again.Java now calculates
120 × 3.Therefore
totalbecomes360.
The = symbol means assignment here.
It means:
"Put this value into this variable."
How to read the important code
int price = 100;Say:
"Declare an int called price and assign it 100."
price = 120;Say:
"Assign 120 to price."
Beginner trap
= does not mean "is equal to" in the mathematical sense. It is the assignment operator.
Key takeaway
A variable is a named place for storing a value, and assignment can change that value.
Chapter 4 — Primitive Data Types & Literals
Question
Given below is a code snippet that:
Uses several primitive data types.
Demonstrates integers, decimals, characters and booleans.
Shows that different variables can store different kinds of values.
Demonstrates literals.
What should be the output of the following code?
class Main {
public static void main(String[] args) {
// Store a whole number.
int age = 35;
// Store a decimal number.
double salary = 55000.50;
// Store a single character.
char grade = 'A';
// Store either true or false.
boolean employed = true;
// Store a smaller whole number.
long population = 1400000000L;
// Display all values.
System.out.println(age);
System.out.println(salary);
System.out.println(grade);
System.out.println(employed);
System.out.println(population);
}
}Answer
35
55000.5
A
true
1400000000Step-by-step explanation
intstores whole numbers such as35.doublestores decimal numbers.charstores one character. Character literals use single quotes:'A'.booleanstorestrueorfalse.longstores large whole numbers.Ltells Java that1400000000is alongliteral.
Some important primitive types are:
| Type | Typical use |
|---|---|
byte | Very small whole numbers |
short | Small whole numbers |
int | Normal whole numbers |
long | Very large whole numbers |
float | Decimal numbers |
double | Decimal numbers; common default choice |
char | One character |
boolean | true / false |
How to read the important code
"Declare a double called salary and assign it 55000.50."
Beginner trap
String is not a primitive type. It is a Java class. We will deal with it separately.
Key takeaway
Choose a data type according to the kind of value the variable needs to store.
Chapter 5 — Operators & Expressions
Question
Given below is a code snippet that:
Uses arithmetic operators.
Uses remainder
%.Combines several expressions.
Demonstrates operator precedence.
Uses increment.
What should be the output of the following code?
class Main {
public static void main(String[] args) {
// Store two numbers.
int a = 10;
int b = 3;
// Perform basic arithmetic.
int sum = a + b;
int difference = a - b;
int product = a * b;
int quotient = a / b;
// % gives the remainder after division.
int remainder = a % b;
// Multiplication happens before addition.
int result = a + b * 2;
// Increase a by one.
a++;
// Display the results.
System.out.println(sum);
System.out.println(difference);
System.out.println(product);
System.out.println(quotient);
System.out.println(remainder);
System.out.println(result);
System.out.println(a);
}
}Answer
13
7
30
3
1
16
11Step-by-step explanation
10 + 3is13.10 - 3is7.10 * 3is30.Integer division
10 / 3gives3; the decimal part is discarded.10 % 3gives1, because 1 is the remainder.a + b * 2becomes10 + 6, because multiplication happens before addition.a++increasesafrom10to11.
How to read the important code
a++;Say:
"Increment a."
or:
"Increase a by one."
Beginner trap
This:
10 / 3with two int values gives:
3not:
3.333...Key takeaway
Operators perform calculations, and Java follows operator precedence when evaluating expressions.
Chapter 6 — Strings & Basic Text Processing
Question
Given below is a code snippet that:
Creates strings.
Combines strings.
Uses string methods.
Compares string content correctly.
Demonstrates string immutability through reassignment.
What should be the output of the following code?
class Main {
public static void main(String[] args) {
// Create a user's name.
String firstName = "Alice";
// Create another piece of text.
String lastName = "Smith";
// Join the two strings.
String fullName = firstName + " " + lastName;
// Count the characters.
int length = fullName.length();
// Convert the name to uppercase.
String upperName = fullName.toUpperCase();
// Check the actual text content.
boolean same = fullName.equals("Alice Smith");
// Strings do not change themselves.
// This creates a new String value and assigns it to fullName.
fullName = fullName + " Jr.";
// Display the results.
System.out.println(fullName);
System.out.println(length);
System.out.println(upperName);
System.out.println(same);
}
}Answer
Alice Smith Jr.
11
ALICE SMITH
trueStep-by-step explanation
firstNamecontains"Alice".lastNamecontains"Smith".+joins strings.fullNametherefore becomes"Alice Smith"."Alice Smith"contains 11 characters, including the space.toUpperCase()produces a new string:"ALICE SMITH".equals()checks whether the actual text is the same.fullName.equals("Alice Smith")istrue.fullName = fullName + " Jr."creates a new string value and assigns it back tofullName.
How to read the important code
String fullName = firstName + " " + lastName;Say:
"Create a String called fullName by joining firstName, a space, and lastName."
Beginner trap
Don't normally compare String contents using:
name1 == name2Use:
name1.equals(name2)== is about whether two references refer to the same object; equals() is designed to compare String content.
Key takeaway
Strings represent text, and String methods generally produce new String values rather than changing the original String.
Chapter 7 — User Input
Question
Given below is a code snippet that:
Creates a
Scanner.Reads text from the keyboard.
Reads an integer.
Uses the input in calculations.
What should be the output if the user enters Alice and then 3?
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// Create a Scanner that reads from the keyboard.
Scanner scanner = new Scanner(System.in);
// Ask the user for a name.
System.out.print("Enter your name: ");
// Read one word from the user.
String name = scanner.next();
// Ask the user for a quantity.
System.out.print("Enter quantity: ");
// Read an integer from the user.
int quantity = scanner.nextInt();
// Calculate the total.
int total = quantity * 100;
// Display the result.
System.out.println("Hello " + name);
System.out.println("Total: " + total);
// Close the Scanner.
scanner.close();
}
}Answer
Enter your name: Alice
Enter quantity: 3
Hello Alice
Total: 300Step-by-step explanation
Scannerallows Java to read input.System.inrepresents standard input, normally the keyboard.next()reads the next word.nextInt()reads an integer.The user enters
Alice, sonamebecomes"Alice".The user enters
3, soquantitybecomes3.3 * 100produces300.The program prints the greeting and total.
How to read the important code
Scanner scanner = new Scanner(System.in);Say:
"Create a Scanner called scanner that reads from standard input."
Beginner trap
next() reads one word. For an entire line containing spaces, you'll commonly use nextLine().
Key takeaway
Scanneris a simple way to read user input from the console.
Chapter 8 — Type Conversion & Type Casting
Question
Given below is a code snippet that:
Converts an
intto adouble.Demonstrates automatic widening conversion.
Demonstrates explicit narrowing casting.
Shows how integer division differs from decimal division.
What should be the output of the following code?
class Main {
public static void main(String[] args) {
// Store a whole number.
int number = 10;
// Java automatically converts int to double here.
double decimalNumber = number;
// Convert the decimal value to int explicitly.
// The decimal portion is discarded.
int wholeNumber = (int) 12.9;
// Integer division happens because both operands are ints.
int integerResult = 5 / 2;
// Convert one operand to double before division.
double decimalResult = 5 / 2.0;
// Display the results.
System.out.println(decimalNumber);
System.out.println(wholeNumber);
System.out.println(integerResult);
System.out.println(decimalResult);
}
}Answer
10.0
12
2
2.5Step-by-step explanation
numberis anintcontaining10.Java can safely put that whole number into a
double, sodecimalNumberbecomes10.0.(int) 12.9explicitly converts the decimal to an integer.The
.9is discarded, producing12.5 / 2uses integer division because both values are integers.Therefore the result is
2.5 / 2.0uses decimal arithmetic because one operand is adouble.Therefore the result is
2.5.
How to read the important code
int wholeNumber = (int) 12.9;Say:
"Declare an int called wholeNumber and cast 12.9 to int."
Beginner trap
Casting a decimal to an integer does not round normally.
(int) 12.9 → 12
(int) 12.1 → 12Key takeaway
Type conversion changes a value from one compatible type to another, and casting explicitly tells Java to perform a conversion.
Chapter 9 — Boolean Logic
Question
Given below is a code snippet that:
Uses comparison operators.
Creates boolean expressions.
Uses logical AND.
Uses logical OR.
Uses logical NOT.
What should be the output of the following code?
class Main {
public static void main(String[] args) {
// Store a user's age and account status.
int age = 25;
boolean verified = true;
// Check whether the user is an adult.
boolean adult = age >= 18;
// Both conditions must be true.
boolean canEnter = age >= 18 && verified;
// At least one condition must be true.
boolean specialAccess = age < 18 || verified;
// ! reverses a boolean value.
boolean notVerified = !verified;
// Display the results.
System.out.println(adult);
System.out.println(canEnter);
System.out.println(specialAccess);
System.out.println(notVerified);
}
}Answer
true
true
true
falseStep-by-step explanation
age >= 18means "is age greater than or equal to 18?"25 >= 18istrue.age >= 18 && verifiedrequires both sides to be true.Both are true, so
canEnteristrue.age < 18 || verifiedrequires at least one side to be true.age < 18is false, butverifiedis true.Therefore the whole OR expression is true.
!verifiedreversestruetofalse.
How to read the important code
age >= 18 && verifiedSay:
"Age is greater than or equal to 18 and verified."
Beginner trap
&& means both conditions must be true.
|| means at least one condition must be true.
Key takeaway
Boolean expressions produce
trueorfalseand are the foundation of decision-making in programs.
Chapter 10 — if, else if & else
Question
Given below is a code snippet that:
Uses conditional execution.
Checks multiple conditions.
Demonstrates
else if.Demonstrates that only the first matching branch executes.
What should be the output of the following code?
class Main {
public static void main(String[] args) {
// Store a student's score.
int score = 82;
// Check the score from highest range to lowest range.
if (score >= 90) {
// This block runs for scores of 90 or more.
System.out.println("A");
} else if (score >= 75) {
// This block handles scores from 75 through 89.
System.out.println("B");
} else if (score >= 60) {
// This block handles scores from 60 through 74.
System.out.println("C");
} else {
// This handles everything below 60.
System.out.println("D");
}
}
}Answer
BStep-by-step explanation
scoreis82.Java checks
score >= 90.82 >= 90is false.Java moves to the
else if.82 >= 75is true.Java prints
B.The remaining branches are skipped.
How to read the important code
"If score is greater than or equal to 90, print A; otherwise, if score is at least 75, print B; otherwise..."
Beginner trap
Once an if/else if branch is successfully executed, Java doesn't continue checking later else if branches.
Key takeaway
Conditional statements allow your program to choose which code should execute based on a condition.
Chapter 11 — switch
Question
Given below is a code snippet that:
Uses a
switch.Matches a value against cases.
Uses
break.Demonstrates
default.Shows modern arrow-style
switchcases.
What should be the output of the following code?
class Main {
public static void main(String[] args) {
// Store the user's selected menu option.
int option = 2;
// Choose an action based on option.
switch (option) {
// Case 1 matches option 1.
case 1 -> System.out.println("Profile");
// Case 2 matches option 2.
case 2 -> System.out.println("Orders");
// Case 3 matches option 3.
case 3 -> System.out.println("Settings");
// Run this if no case matches.
default -> System.out.println("Invalid option");
}
}
}Answer
OrdersStep-by-step explanation
optioncontains2.Java evaluates the
switch.It looks for a case matching
2.case 2matches.Java prints
Orders.The other cases don't execute.
How to read the important code
"Switch on option. If it's 1, print Profile; if it's 2, print Orders; if it's 3, print Settings; otherwise print Invalid option."
Beginner trap
Traditional switch syntax often uses break to prevent fall-through. The arrow-style syntax shown here avoids that particular problem.
Key takeaway
switchis useful when one value needs to be compared against several specific choices.
Chapter 12 — for Loops
Question
Given below is a code snippet that:
Uses a
forloop.Initializes a counter.
Checks a loop condition.
Increments the counter.
Uses the counter to calculate values.
What should be the output of the following code?
class Main {
public static void main(String[] args) {
// Repeat the block for numbers 1 through 5.
for (int i = 1; i <= 5; i++) {
// Calculate the square of the current number.
int square = i * i;
// Display the current number and its square.
System.out.println(i + " -> " + square);
}
}
}Answer
1 -> 1
2 -> 4
3 -> 9
4 -> 16
5 -> 25Step-by-step explanation
A for loop has three important parts:
for (initialization; condition; update)int i = 1runs once at the beginning.Java checks
i <= 5.If true, the loop body executes.
squareis calculated.The result is printed.
i++increasesi.Java checks the condition again.
This continues until
ibecomes6.6 <= 5is false, so the loop ends.
How to read the important code
"A for loop: initialize i to one, continue while i is less than or equal to five, and increment i."
Beginner trap
The loop doesn't execute when the condition becomes false. The condition is checked before each iteration.
Key takeaway
A
forloop is ideal when you know the basic counting/repetition pattern you need.
Chapter 13 — while & do-while Loops
Question
Given below is a code snippet that:
Uses a
whileloop.Uses a
do-whileloop.Demonstrates the difference between checking before and after execution.
What should be the output of the following code?
class Main {
public static void main(String[] args) {
// Start a counter at 1.
int i = 1;
// Continue while the condition is true.
while (i <= 3) {
// Print the current value.
System.out.println("while: " + i);
// Increase the counter.
i++;
}
// Start another counter at 5.
int j = 5;
// The do block executes before the condition is checked.
do {
// Print the current value.
System.out.println("do: " + j);
// Increase the counter.
j++;
} while (j < 5);
}
}Answer
while: 1
while: 2
while: 3
do: 5Step-by-step explanation
istarts at1.The
whilecondition is checked first.1 <= 3is true, so the body executes.The loop repeats for
2and3.When
ibecomes4,4 <= 3is false.The
whileloop stops.jstarts at5.The
doblock executes immediately.It prints
do: 5.jbecomes6.Java checks
6 < 5, which is false.The
do-whileloop stops.
How to read the important code
"Do this block first, then continue while j is less than five."
Beginner trap
A do-while loop always executes its body at least once, even if the condition is initially false.
Key takeaway
whilechecks before execution;do-whileexecutes once before checking.
Chapter 14 — break, continue & Nested Loops
Question
Given below is a code snippet that:
Uses nested loops.
Uses
continue.Uses
break.Demonstrates how these statements affect loop execution.
What should be the output of the following code?
class Main {
public static void main(String[] args) {
// Outer loop represents rows.
for (int row = 1; row <= 3; row++) {
// Inner loop represents columns.
for (int column = 1; column <= 4; column++) {
// Skip column 2.
if (column == 2) {
continue;
}
// Stop the inner loop when column reaches 4.
if (column == 4) {
break;
}
// Print the current position.
System.out.println(row + "," + column);
}
}
}
}Answer
1,1
2,1
3,1Step-by-step explanation
For each row:
columnstarts at1.column == 2is false.column == 4is false.Java prints the position.
columnbecomes2.continueskips the remaining code in that iteration.columnbecomes3.Java reaches the
print.Wait—there is an important detail: the code as written would actually print
row,3too.
Therefore, the correct output is:
1,1
1,3
2,1
2,3
3,1
3,3The break happens when column reaches 4.
How to read the important code
continue;Say:
"Skip this iteration and move to the next iteration."
break;Say:
"Break out of this loop."
Beginner trap
continue does not stop the entire loop. It skips the current iteration.
break stops the nearest enclosing loop.
Key takeaway
continueskips an iteration;breakexits the current loop.
Chapter 15 — Methods & return
Question
Given below is a code snippet that:
Defines methods.
Calls methods.
Uses parameters.
Returns values.
Reuses a method multiple times.
What should be the output of the following code?
class Main {
// This method receives two numbers and returns their sum.
static int add(int first, int second) {
// Calculate and return the result.
return first + second;
}
// This method receives a price and quantity and returns the total.
static int calculateTotal(int price, int quantity) {
// Multiply the values and return the result.
return price * quantity;
}
public static void main(String[] args) {
// Call add() and store the returned value.
int sum = add(10, 20);
// Call calculateTotal() with different arguments.
int total = calculateTotal(50, 3);
// Display both results.
System.out.println(sum);
System.out.println(total);
}
}Answer
30
150Step-by-step explanation
add(10, 20)calls theaddmethod.firstreceives10.secondreceives20.return first + secondproduces30.sumreceives that returned value.calculateTotal(50, 3)is called.pricebecomes50.quantitybecomes3.The method returns
150.totalreceives150.
How to read the important code
static int add(int first, int second)Say:
"Define a static method called add that takes two ints and returns an int."
int sum = add(10, 20);Say:
"Call add with 10 and 20 and assign the returned value to sum."
Beginner trap
A parameter is the variable defined by the method:
int firstAn argument is the actual value supplied when calling it:
add(10, 20)Key takeaway
Methods package reusable behavior, and
returnsends a value back to the code that called the method.
Chapter 16 — Method Parameters, Overloading & Varargs
Question
Given below is a code snippet that:
Uses method parameters.
Demonstrates method overloading.
Uses variable-length arguments.
Shows Java choosing the appropriate overloaded method.
What should be the output of the following code?
class Main {
// Method version 1: accepts two integers.
static int add(int a, int b) {
return a + b;
}
// Method version 2: accepts two doubles.
static double add(double a, double b) {
return a + b;
}
// Varargs allows zero or more integers.
static int addAll(int... numbers) {
// Start the total at zero.
int total = 0;
// Visit every supplied number.
for (int number : numbers) {
total += number;
}
// Return the final total.
return total;
}
public static void main(String[] args) {
// Java selects the int version.
System.out.println(add(2, 3));
// Java selects the double version.
System.out.println(add(2.5, 3.5));
// Varargs receives three integers.
System.out.println(addAll(1, 2, 3, 4));
}
}Answer
5
6.0
10Step-by-step explanation
There are two
addmethods.They have the same name but different parameter types.
This is called method overloading.
add(2, 3)matches the integer version.add(2.5, 3.5)matches the double version.addAll(1, 2, 3, 4)passes four integers to the varargs parameter.The enhanced
forloop visits each number.1 + 2 + 3 + 4equals10.
How to read the important code
static int addAll(int... numbers)Say:
"Define a method called addAll that accepts a variable number of ints."
Beginner trap
Overloading isn't based merely on changing the return type.
This would not be a valid overload:
int add(int a, int b)
double add(int a, int b)The parameter list needs to differ.
Key takeaway
Overloading lets methods share a name while accepting different parameter lists.
Chapter 17 — Scope & Lifetime of Variables
Question
Given below is a code snippet that:
Demonstrates local variables.
Demonstrates block scope.
Shows that a variable declared inside a block cannot be used outside it.
Shows separate variables with the same name in different scopes.
What should be the output of the following code?
class Main {
public static void main(String[] args) {
// This variable belongs to the main method's scope.
int value = 10;
// Create a separate block.
{
// This variable belongs only to this block.
int inside = 20;
// Display both accessible variables.
System.out.println(value);
System.out.println(inside);
}
// The block has ended, so inside no longer exists here.
// We can still use value because it belongs to the outer scope.
System.out.println(value);
// This is a new variable named inside.
int inside = 30;
// Display the new variable.
System.out.println(inside);
}
}Answer
10
20
10
30Step-by-step explanation
valueis declared insidemain, so it is available throughout its relevant scope.A new block is created with
{}.insideis declared inside that block.Both
valueandinsidecan be accessed there.The block ends.
insidefrom that block is no longer accessible.valueis still accessible.A new
insidevariable is then created outside the old block.That new variable contains
30.
How to read the important code
"Declare a local variable called value."
and:
"Declare inside inside this block."
Beginner trap
A variable's name does not automatically make it available everywhere. Where it is declared determines its scope.
Key takeaway
Scope determines where a variable can be accessed in a program.
Chapter 18 — Arrays
Question
Given below is a code snippet that:
Creates an array.
Stores multiple values of the same type.
Accesses elements by index.
Uses
length.Traverses the array with an enhanced
forloop.
What should be the output of the following code?
class Main {
public static void main(String[] args) {
// Create an array containing four prices.
int[] prices = {100, 250, 80, 150};
// Access the first element.
System.out.println(prices[0]);
// Access the third element.
System.out.println(prices[2]);
// Arrays have a fixed length.
System.out.println(prices.length);
// Visit every element in the array.
for (int price : prices) {
// Print the current price.
System.out.println(price);
}
}
}Answer
100
80
4
100
250
80
150Step-by-step explanation
pricescontains four integers.Java array indexes start at
0.prices[0]is100.prices[2]is80.prices.lengthis4.The enhanced
forloop visits each element in order.Therefore all four prices are printed.
How to read the important code
int[] pricesSay:
"An array of ints called prices."
prices[2]Say:
"The element at index two in prices."
Beginner trap
The first element is index 0, not index 1.
For four elements:
index: 0 1 2 3
value: 100 250 80 150Key takeaway
An array stores multiple values of the same type, and indexing starts at zero.
Chapter 19 — Multidimensional Arrays
Question
Given below is a code snippet that:
Creates a two-dimensional array.
Treats it like rows and columns.
Accesses individual elements.
Uses nested loops to traverse it.
What should be the output of the following code?
class Main {
public static void main(String[] args) {
// Create a 2D array representing two rows of products.
int[][] sales = {
{10, 20, 30},
{40, 50, 60}
};
// Access row 0, column 1.
System.out.println(sales[0][1]);
// Visit every row.
for (int row = 0; row < sales.length; row++) {
// Visit every column in the current row.
for (int column = 0; column < sales[row].length; column++) {
// Print the current value.
System.out.print(sales[row][column] + " ");
}
// Move to the next output line after each row.
System.out.println();
}
}
}Answer
20
10 20 30
40 50 60 Step-by-step explanation
salesis a two-dimensional array.It contains two rows.
Each row contains three values.
sales[0][1]means row0, column1.That value is
20.The outer loop visits each row.
The inner loop visits each value within that row.
Every value is printed.
How to read the important code
sales[row][column]Say:
"The value at row and column."
Beginner trap
A two-dimensional Java array is technically an array of arrays. Rows don't have to be the same length, although rectangular arrays are very common.
Key takeaway
Multidimensional arrays allow you to organize arrays into multiple dimensions such as rows and columns.
Chapter 20 — Packages, Imports & Basic Java Organization
Question
Given below is a code snippet that:
Uses an imported Java class.
Demonstrates a package declaration.
Shows how classes can be organized.
Uses a class from Java's standard library.
What should be the output of the following code?
// Put this class inside the com.example.shop package.
package com.example.shop;
// Import Java's ArrayList class so we can use its simple name.
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// Create a list of product names.
ArrayList<String> products = new ArrayList<>();
// Add products to the list.
products.add("Laptop");
products.add("Mouse");
// Print the number of products.
System.out.println(products.size());
// Print the first product.
System.out.println(products.get(0));
}
}Answer
2
LaptopStep-by-step explanation
package com.example.shop;places the class in a named package.Packages help organize Java classes and avoid naming conflicts.
import java.util.ArrayList;tells Java we want to useArrayListby its simple name.new ArrayList<>()creates the list.Two products are added.
size()returns the number of elements:2.get(0)returns the first element:"Laptop".
How to read the important code
import java.util.ArrayList;Say:
"Import ArrayList from java dot util."
Beginner trap
import doesn't download or install a library. It mainly allows you to refer to an already available class using its shorter name.
Key takeaway
Packages organize classes, while imports let you conveniently use classes from other packages.
Chapter 21 — Basic Problem-Solving Patterns & Putting Fundamentals Together
Question
Given below is a code snippet that:
Uses variables and constants.
Reads an array of sales.
Uses a loop.
Uses conditions.
Calls a method.
Calculates a total and average.
Solves a realistic small programming problem.
What should be the output of the following code?
class Main {
// Keep the tax rate in one named constant.
static final double TAX_RATE = 0.10;
// Calculate the total of all sales.
static int calculateTotal(int[] sales) {
// Start the total at zero.
int total = 0;
// Visit every sale.
for (int sale : sales) {
// Add the current sale to the total.
total += sale;
}
// Return the final total.
return total;
}
public static void main(String[] args) {
// Store the sales for the day.
int[] sales = {100, 250, 150, 300};
// Calculate the total using the method.
int total = calculateTotal(sales);
// Calculate the average as a decimal value.
double average = (double) total / sales.length;
// Calculate tax using the constant.
double tax = total * TAX_RATE;
// Determine whether the sales target was reached.
boolean targetReached = total >= 700;
// Display the results.
System.out.println("Total: " + total);
System.out.println("Average: " + average);
System.out.println("Tax: " + tax);
System.out.println("Target reached: " + targetReached);
}
}Answer
Total: 800
Average: 200.0
Tax: 80.0
Target reached: trueStep-by-step explanation
The array contains four sales:
100, 250, 150, 300calculateTotal(sales)sends the array to the method.The enhanced
forloop visits every sale.The total becomes:
100 + 250 + 150 + 300 = 800The method returns
800.sales.lengthis4.(double) totalconverts800to a decimal value before division.800 / 4therefore produces200.0.TAX_RATEis0.10.800 × 0.10produces80.0.total >= 700checks whether800is at least700.The condition is true.
Therefore
targetReachedcontainstrue.
How to read the important code
int total = calculateTotal(sales);Say:
"Call calculateTotal with sales and assign the returned int to total."
for (int sale : sales)Say:
"For each sale in sales..."
static final double TAX_RATE = 0.10;Say:
"Declare a static final double constant called TAX_RATE with the value zero point one."
final means the variable cannot be reassigned after initialization.
Beginner trap
This line is important:
double average = (double) total / sales.length;Without the cast, if both sides were integers, Java would perform integer division.
Key takeaway
Programming is largely about combining simple concepts—data, decisions, repetition, and reusable methods—to solve real problems.
Phase 1 — What You Now Know
You have now covered the complete foundation needed before moving seriously into object-oriented Java.
Java basics
Java program structure
classmainSystem.outprintprintlnComments
Statements
Blocks
Packages
Imports
Data
Variables
Assignment
Primitive types
Literals
Constants
Strings
Arrays
Multidimensional arrays
Operators
Arithmetic
Assignment
Comparison
Logical operators
Increment/decrement
Remainder
Precedence
Type conversion
Casting
Decision making
Boolean expressions
ifelse ifelseswitch
Repetition
forEnhanced
forwhiledo-whilebreakcontinueNested loops
Reusable code
Methods
Parameters
Arguments
Return values
Overloading
Varargs
Scope
Practical programming
Console input
Basic calculations
Arrays + loops
Conditions + loops
Methods + arrays
Constants
Basic problem-solving patterns
The mental model I want you to develop
At this point, don't think of Java as thousands of syntax rules.
Think:
DATA
↓
Variables / Arrays / Strings
↓
PROCESSING
↓
Operators / Methods
↓
DECISIONS
↓
if / switch
↓
REPETITION
↓
for / while
↓
ORGANIZATION
↓
Methods / Packages
↓
SOLVE PROBLEMThat is the foundation on which Phase 2 — Object-Oriented Java + Core Java will be built.
And importantly, Phase 2 will not restart these basics. It will start using them inside increasingly realistic classes, objects, constructors, inheritance, interfaces, polymorphism, encapsulation, exceptions, collections, and generics.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.