Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot cast from Object to char

Tags:

java

casting

My code works perfectly as far as I can see but I still get the error "Cannot cast from Object to char" and I was wondering if anyone could explain to me what the problem is and if I can do it another way that does not cause an error.

This is the bit of code causing the error char op = (char) term;. It is from an infix to postfix converter

//Take terms off the queue in proper order and evaluate
private double evaluatePostfix(DSAQueue<Object> postfixQueue) {
    DSAStack<Double> operands = new DSAStack<Double>();
    Object term; 

    //While still terms on queue, take term off.
    while(!postfixQueue.isEmpty()) {
        term = postfixQueue.dequeue();
        if(term instanceof Double) { //If term is double put on stack
            operands.push((Double) term);
        }
        else if(term instanceof Character) { //If term is character, solve
            double op1 = operands.pop();
            double op2 = operands.pop();
            char op = (char) term;
            operands.push(executeOperation(op, op2, op1));
        }
    }
    return operands.pop(); //Return evaluated postfix
}

Any help (even pointing me to some reading) would be much appreciated.

like image 302
user2963286 Avatar asked Apr 30 '14 08:04

user2963286


2 Answers

You can change this line:

char op = (Character) term;

Explanation: in Java 6 you can't cast an Object to a primitive type, but you can cast it to Character (which is a class) and unboxing does the rest :)

Edit: Alternatively, you can bump the language level of your project up to Java 7 (or 8...)

like image 170
vikingsteve Avatar answered Nov 17 '22 05:11

vikingsteve


There is nothing wrong with your code. Since term is an instance of Character you could even assign it directly without casting as char op = term if you are using jdk 1.5+

One possibility i could see is the compiler compliance level used. You might have a JDK 1.5+ but you are compiling your project in a lower level. If you are using eclipse check for JDK compliance level in Project->properties->Java Compiler

If you are directly compiling or using Ant build check for -source & -target options.

And just for your info, as far as i know Object to primitive casting was introduced in JDK 1.7. So if you are using JDk 1.7+ you could wirte as

Object term = 'C';
char op = (char) term;
like image 29
Syam S Avatar answered Nov 17 '22 03:11

Syam S