Output of Java program | Set 5
Predict the output of following Java Programs.
Explanation : In case of method overloading, the most specific method is chosen at compile time. As ‘java.lang.String’ is a more specific type than ‘java.lang.Object’. In this case the method which takes ‘String’ as a parameter is chosen.
Compile Error at line 19.
Explanation: In this case of method Overloading, the most specific method is chosen at compile time.
As ‘java.lang.String’ and ‘java.lang.Integer’ is a more specific type than ‘java.lang.Object’,but between ‘java.lang.String’ and ‘java.lang.Integer’ none is more specific.
In this case the Java is unable to decide which method to call.
abcd abc false abcd abcd true
Explanation : In Java, String is immutable and string buffer is mutable.
So string s2 and s1 both pointing to the same string abc. And, after making the changes the string s1 points to abcd and s2 points to abc, hence false. While in string buffer, both sb1 and sb2 both point to the same object. Since string buffer are mutable, making changes in one string also make changes to the other string. So both string still pointing to the same object after making the changes to the object (here sb2).
Compile Error at line 8
1. In Line 12 The “” in the println causes the numbers to be automatically cast as strings. So it doesn’t do addition, but appends together as string.
2. In Line11 the += does an automatic cast to a short. However the number 123456 can’t be contained within a short, so you end up with a negative value (-7616).
(NOTE – short 2 bytes -32,768 to 32,767), Here the number 123456 doesn’t mean the Value of int z,it shows the length of the int value
3. Those other two are red herrings however as the code will never compile due to line 8.
Any number beginning with zero is treated as an octal number (which is 0-7).
This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...