Tuesday, January 7, 2014

Can you explain it?

+ operator behaves in an interesting manner when used with a combination of String and numbers.

Case 1:

public class InterestingClass {
    public static void main(String[] args) {
        int x=25;
        int y=12;
     
        System.out.println("sum is "+x+y);
    }  
}

OUTPUT:

sum is 2512

Case 2:

public class InterestingClass {
    public static void main(String[] args) {
        int x=25;
        int y=12;
     
        System.out.println("sum is "+(x+y));
    }  
}

OUTPUT:

sum is 37

Case 3:

public class InterestingClass {
    public static void main(String[] args) {
        int x=25;
        int y=12;
     
        System.out.println(x+y+" is sum");
    }  
}

OUTPUT:

37 is sum

Reason:

In Case 1, System.out.println("sum is "+x+y); uses println(String x) method of PrintStream class. Statement "sum is"+x+y is processed from left to right. So it is String+number = String. Hence the output is sum is 2512. Numbers are concatenated with the string.

In Case 2, (x+y) are in brackets, hence bracketed expression is processed before concatenation. Hence, result x+y which is 37 is concatenated with the string "sum is ".

In Case 3, System.out.println(x+y+" is sum"); Expression is processed from left to right, x+y, both are number, it adds the numbers and expression is later evaluated as number+String, which results in 37 is sum.

Enjoy Java :)

Posted by Nancy
@12:33 am 01/08/2014 

No comments:

Post a Comment