+ 2

Why type casting doesn't work with String Type

Please answer this https://code.sololearn.com/c3cuW50Wncy1/?ref=app

7th Oct 2019, 4:22 PM
Gautamkumar Kapadiya
Gautamkumar Kapadiya - avatar
5 Answers
+ 4
Casting to String will work only if the object is a String: Object text ="Hi there" ; String str = (String) text ; https://code.sololearn.com/c27ekjo2qtxY/?ref=app converting int to string can be done this way : "" + num;
7th Oct 2019, 5:21 PM
voja
voja - avatar
+ 2
// used types for casting must be compatible // eg super class and sub class public class Program { public static void main(String[] args) { System.out.println( (Number) 12345 ); //12345 CharSequence c = "12345"; System.out.println( (String) c ); //12345 B b = new B(); System.out.println( ( (A) b ).i); //12345 } } class A { int i = 12345; } class B extends A { int i = 22222; }
7th Oct 2019, 5:13 PM
zemiak
+ 1
zemiak Ah ok, I see what you were going for. Makes sense.
7th Oct 2019, 5:19 PM
Odyel
Odyel - avatar
0
String b=String.valueOf(12345); System.out.println(b.length());
7th Oct 2019, 4:30 PM
zemiak
0
What zemiak said, except dont use b.length() just use b, otherwise if you do String.valueOf(5) System.out.println(b.length()) it would output an int 1 and not a string 5
7th Oct 2019, 5:02 PM
Odyel
Odyel - avatar