난이도 : 중급
다음 Java 프로그램의 출력을 예측합니다.
프로그램 1:
Javaclass Gfg { // constructor Gfg() { System.out.println('Geeksforgeeks'); } static Gfg a = new Gfg(); //line 8 public static void main(String args[]) { Gfg b; //line 12 b = new Gfg(); } }
산출:
Geeksforgeeks
Geeksforgeeks
설명:
우리는 클래스가 로드될 때 정적 변수가 호출되고 정적 변수는 한 번만 호출된다는 것을 알고 있습니다. 이제 라인 13은 생성자를 호출하고 'Geeksforgeeks'가 두 번째로 인쇄되는 객체 생성 결과입니다. 8번째 줄에서 정적 변수가 사용되지 않았다면 객체는 무한히 재귀적으로 호출되어 StackOverFlow 오류가 발생했을 것입니다.
객관적인 자바
프로그램 2:
Javaclass 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); } }
산출:
Static Block 1
Static Block 2
Value of num = 100
Value of mystr = Constructor
설명:
클래스가 메모리에 로드되면 정적 블록이 실행됩니다. 클래스에는 프로그램에 작성된 것과 동일한 순서로 실행되는 여러 정적 블록이 있을 수 있습니다.
메모 : 정적 메소드는 클래스의 객체를 사용하지 않고 클래스 변수에 액세스할 수 있습니다. 생성자는 새 인스턴스가 생성될 때 호출되므로 먼저 정적 블록이 호출되고 그 후에 생성자가 호출됩니다. 객체를 사용하지 않고 동일한 프로그램을 실행했다면 생성자는 호출되지 않았을 것입니다.
프로그램 3:
Javaclass 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)); } }
산출:
Compilation fails. 설명:
superClass 클래스의 calc() 메서드는 최종 메서드이므로 재정의할 수 없습니다.
프로그램 4:
Javapublic 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); } }
산출:
false
true
설명:
Integer 객체의 소스 코드에는 Integer 객체의 범위가 IntegerCache.low(-128)에서 IntegerCache.high(127)까지인 것을 볼 수 있는 'valueOf' 메소드가 있습니다. 따라서 127보다 큰 숫자는 예상된 출력을 제공하지 않습니다. IntegerCache의 범위는 IntegerCache 클래스의 소스 코드에서 확인할 수 있습니다.
자바스크립트를 위해 잠자기