You must Sign In to post a response.
  • Category: Group Discussions

    .java interview questions - 02

    What is casting?
  • #79484
    A common form of explicit type conversion is called Casting.It can make any conversions except string conversions.

  • #79917
    Casting means converting one type to another type.
    When a data type of lower type is converted into higher type casting is done automatically. For ex: from integer to float. The data is not lost.
    But when we convert data from higher to lower we have to specify it explicitly. This is because there is loss of data. Ex from float to integer. The fractional part gets truncated.

  • #80025
    Converting one type to another type is known as casting.

    In java everything is taken as string but String conversion is not possible with other datatype.

    Different datatypes accept different bytes.
    For example int 2 bytes of data.
    Float,double accept 4 bytes of data.

    When casting one datatype of lower level to higher level the casting is done implicity by java converter but down casting is not allowed in java we need to explicity convert it.

    Java allows widening of conversions but narrowing is not.

    For example:
    -> byte, short ,char,int are involved in an expression then byte,char,int are promoted to int .//this is known as widening

    for int ,long the result would be long.
    for int ,float the result would be float.
    float,double the result is double.

    for downcasting we need it to convert to one type
    for example we declared variable as int and the result that is expected is double we need to conver it by casting

    int a=Double.parseDouble(b);//while taking input from command line

    --->Assignment lead to conversions.
    --->Expression involving mixed datatypes.
    --->During method invocation.

  • #80047
    Down Casting is nothing but casting down the inheritance
    tree to a more specific class i.e casting a superclass to
    Upcasting- casting up the inheritance tree to a more general
    type. It is done implicitly (i.e typing in the cast is not
    required). Its because the classes at lower level of
    hierarchy have all those features that are present in the
    classes above them in the inheritance hierarchy. So they can
    be upcasted implicitly ( like Dog IS-A Animal).

    I got this answer
    with example.

  • This thread is locked for new responses. Please post your comments and questions as a separate thread.
    If required, refer to the URL of this page in your new post.