「本文已参与好文召集令活动,点击查看:后端、大前端双赛道投稿,2万元奖池等你挑战!」
难度等级: 中等
预测以下 Java 程序的输出:
问题问题一
class Gfg
{
    // constructor
    Gfg()
    {
        System.out.println("juejin");
    }
      
    static Gfg a = new Gfg(); //line 8
  
    public static void main(String args[])
    {
        Gfg b; //line 12
        b = new Gfg();
    }
}
复制代码问题二
class Gfg
{
    static int num;
    static String mystr;
  
    // constructor
    Gfg()
    {
        num = 100;
        mystr = "Constructor";
    }
  
    // First Static block
    static
    {
        System.out.println("Static Block 1");
        num = 68;
        mystr = "Block1";
    }
  
    // Second static block
    static
    {
        System.out.println("Static Block 2");
        num = 98;
        mystr = "Block2";
    }
  
    public static void main(String args[])
    {
        Gfg a = new Gfg();
        System.out.println("Value of num = " + a.num);
        System.out.println("Value of mystr = " + a.mystr);
    }
}
复制代码问题三
class superClass
{
	final public int calc(int a, int b)
	{
		return 0;
	}
}
class subClass extends superClass
{
	public int calc(int a, int b)
	{
		return 1;
	}
}
public class Gfg
{
	public static void main(String args[])
	{
		subClass get = new subClass();
		System.out.println("x = " + get.calc(0, 1));
	}
}
复制代码问题四
public class Gfg
{
	public static void main(String[] args)
	{
		Integer a = 128, b = 128;
		System.out.println(a == b);
		Integer c = 100, d = 100;
		System.out.println(c == d);
	}
}
复制代码放张可爱妹子的图缓解一下眼睛疲劳,文章后半部分是程序的输出及解析

输出及解析
问题一答案
输出:
juejin
juejin
复制代码解释:
我们知道静态变量在类加载时调用,静态变量只调用一次。现在第 13 行导致创建对象,该对象反过来调用构造函数,第二次打印“juejin”。如果第 8 行中没有使用静态变量,则该对象将被无限递归调用,从而导致 StackOverFlow 错误。请参阅此示例运行。
问题二答案
输出:
Static Block 1
Static Block 2
Value of num = 100
Value of mystr = Constructor
复制代码说明:
当类加载到内存中时,静态块被执行。一个类可以有多个静态块,它们的执行顺序与它们被写入程序的顺序相同。
注意:静态方法可以在不使用类的对象的情况下访问类变量。由于在创建新实例时调用构造函数,因此首先调用静态块,然后调用构造函数。如果我们在不使用对象的情况下运行相同的程序,则不会调用构造函数。
问题三答案
输出:
Compilation fails
复制代码解释:
superClass 类中的 calc() 方法是 final 的,因此不能被覆盖。
问题四答案
输出:
false
true
复制代码说明:
说明:在Integer对象的源代码中,我们会找到一个方法'valueOf',在这个方法中我们可以看到Integer对象的范围是从IntegerCache.low(-128)到IntegerCache.high(127)。因此,127 以上的数字不会给出预期的输出。IntegerCache的范围可以从IntegerCache类的源码中观察到。
 
 
                     
            
        













 
                    

 
                 
                    