In Java, == and equals() are both used for comparison, but they operate differently. The == operator checks for reference equality, meaning it compares whether two variables point to the same object in memory. In contrast, the equals() method, when properly implemented, compares the content or state of the objects.
So, the main difference between "==" and "equals" in Java is that "==" compares the memory location of two objects, while "equals" compares the contents of two objects.
SWITCH KEYWORD
Below is an example program demonstrating the switch keyword in Java. The switch statement evaluates an expression, matching its value against a series of case labels. If a match is found, the corresponding block of code is executed. The break statement is typically used to exit the switch block after a match, and the default case handles situations where no match is found.
Example 01
package demo_programs;
public class SwitchExample {
public static void main(String[] args) {
int day = 1;
String dayString;
switch (day) {
case 1:
dayString = "Monday";
break;
case 2:
dayString = "Tuesday";
break;
case 3:
dayString = "Wednesday";
break;
default:
dayString = "Invalid day";
}
System.out.println(dayString); // Output: Wednesday
}
}
Remove break from case1, case2, case3?
What happens:
day = 1, so it matches case 1
Since there's no break after case 1, it falls through to case 2
dayString gets overwritten as "Tuesday"
Then it hits break, so it exits the switchMore default just above any case block?
The default case is already definedremove break statement from default?
the local variable dayString may not have been initialized.
4.Instead of using int day, try using float values?
package demo_programs;
public class SwitchExample2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
float day = 3.0f;
String dayString;
if (day == 1.0f) {
dayString = "Monday";
} else if (day == 2.0f) {
dayString = "Tuesday";
} else if (day == 3.0f) {
dayString = "Wednesday";
} else {
dayString = "Invalid day";
}
System.out.println(dayString); // Output: Tuesday
}}
//output Wednesday