Difficulty level : Intermediate
Predict the output of following Java Programs.
We know that static variables are called when a class loads and static variables are called only once. Now line 13 results to creation of object which inturn calls the constructor and “Geeksforgeeks” is printed second time.
If in line 8 static variable would not have been used the object would have been called recursively infinitely leading to StackOverFlow error. See this for a sample run.
Static Block 1 Static Block 2 Value of num = 100 Value of mystr = Constructor
Static block gets executed when the class is loaded in the memory. A class can have multiple Static blocks, which are executed in the same sequence in which they have been written into the program.
Note: Static Methods can access class variables without using object of the class. Since constructor is called when a new instance is created so firstly the static blocks are called and after that the constructor is called. If we would have run the same program without using object, the constructor would not have been called.
The method calc() in class superClass is final and so cannot be overridden.
Explanation: In the source code of Integer object we will find a method ‘valueOf’ in which we can see that the range of the Integer object lies from IntegerCache.low(-128) to IntegerCache.high(127). Therefore the numbers above 127 will not give the expected output. The range of IntegerCache can be observed from the source code of the IntegerCache class. Please refer this for details.
This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
- Output of Java Program | Set 19
- Output of Java Program | Set 11
- Output of Java Program | Set 2
- Output of Java Program | Set 3
- Output of Java Program | Set 1
- Output of Java Program | Set 6
- Output of Java program | Set 26
- Output of Java Program | Set 7
- Output of Java program | Set 17
- Output of Java program | Set 27
- Output of Java Program | Set 8
- Output of Java program | Set 5
- Output of Java program | Set 28
- Output of Java Program | Set 4
- Output of Java program | Set 22 (Overloading)
Improved By : al_architjain