Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type casting in Java [duplicate]

Possible Duplicate:
Any idea why I need to cast an integer literal to (int) here?

package typecastingpkg;

public class Main
{        
    public static void main(String[] args)
    {
       byte a=10;
       Integer b=(int)-a;
       System.out.println(b);

       int x=25;
       Integer c=(Integer)(-x); // If the pair of brackets around -x are dropped, a compile-time error is issued - illegal start of type.
       System.out.println(c);

       Integer d=(int)-a;     //Compiles fine. Why does this not require a pair of braces around -a?
       System.out.println(d);
    }
}

In this code, while casting of -x of primitive type int to a wrapper type Integer, a compile-time error is produced: illegal start of type.

Integer c=(Integer)-x;

It requires a pair of braces around -x like Integer c=(Integer)(-x);

The following expression however compiles fine.

Integer d=(int)-a;

Why does this one not require a pair of braces around -a as in the preceding expression?

like image 629
Tiny Avatar asked Oct 09 '12 21:10

Tiny


People also ask

Can you double cast Java?

In Java when you cast you are changing the “shape” (or type) of the variable. The casting operators (int) and (double) are used right next to a number or variable to create a temporary value converted to a different data type. For example, (double) 1/3 will give a double result instead of an int one.

What is the problem with type casting in Java?

In the case of Narrowing Type Casting, the higher data types (having larger size) are converted into lower data types (having smaller size). Hence there is the loss of data. This is why this type of conversion does not happen automatically.

Why is clone () method used in Java?

The clone() method is used to create a copy of an object of a class which implements Cloneable interface. By default, it does field-by-field copy as the Object class doesn't have any idea about the members of the particular class whose objects call this method.


3 Answers

The compiler thinks that, in the expression (Integer)-x, you are trying to subtract x from a variable called Integer, hence the error since no such variable is defined. (int)-x works because int is a reserved keyword for a primitive type and cannot be used as a variable name, so the compiler can deduce that you are trying to cast, not subtract.

like image 187
arshajii Avatar answered Nov 04 '22 03:11

arshajii


The answer can be found by examining Java's grammar:

CastExpression:
    ( PrimitiveType ) UnaryExpression
    ( ReferenceType ) UnaryExpressionNotPlusMinus

Which tells you that you can use a cast expression like (int) -x; because int is a primitive type and so you can have a unary expression that follows it. However, if you use an object then that's a ReferenceType and the only thing that follows a ReferenceType is UnaryExpressionNotPlusMinus, which doesn't include things like -x or +x:

UnaryExpressionNotPlusMinus:
    PostfixExpression
    ~ UnaryExpression
    ! UnaryExpression
    CastExpression

The reason for this prohibition is that Integer by itself could be interpreted as an identifier, which leads to ambiguity. int cannot be interpreted as an identified because it is a reserved word. To resolve this ambiguity, you would have to wrap the unary expression in parenthesis.

like image 27
Vivin Paliath Avatar answered Nov 04 '22 05:11

Vivin Paliath


You cannot cast primitive to class and vice versa.

You can cast primitives to other primitives. In this case value precision can be lost. For example if you are casting long to int.

You can also cast object to other type.

Actually assignment of primitive wrapper types to primitives is allowed since java 1.5 by autoboxing and can confuse. This is just a compiler sugar. When you say

Integer a = 5; compiler translates it to Integer a = new Integer(5);

If you say then

int b = a; you really say int b = a.intValue();

Unfortunately operators like +, - etc are not working with primitive wrappers. Only primitives support them. So, you cannot say -a. You must say (-1)*a.intValue(). Now this value can be assigned to either int or Integer variable: autoboxing will do the job.

like image 1
AlexR Avatar answered Nov 04 '22 05:11

AlexR