What does the dereferenced compilation error in Java mean?

3

In a test code (in Java), the purpose of which was to convert a string to another string by intersecting the letters between uppercase and lowercase letters, I received the error a follow at compile time:

  

error: char can not be dereferenced

     

result = letter.toLowerCase ();

Following is the sample code:

public void solve(String text) {
    int len = text.length();
    StringBuffer buffer = new StringBuffer(len);

    for(int i=0; i<len; i++){
        char letter = text.charAt(i);
        char result;

        if (i % 2 == 0)
            result = letter.toUpperCase(); //error: compile time
        else
            result = letter.toLowerCase(); //error: compile time

        buffer.append(result);
    }

    System.out.println(buffer.toString());
}

solve("Teste");

// Resultado esperado:
// TeStE

Why does the error happen and what does it mean?

    
asked by anonymous 28.12.2014 / 21:51

2 answers

5

The variable letter is a char , which is a primitive data type (an unsigned 16-bit integer). It is not an object. If it were an object (such as String or Character ) you could call methods on it as letter.toUpperCase() . But it is not an object, so this is not possible.

If you work with static utility methods of the Character class, it's easier to convert to uppercase or lowercase as you want:

char letter = text.charAt(i);
char result;

if (i % 2 == 0)
    result = Character.toUpperCase(letter);
else
    result = Character.toLowerCase(letter);

buffer.append(result);
    
28.12.2014 / 22:00
3

You are using a primitive type. The syntax used should take a reference in the variable used and primitive types have no reference, they save the direct value without any reference. So there was a non-reference problem ( dereferenced ). You have to call the static method that does not work with references and pass the character as normal parameter. Directly use the Character class for this.

import java.util.*;
import java.lang.*;

class Ideone {
    public static void main (String[] args) {
        solve("Teste");
    }
    public static void solve(String text) {
        int len = text.length();
        StringBuffer buffer = new StringBuffer(len);

        for(int i=0; i<len; i++){
            char letter = text.charAt(i);
            char result;

            if (i % 2 == 0)
                result = Character.toUpperCase(letter);
            else
                result = Character.toLowerCase(letter);

            buffer.append(result);
        }

        System.out.println(buffer.toString());
    }
}

See running on ideone . The code is cleaner.

    
28.12.2014 / 22:01