Wednesday, November 13, 2019

Java Coding Interview Questions-2

Q- What is output of below program?


Integer intObj1 = new Integer(10);
// Output: 10


String str = "100";
 Integer intObj2 = new Integer(str);
 // Output: 100


Integer intObj3 = new Integer("abc");
/*Output: Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.<init>(Unknown Source)

at corejavaExample.MainTest.main(*/


List<Object> objList = new ArrayList<Object>();
List<String> strList = new ArrayList<String>();
objList = strList;

/*Output: Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Type mismatch: cannot convert from List<String> to List<Object>
at corejavaExample.MainTest.main(*/


Object object = new Object();
String string = new String();
object = string;  // Yes this is perfectly possible
string = object;  // this is wrong because we are casting parent to child
/*Output:- Exception in thread "main" java.lang.Error: Unresolved compilation problem:
            Type mismatch: cannot convert from Object to String
at corejavaExample.MainTest.main(*/

Solution:- Here we need to do explicit object type casting.
string = (String) object;


Related Tutorials:
Object Type Casting In Java

No comments:

Post a Comment