Popcorn Hacks
- showed popcorn hack 1.1
- popcorn hack 1.1, 2.1, 2.2 are verbal (no code cells needed)
- showed popcorn hack 3
int x = 10;
x = 20;
int y = x;
System.out.println(y);
20
import java.util.Scanner;
public class InputLesson {
public static void main(String[] args) {
System.out.println("=== User Information Program ===\n");
Scanner sc = new Scanner(System.in);
// String input
System.out.print("Enter your full name: ");
String name = sc.nextLine();
// Integer input
System.out.print("Enter your age: ");
int age = sc.nextInt();
// Double input
System.out.print("Enter your GPA: ");
double gpa = sc.nextDouble();
// Display results
System.out.println("\n--- Summary ---");
System.out.println("Name: " + name);
System.out.println("Age: " + age + " (next year: " + (age + 1) + ")");
System.out.println("GPA: " + gpa);
sc.close();
}
}
Homework Hacks
- picked the second homework hack (as the lesson said to choose one)
Assignment Operator (=) vs Comparison Operator (==) in Java
In Java, the symbols =
and ==
look similar but serve very different purposes.
1. Assignment Operator (=)
- Purpose: Assigns a value to a variable.
- Effect: Changes the value stored in that variable.
int x = 5;
String y = "Hello";
System.out.println(x);
System.out.println(y);
5
Hello
2. Comparison Operator (==)
- Purpose: Compares two values for equality.
- Effect: Returns a boolean (
true
orfalse
).
int a = 10;
int b = 20;
System.out.println(a == b);
System.out.println(a == 10);
String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
false
true
false
true
3. Common Bug: Mixing up =
and ==
- A common mistake is to use
=
when you mean==
. - In Java, this won’t raise a syntax error inside
if
statements (unlike Python). - Instead, it changes the variable and the condition may always evaluate as
true
orfalse
.
int z = 3;
// incorrect usage (common mistake):
if (z = 5) {
System.out.println("z is 5");
}
// correct usage:
z = 5;
if (z == 5) {
System.out.println("z is 5");
}
| if (z = 5) { // ❌ Error: incompatible types (int cannot be converted to boolean)
incompatible types: int cannot be converted to boolean