String Class (Cont.)


You can also use the concat() method to concatenate two strings:

 String firstName = "John ";
 String lastName = "Doe";
 System.out.println( firstName.concat( lastName ) );      // Output: John Doe

Because strings must be written within quotes, Java will misunderstand this string, and generate an error:

 String txt = "We are the so-called "Vikings" from the north.";

The solution to avoid this problem is to use the backslash escape character. The backslash escape character (\) turns special characters into string characters. For example, the sequence \" inserts a double quote in a string:

 String txt = "We are the so-called \"Vikings\" from the north."; 

Other escape sequences are valid in Java:

Code Result Description Code Result Description Code Result Description
\' ' Single quote \" " Double quote \\ \ Backslash
\n New line \r Carriage return \t Tab
\b Backspace \f Form feed

MyString.java (java.lang.String class)

 public class MyString {
   public static void main( String[ ] args ) {
     String  a = "Hello";
     String  b = new String( "Hello" );
     String  c = new String( "Hello" );

     System.out.println( a.equals( b ) );
       //  true   false   error
     System.out.println( b.equals( c ) );
       //  true   false   error
     System.out.println( a == b ); 
       //  true   false   error
     System.out.println( b == c );        
       //  true   false   error
     System.out.println( "Hello" == "Hello" );
       //  true   false   error
   }
 }
   




      A cat has nine lives.