Training Java – part 1-concatenante string and numbers

It is first topic given execises in Java.

In this example you can see how will be result in print method if it will be set number or string parametr into it. Write this code:

public class Test {
	public static void main(String[] ar )
{	
    int a = 3;
    int b = 2;    

    System.out.print(" (1): ");    System.out.print(" " + 3 + 2 + " ");
    System.out.print(" (2): ");    System.out.print(3 + 2 + " ");
    System.out.print(" (3): ");    System.out.print(" "+3 + 2);
    System.out.print(" (4): ");    System.out.print(3 + 2);
    
         System.out.println();
    
    System.out.print(" (5): ");    System.out.print(" " + a + b + " ");
    System.out.print(" (6): ");    System.out.print(a + b + " ");
    System.out.print(" (7): ");    System.out.print(" "+a + b);
    System.out.print(" (8): ");    System.out.print(a + b);
    
	 System.out.println();
	 
    System.out.print(" (9): ");	   System.out.print(foo() + a + b + foo());
    System.out.print(" (10): ");   System.out.print(a + b + foo());
    System.out.print(" (11): ");   System.out.print(foo() + a + b);

	System.out.println();
		 
    System.out.print(" (12): ");   System.out.print(foo2() + a + b + foo2());
    System.out.print(" (13): ");   System.out.print(a + b + foo2());
    System.out.print(" (14): ");   System.out.print(foo2() + a + b);
}
 public static String foo()
 {
     return "foo";
 }
 public static int foo2()
 {
     return 1;
 }
}

It displays result:
As you can notice, if even one of part of parameter precedes numbers is string , the result will be string. The numbers into it is treat as string and concatenated: 2+4 give 24. But if into parameter are only numbers they are added: 2+4 give 6. And if the numbers precedes string, then number are added and result is concatenate with string following parts in parameter. It is important what is on the left: numbers or string.

 

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.