Skip to main content
Lesson 13 - String Class
Lesson MenuPreviousNext
  
Strings and Characters page 8 of 12

  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 a reference type and a char is a primitive type. Some of the limitations of this incompatibility are:

    1. You cannot pass a char argument to a String parameter (nor the opposite).
    2. You cannot use a char constant in place of a String constant.
    3. You cannot assign a char expression to a String variable (nor the opposite).

    The last restriction is particularly troublesome, because there are many times in programs when char data and String data must be used cooperatively.

  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, the following expression

    "" + 'X';

    evaluates to a String of length 1, consisting of the letter "X"

    // charVar is a variable of type char
    // stringVar is a variable of type String
    stringVar = "" + charVar;
    

    The execution of this instruction assigns to stringVar a String object that consist of the single character from charVar.


Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.