Skip to main content
ICT
Lesson A10 - The String Class
 
Main   Previous Next
 

I. Strings and Characters page 11 of 17

  1. It is natural to think of a char as a String of length 1. Unfortunately, in Java the char and String types are incompatible since a String is an object and a char is a primitive type. This means that you cannot use a String in place of a char or use a char in place of a String.

  2. Extracting a char from within a String can be accomplished using the charAt method as previously described.

  3. Conversion from char to String can be accomplished by using the "+" (concatenation) operator described previously. Concatenating any char with an empty string (String of length zero) results in a string that consists of that char. The java notation for an empty string is two consecutive double quotation marks. For example, to convert myChar to a String it is added to “”.

    char myChar = 'X';
    String myString = "" + myChar;
    System.out.println(myString);
    char anotherChar = 'Y';
    myString += anotherChar;
    System.out.println(myString);

    The output of this block of code would be:

    X
    XY

 

Main   Previous Next
Contact
 © ICT 2006, All Rights Reserved.