Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Anoop Kumar
1,715 Pointstypecasting in java?
can anyone explain me brief about typecast in java ...i am new in java and a having lot of problem related typecasting ..what is typecasting ? why we typecaste ?etc
1 Answer
Adam Sawicki
15,967 Points- What is typecasting - simply is changing type of REFERENCE to the object. Imagine this
String a = "example";
Object b = a;
Now we have 2 references to the same object, but:
a.charAt(0);
b.charAt(0);
Second line won't work because b is type Object not type String and Object doesn't have method .charAt();. This is the point where typecasting is useful. Because you know that b is reference to STRING you can typecast
b=(String)b;
b.charAt(0);
And now it's all fine.
- Example of usage:
public void someMethod(Object x){ x = (String)x; x.charAt(0); }In this example you pass to the method a string which is typecasted to Object, but inside the method you want to use it as a String so you need to typecast it to String again.
Anoop Kumar
1,715 PointsAnoop Kumar
1,715 Pointsthanks a lot