Type Conversion and Casting

Q)
  Which one is valid in the following?
      int a=3.14;// INVALID
     double d=35;//VALID

Tell me the reason,
Ans: As per the behavior of java data types I am listing out the order(numeric/integral): (smaller to larger)
                          byte
                          short
                          int
                          long
                         float
                        double
(So, we can not assign larger type value to a smaller type variable.)


In java, we have two kinds of conversions:
  1. Implicit/Automatic conversion/coercion (widening conversion )
  2. Explicit conversion(narrowing conversion)

Implicit conversion
Q) When the automatic conversion will take place in java?
Ans: if the following two conditions are met:
  1. The two types are compatible.

  2. The destination type is larger than the source type.
Ex: double d=34;// here source is 34(int) and destination is d(double).

Q) Are double and boolean compatible?
Ans: No
Q) Are int and char compatible?
Ans: Yes
Q) Are double and char compatible?
Ans: No
Q) Can I assign char type value to int type variable?
Ans: Yes (Here, its UNICODE value will be assigned)

Explicit conversion (Type casting)
To create a conversion between two incompatible types, you must use a cast.
A cast is simply an explicit type conversion.
It has this general form:
                        (target-type) value
Here, target-type specifies the desired type to convert the specified value to.

Ex: int i=300.33;// before casting
    int i=(int)300.33;//after casting

Observations:
  1.  byte b1=(byte)300;// b1 value will be 300%256( here, 256 is the range of values of byte type).
  2. byte b2=(byte)345.43;// It first truncates the fractional part-->then 345 will be remained                                                        -->then it performs 345%256(this will be the value of b2).
  3. int i=(int)456.23;// just it truncates the fractional part.So, 456 will be the result.


Automatic Type Promotion in Expressions in JAVA:
üJava automatically promotes each byte, short, or char operand to int when evaluating an expression.
üIf one operand is a long, the whole expression is promoted to long.
üIf one operand is a float, the entire expression is promoted to float.
üIf any of the operands is double, the result is double.


Comments

Popular posts from this blog

Data types: