Wednesday, November 13, 2019

Java Coding Interview Questions-2

Q- What is output of below program?


Question-1:

Integer intObj1 = new Integer(10);
 System.out.println(intObj1);
// Output: 10


Question-2:

String str = "100";
 Integer intObj2 = new Integer(str);
 System.out.println(intObj2);
 // Output: 100


Question-3:

Integer intObj3 = new Integer("abc");
System.out.println(intObj3);
/*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(MainTest.java:16)*/

Question-4:

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(MainTest.java:11)*/


Question-5:

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(MainTest.java:13)*/

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


Question-6:


Related Tutorials:
Object Type Casting In Java

No comments:

Post a Comment