Thursday, 10 January 2013

Java: String Concatention Precedence

With the ability of Java to concatenate strings using the plus (+) sign, a common mistake that new programmers may face is the mix up of adding integers and strings. Let me show you a sample.

Consider the following code:

public class StringConcatTest { 
   public static void main(String[] args){
       int firstNum = 10;
       int secNum = 5;    
       System.out.println(firstNum + secNum + " total number of apples.");
       System.out.println("Total number of apples: " + firstNum + secNum);       
   }
} 

OUTPUT:
15 total number of apples.
Total number of apples: 105 


Clearly, the second sentence is incorrect.

0 comments:

Post a Comment