Tag: java

Questions Related to java

What will happen when you attempt to compile and run the following code


public class Hope{
    public static void main(String argv[]){
        Hope h = new Hope();
    }
    protected Hope(){
        for(int i =0;
        i <10;
        i ++){
            System.out.println(i);
        }
    }
}
  1. Compilation and running with output 0 to 9

  2. Run time error: Constructors cannot be declared protected

  3. Compilation error: Constructors cannot be declared protected

  4. Compilation and running with output 0 to 10

  5. None of the above


Correct Option: A

What is output of the above program?

Class conditional {
 public static void main(String args[]) {
  int i = 20;
  int j = 55;
  int z = 0;
  z = i < j ? i : j; // ternary operator
  System.out.println("The value assigned is " + z);
 }
}
  1. 20

  2. 55

  3. None of the above


Correct Option: A

AI Explanation

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

The given code snippet demonstrates the usage of the ternary operator to assign a value to the variable z based on a condition.

The ternary operator (condition) ? (expression1) : (expression2) works as follows:

  • If the condition is true, it evaluates to expression1.
  • If the condition is false, it evaluates to expression2.

In this case, the condition is i < j, where i is 20 and j is 55.

Since the condition i < j is true (20 is less than 55), the ternary operator will evaluate to i, which is 20.

Therefore, the value assigned to z is 20.

The output of the program will be: "The value assigned is 20"

Hence, the correct answer is option A) 20.

  1. Strings are a primitive type in Java and the StringBuffer is used as the matching wrapper type

  2. The size of a string can be retrieved using the length property.

  3. Strings are a primitive type in Java that overloads the + operator for concatenation

  4. The String class is implemented as a char array, elements are addressed using the stringname[] convention


Correct Option: C
  1. Static

  2. Private

  3. Default

  4. None of the above


Correct Option: B
  1. Compilation error

  2. Runtime error

  3. No errors

  4. Execptions


Correct Option: C
  1. A methods in object

  2. An operator and keyword

  3. Both

  4. None


Correct Option: B

What is the size of a Char?

  1. 4 bits

  2. 7 bits

  3. 8 bits

  4. 16 bits


Correct Option: D