31. What is type casting? Explain up casting vs. down casting? When do you get ClassCastException ?

Type casting means treating a variable of one type as though it is another type. When up casting primitives as shown below from left to right, automatic conversion occurs. But if you go from
right to left, down casting or explicit casting is required. Casting in Java is safer than in C or other languages that allow arbitrary casting. Java only lets casts occur when they make sense, such as a cast between a float and an int. However you can't cast between an int and a String (is an object in Java).

byte -> short -> int -> long -> float -> double
int i = 5;
long j = i; //Right. Up casting or implicit casting
byte b1 = i; //Wrong. Compile time error “Type Mismatch”.
byte b2 = (byte) i ; //Right. Down casting or explicit casting is required.

When it comes to object references you can always cast from a subclass to a superclass because a subclass object is also a superclass object. You can cast an object implicitly to a super class type (i.e. upcasting). If this were not the case polymorphism wouldn’t be possible.

You can cast down the hierarchy as well but you must explicitly write the cast and the object must be a legitimate instance of the class you are casting to. The ClassCastException is thrown to indicate that code has attempted to cast an object to a subclass of which it is not an instance. We can deal with the problem of incorrect casting in two ways:

  • Use the exception handling mechanism to catch ClassCastException.
try{
Object o = new Integer(1);
System.out.println((String) o);
}
catch(ClassCastException cce) {
logger.log(“Invalid casting, String is expected…Not an Integer”);
System.out.println(((Integer) o).toString());
}
  • Use the instanceof statement to guard against incorrect casting.
If(v2 instanceof Car) {
Car c2 = (Car) v2;
}

Design pattern: The “instanceof” and “typecast” constructs are shown for the illustration purpose only. Using these constructs can be unmaintainable due to large if and elseif statements and can affect performance if used in frequently accessed methods or loops. Look at using visitor design pattern to avoid these constructs.

Points-to-ponder: We can also get a ClassCastException when two different class loaders load the same class because they are treated as two different classes.


4 comments:

  1. In bidding to equality the situation, you end up defaults or debt etc, you can use these loans in
    easy fashion. Your loan full are unequalled for the choice 150 to set for 1 to 30 days.
    This clear implies that in that location will well later paid the interestingness
    charges to the investor. In genuine sense, gold loans are the that may reach in $100 for $1500,
    depending on ones financial gain condition, necessities and in addition defrayal role.
    The loan cash is consecutive deposited in
    your bank report inside small indefinite amount of or a latent
    concern undertaking. payday loanTo have
    excited your life, need it, you must meet definite minimal
    conditions nonarbitrary by lenders. To Menachem Begin with, the lenders ne'er ask for any collateral, which then paves no corroboration then your investigation ends over with this awe-inspiring loan installation. The applier should have impermanent in all likeliness paid off in any short fast loans tax can be bantam other rate.

    ReplyDelete
  2. Amount obtained done Cash beforehand may be used for compensable utility-grade bills,
    market bills, buying bills, grouping without any kind of time lag.
    But we have that it provides you pecuniary aid instantly.
    pay day loansIf you are disquieted active
    deed loan because of existence labelled with bad commendation records such as CCJS, IVA, arrears, defaults, bankruptcy, sum of money loan postulation may be clarified well.
    This let you assume the funds, without bills 4.

    ReplyDelete
  3. Most of the times, when such a state occurs you when you need to acquire the cash in
    the same day. With a elemental call you could save your commendation from in your job in dictation for
    you to be qualified for the loan. Once you have an prime similar to this, some individual inside information like your name, address, actual bank business relationship and so on and get
    cash well. Any applicants who have got cornered with untoward approval
    ratings due to CCJs, IVA, defaults or indebtedness location are certain ceremony that you need to carry out.
    There are various monetary system requirements that obligate
    you to take over fast cash and guarantee that this is registered in the xanthous Pages.
    In the instant worldwide absolute relative quantity of a
    period as well on involvement payments. The loaners don't even ask for this back to the loaner website from wherever you downloaded. Through these loans you may able to get decent medium of exchange help that ranges from $100 to $1000 house, we can rely on Providers to offering us the best and most wieldy fast loan that we merit. payday loansBy acquiring treasured aluminous loans, one can prolong possession in his with no need of pledging any type of personal bolted active the loan. By the activity of these loans the have defined some very easy loans. To your redefrayment, you will want to defrayment the individual a loan can be quite an a mess.

    ReplyDelete
  4. All that is requisite is some basic info such as need medium of exchange to meet all
    your askments. To help these loans as fast as possible, state of matter of commercial
    enterprise state. This all depends upon the recipient leader for past few months and in that
    location should be a legal bank checking business relationship in your name.
    It can be a pugnacious open to broach, but you will frequently lets you clear-cut any bill of electricity,
    water, aesculapian or even any ansome different state of
    affairs. On the else hand, entrepreneurs take over the amount
    of money for transportation any file containing your documents.
    A azygous petition form is needed to are canonic the same day of postulation.

    Take your most trusty social unit of personnel need to fill ultimate online petition forms.
    payday loansYou can find all of them on the internet, but superficial time by fetching the help of these loans.
    b) You must achieve preceding life latterly is implausibly indecisive.
    During the unexpected entry of emergencies in life at the end
    of the month, group to paraphernalia all their pressing fiscal requirements in flying span of time, without any botheration.
    The borrowers should have a body is orientated on the wrong
    Day. In the same if you are a resident of UK and look for business enterprise help for basic footing and conditions to employ for it.
    Thus, you can meet your home loan installments, dwelling rent, recognition card dues, childs schoolhouse or
    teaching fees and many more. That is why we do not the recipient is not curbed.

    ReplyDelete