Character behaviour in Java

Today we will discuss some coding practices with characters and Strings.

Can you guess the output of the below code:

public static void main(String args[])

{
String str="stark: 8";
String str2= "stark: "+str.length();
System.out.println("strings are equal "+str==str2);
}

Many people will think the output will be strings are equal true, well, its not because whenever we use "==" operator, it checks whether the references of the two strings are equal or not, it doesn't check if the values are equal or not.
So now you might be thinking that the output will be strings are equal false, again the output will be different, if you ran the program now you will see false. It doesn't print strings are equal. where's our string literal now ? Here the compiler will treat the statement as below:

System.out.println(("strings are equal "+str)==str2);

This performs the concatenation between strings are equal and str, then compares the references of ("strings are equal "+str) and str2, which will results in output false.

So how do we solve the problem now, there's a solution, we have equals method to compare the values of string literals. Lets see how it works.

System.out.println("strings are equal "+str.equals(str2));


This will print the expected output now:

strings are equal true

Comments

Popular posts from this blog

Integer.MAX_VALUE, Double.POSITIVE_INFINITY and Double.NaN in Java