String Class (Cont.)


Java uses the + operator for both addition and concatenation. Numbers are added, whereas strings are concatenated. If you add two numbers, the result will be a number:

 int x = 10;
 int y = 20;
 int z = x + y;      // z will be 30 (an integer/number).

If you add two strings, the result will be a string concatenation:

 String x = "10";
 String y = "20";
 String z = x + y;      // z will be 1020 (a String).

If you add a number and a string, the result will be a string concatenation:

 String x = "10";
 int    y = 20;
 String z = x + y;     // z will be 1020 (a String).

For a complete reference of String methods, check Java String Methods Reference.

StringReverse.java (reversing a string without using the reverse method)

 public class  StringReverse {
   public static void  main( String[ ] args ) {
     int  strLength    = args[0].length( );
     // StringBuilder is used to create a modifiable string.
     StringBuilder  sb = new StringBuilder( strLength );

     for ( int i = strLength - 1; i >= 0; i-- )
       // Append the characters one by one to StringBuilder.
       sb.append( args[0].( i ) );

     // Returns the value of a String object.
     String  reverseString = sb.( );
     System.out.println( args[0] + " ⇒ (reverse) ⇒ " + reverseString );
   }
 }
shell> java MyReverse