10!=2 is getting true and "Hello "+10!=2 compilation error
Problem Description:
I am preparing for Oracle certification exam so could you explain how 10!=2 is getting true and compilation error, I have mention a small program below.
10!=2 : why it is true
"Hello "+10!=2 : why it is compile time error
public class Demo1 {
public static void main(String[] args1) {
System.out.println(10!=2); //Output is True
System.out.println("Hello "+10!=2); //Compile Time Error
}
}
Solution – 1
Please check basics of java and generally programming. ‘==’ sign checks if values are the same, ‘!=’ checks if values are not the same.
So 10!=2 means is 10 different than 2, and you get ‘true’.
Solution – 2
for concat boolean with string in java you first need to store answer in a variable.
try using this.
public static void main(String[] args1) {
boolean a=10!=2;
System.out.println(a); //Output is True
System.out.println("Hello "+a);// Output is Hello true
}