Tag: programming languages

Questions Related to programming languages

What is the output for the below code ? public class A {} public class B implements Serializable { A a = new A(); public static void main(String... args){ B b = new B(); try{ FileOutputStream fs = new FileOutputStream("b.ser"); ObjectOutputStream os = new ObjectOutputStream(fs); os.writeObject(b); os.close(); }catch(Exception e){ e.printStackTrace(); } } }

  1. Compilation Fail

  2. java.io.NotSerializableException: Because class A is not Serializable

  3. Run properly

  4. Compilation Fail : Because class A is not Serializable.


Correct Option: B
  1. Compilation clean and run but no output

  2. Compilation and run with the output "Running"

  3. Compile time error with complaint of no Thread import

  4. Compile time error with complaint of no access to Thread package


Correct Option: B

What is the output for the below code ? public class Outer { private String x = "Outer variable"; void doStuff() { String z = "local variable"; class Inner { public void seeOuter() { System.out.println("Outer x is " + x); System.out.println("Local variable z is " + z); } } } }

  1. Outer x is Outer variable.

  2. Compile Error

  3. Local variable z is local variable

  4. Outer x is Outer variable Local variable z is local variable


Correct Option: B

AI Explanation

To answer this question, let's go through the code:

public class Outer {
  private String x = "Outer variable";

  void doStuff() {
    String z = "local variable";

    class Inner {
      public void seeOuter() {
        System.out.println("Outer x is " + x);
        System.out.println("Local variable z is " + z);
      }
    }
  }
}

In this code, the class Outer contains a method doStuff() which declares a local variable z of type String.

Inside the doStuff() method, there is also a nested class Inner which has a method seeOuter().

The seeOuter() method tries to access the variables x and z from the enclosing Outer class. However, it is important to note that local variables, like z, are only accessible within the method they are declared in.

Therefore, when trying to access the local variable z from the seeOuter() method, it will result in a compile error because z is not in scope.

So, the correct answer is:

B. Compile Error

What is the output for the below code ? public class Test { public static void main(String... args) { for(int i = 2; i < 4; i++) for(int j = 2; j < 4; j++) assert i!=j : i; } }

  1. The class compiles and runs, but does not print anything.

  2. The number 2 gets printed with AssertionError

  3. The number 3 gets printed with AssertionError

  4. compile error


Correct Option: B