Вывод программы на Java | Комплект 1

Опубликовано: 15 Февраля, 2022

Уровень сложности: новичок

Спрогнозируйте результат следующих программ Java.

Program 1

// filename Main.java
class Test {
    protected int x, y;
}
  
class Main {
    public static void main(String args[]) {
        Test t = new Test();
        System.out.println(t.x + " " + t.y);
    }
}

Выход

 0 0 


В Java защищенный член доступен во всех классах одного пакета и в унаследованных классах других пакетов. Поскольку Test и Main находятся в одном пакете, в указанной выше программе нет проблем, связанных с доступом. Кроме того, конструкторы по умолчанию инициализируют целые переменные как 0 в Java (подробнее см. ThisGFact). Вот почему мы получаем на выходе 0 0.



Program 2

// filename Test.java
class Test {
    public static void main(String[] args) {
        for(int i = 0; 1; i++) {
            System.out.println("Hello");
            break;
        }
    }
}

Output: Compiler Error
There is an error in condition check expression of for loop. Java differs from C++(or C) here. C++ considers all non-zero values as true and 0 as false. Unlike C++, an integer value expression cannot be placed where a boolean is expected in Java. Following is the corrected program.

// filename Test.java
class Test {
    public static void main(String[] args) {
        for(int i = 0; true; i++) {
            System.out.println("Hello");
            break;
        }
    }
}
// Output: Hello



Program 3

// filename Main.java
class Main {
    public static void main(String args[]) {   
        System.out.println(fun());
    
    int fun() {
        return 20;
    
}

Output: Compiler Error
Like C++, in Java, non-static methods cannot be called in a static method. If we make fun() static, then the program compiles fine without any compiler error. Following is the corrected program.

// filename Main.java
class Main {
    public static void main(String args[]) {
        System.out.println(fun());
    
    static int fun() {
        return 20;
    }
}
// Output: 20



Program 4

// filename Test.java
class Test {
   public static void main(String args[]) {
       System.out.println(fun());
   }
   static int fun() {
       static int x= 0;
       return ++x;
   }
}

Output: Compiler Error
Unlike C++, static local variables are not allowed in Java. See thisGFact for details. We can have class static members to count number of function calls and other purposes that C++ local static variables serve. Following is the corrected program.

class Test {
   private static int x;
   public static void main(String args[]) {
       System.out.println(fun());
   }
   static int fun() {
       return ++x;
   }
}
// Output: 1

Пожалуйста, напишите комментарии, если вы найдете какие-либо ответы / объяснения неверными или хотите поделиться дополнительной информацией по темам, обсужденным выше.

Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .