Free SCJP ebook!

Free SCJP Mock exams!( Registration required)
The free SCJP ebook
Witscale Test Center

Previous Page Next Page Contents Index

Valid XHTML 1.0!

Conversion, Casting and Promotion

Conversion and casting
  • Type incompatibility
    Every java expression has a type. The type is based on the expression and the types of the operands (literals, variables, and methods) in that expression. We can write an expression in a context where the type is not appropriate.
    In some cases, this leads to compile time errors.

    For example,
    if(someCondition) {
    // do something
    }
    If the type of someCondition is other than boolean, a compile-time error occurs.
  • Implicit type conversion
    The context may accept a type that is compatible to the type of the expression; as a convenience, rather than requiring the programmer to indicate a type conversion explicitly.
    Java performs an implicit/automatic conversion from the type of the expression to a type acceptable in that context.
  • Conversion rules
    Java has certain rules for these types of implicit conversions. Programmer may do explicit conversion, which is generally called as casting.
[More in ebook]

Conversion Contexts

Following conversion contexts define different situations in which implicit conversions occur.
  • Assignment conversion
  • Method invocation conversion
  • Numeric/Arithmetic promotion
  • String conversion

Casting specifies a special situation in which explicit conversion takes place.

[More in ebook]


Rules for conversion of primitives in assignment.
  1. boolean may not be converted to any other data type.
  2. Non-boolean primitive data types can be converted to non-boolean only if it is widening conversion.

Widening Conversion in primitives
[More in ebook]
  • Widening Conversion.
    Above diagram shows the widening conversions in primitives. Outermost rectangle represents the widest data type of all and innermost represent narrowest of all.
    For example,
    Rectangle representing long contains the rectangle representing int indicated that long is wider data type than int. Thus, int value can be assigned to long variable without any need of explicit casting. For example,
     int a = 4;
     long b = a;
                   
    
    [More in ebook]
  • Incompatible data types. Two independent rectangles indicate that the variable cannot be automatically converted.
    For example,
     byte b = 4;
     short s = b; // valid as short is wider than byte.
     char ch = b; // Invalid as char and byte are incompatible types.
                   
    
    Please note that data type is considered wider if it can represent wider range of numbers. The data type is not wider than other data type just because it has more bits. For example, float (represented with 32 bits) is wider than long (represented with 64 bit) This is due to the fact that float can represent wider range of numbers than long.
  • Few Exceptions to the rule
    You might recall that integral literals are of type int by default. So you may think that byte b = 2; is invalid as 2 is integral literal and integral literals are by default of type int. Therefore byte b = 2 will be narrowing conversion (int ==> byte) and hence will throw an exception.
    However, it is not so.
     byte b = 2; //valid.
                   
    
    Variables of byte type can be assigned any integral literal up to the value -128 to +127 without any need of explicit casting.
    Similarly,
     short s = 2; //valid
     char c = 10; //valid
                   
    
    Please note that these types of conversions are allowed because even if they look like narrowing conversions, there is no loss of information.
    [More in ebook]


Rules for conversion of primitives during the method call.
The rules are same as those of assignment.
  1. boolean may not be converted to any other data type.
  2. Non-boolean primitive data types can be converted to non-boolean only if it is widening conversion.

[More in ebook]

Rules for conversion of primitives during the numeric/arithmetic operations.

Arithmetic Promotions for unary operators.
  1. For ++ and -- operators , there is no conversion.
  2. For unary +, - and ~ , widening conversion happens as variables of type byte, short or char are promoted to int.

Arithmetic Promotions for binary operators.
  1. If one of the operand is double, other is promoted to double before operation.
  2. Else, if one of the operand is float, other is promoted to float before operation
  3. Else, if one of the operand is long, other is promoted to long before operation.
  4. Else, both operands are promoted to int before operation.
Please note that both the operands must be of non-boolean primitive type.
[More in ebook]
Casting of primitive data types

Rules
  1. Any non-boolean to any non-boolean is allowed.
  2. boolean to non-boolean casting is NOT allowed.
  3. Non-boolean to boolean casting is NOT allowed.
[More in ebook]

Object reference Conversion.

Object reference Conversion rules for assignment and method calls are same.

Rule
Any object reference can be converted into other object type provided it is a widening conversion.

Widening reference conversion.

 OldType anObjectRef = new OldType();
 NewType anotherObjectRef = anObjectRef;  //conversion.
               

Object reference conversion specified above is valid ...
  1. If OldType is an interface type then NewType must be the super interface of the OldType.
    Object references (widening conversion)
  2. If OldType is a class, and
    1. If NewType is also a class, it must be the super class of OldType.
      Object reference widening conversion
    2. Alternatively, if NewType is an interface, OldType must implement it.
      Object reference widening conversion
  3. If OldType is an array, NewType can be of type Object or of type Cloneable, Serializable. Alternatively, NewType can be an array of compatible type.


[More in ebook]
Object reference Casting.

Object reference casting rules are different for compile time and runtime.

Compile-Time Rules
(Less strict)
Runtime Rules
(More strict)
  1. If OldType and NewType are classes, then any one of them must be the subclass of the other.
  2. If both are arrays , they must be arrays of object references and data types of array elements must be compatible.(You cannot cast an array of one primitive type to an array of another primitiive type).
  3. You can always cast an interface to a non-final object.
  1. NewType must be the super class of OldType.
  2. If NewType is an interface, OldType must implement it.

[More in ebook]




Related SCJP Objective

Section 4 : Language Fundamentals
  1. Identify correctly constructed package declarations, import statements, class declarations (of all forms including inner classes) interface declarations, method declarations (including the main method that is used to start execution of a class), variable declarations, and identifiers.
  2. Identify classes that correctly implement an interface where that interface is either java.lang.Runnable or a fully specified interface in the question.
  3. State the correspondence between index values in the argument array passed to a main method and command line arguments.
  4. Identify all Java programming language keywords. Note: There will not be any questions regarding esoteric distinctions between keywords and manifest constants.
  5. State the effect of using a variable or array element of any kind when no explicit assignment has been made to it.
  6. State the range of all primitive formats, data types and declare literal values for String and all primitive types using all permitted formats bases and representations.

[More in ebook]

Previous Page Next Page Contents Index Top of this page

Valid CSS!