"+" between Integer and String

"+" between Integer and String:

what will happend if System.out.println(10+5 + "=" +10+5)?

public class Test{
    
public static void main(String[] args) {
        
System.out.println(10+5 + "=" +10+5);                                                  
    }
}

output-

15=105

 This is very tricky question number of time. he reason behind this program – Initially the integers are added and  we get the left side value is 15. But, as soon as a string is encountered it is appended and we get “50=” . Now the integers after ‘=’ are also considered as a string and so are appended.
 

To make the output 15=15, we need to add a bracket around the sum statement to overload the concatenation operation.

This will enforce the sum to happen before string concatenation as bracket as the highest precedence.

public class Test{
    
public static void main(String[] args){
        
System.out.println(10+5 + "=" +(10+5));                                               
    }
}

output-

15=15

Related Articles

post a comment