int x = 5;
x = x + 3;
System.out.println(x);
8
The variable x starts at 5, then 3 is added to it, making the final value 8.
for (int i = 0; i < 3; i++) {
System.out.println(i);
}
0,1,2
The loop starts at 0 and runs while i < 3, printing i each time. It stops before reaching 3.
int x = 7;
if (x > 5) {
System.out.println("High");
} else {
System.out.println("Low");
}
High
Since 7 is greater than 5, the condition is true and "High" is printed.
int x = 5;
if (x = 3) {
System.out.println("Yes");
}
The = operator is used instead of ==.
= assigns a value, while == checks for equality. This causes a compile-time error.
What is a variable?
A container that stores data in a program.
Variables hold values that can change while the program runs.
int a = 4;
int b = 2;
a = a * b;
b = a - b;
System.out.println(a + " " + b);
8,6
First a becomes 8. Then b becomes 8 - 2, which is 6. Both values are printed.
int sum = 0;
for (int i = 1; i <= 4; i++) {
sum += i;
}
System.out.println(sum);
10
The loop adds numbers 1 through 4 to sum (1+2+3+4), which equals 10.
int score = 85;
if (score >= 90) {
System.out.println("A");
} else if (score >= 80) {
System.out.println("B");
} else {
System.out.println("C");
}
B
The score is not 90 or higher, but it is 80 or higher, so the second condition runs.
for (int i = 0; i <= 5; i--) {
System.out.println(i);
}
The loop will never end.
i is decreasing while the condition checks if it is less than or equal to 5, so the condition stays true forever.
What does a loop do in a program?
Repeats a block of code while a condition is true.
Loops are used to avoid repeating code and to automate repetitive tasks.
int num = 10;
if (num % 3 == 0) {
num += 5;
} else {
num -= 2;
}
System.out.println(num);
8
10 is not divisible by 3, so the else block runs and subtracts 2, resulting in 8.
int count = 0;
int i = 5;
while (i > 0) {
count++;
i -= 2;
}
System.out.println(count);
3
The loop runs when i is 5, 3, and 1. Each loop increases count by 1, so it runs 3 times.
int num = 12;
if (num % 2 == 0 && num % 3 == 0) {
System.out.println("Divisible");
} else {
System.out.println("Not Divisible");
}
Divisible
12 is divisible by both 2 and 3, so the && condition is true.
int[] nums = {1, 2, 3};
System.out.println(nums[3]);
The index is out of bounds.
Arrays start at index 0, so the last valid index is 2. Accessing index 3 causes a runtime error.
What is the difference between == and .equals() in Java?
== compares memory locations, while .equals() compares values.
For objects like strings, .equals() checks the actual content, which is usually what you want.