Java MCQ Question for Answer

QUESTION - 1 

 1. What does encapsulation mean in java?

a) Grouping data and methods 

b) Hiding data 

c) Inheritance 

d) Overloading 

Ans : Hiding data

Reason : encapsulation is used for hide the data from user setter function is hide function in setter function data is visible

Example :  

public class Student {

    // private data - encapsulated

    private String name;

    // public getter for name

    public String getName() {

        return name;

    }

    // public setter for name

    public void setName(String name) {

        this.name = name;

    }

}


2. Which keyword prevents method overriding? 

a) static 

b) private 

c) final 

d) super 

Answer : Final

Reason : This method is complete and should not be changed by subclasses.

Example

class Parent {

    public final void show() {

        System.out.println("This is a final method.");

    }

}


class Child extends Parent {

     public void show() {

     System.out.println("Trying to override.");

    }

}


3. What is the purpose of the 'new' keyword? 

a) Create class 

b) Create object 

c) Create variable 

d) Call method 

Answer : Create object 

Reason : The  new keyword in Java is used to create an object (instance) of a class

Example

class Car {

    void display() {

        System.out.println("This is a car.");

    }

}


public class Main {

    public static void main(String[] args) {

        // Creating an object of Car using 'new'

        Car myCar = new Car();

        myCar.display();

    }

}


4. Which of the following is used for polymorphism? 

a) Method overloading 

b) Variables 

c) final keyword 

d) Static blocks 

Answer : Method overloading

Reason

Method Overloading and Method Overriding

Both are key ways to achieve polymorphism in Java

Method Overloading allows us to define multiple methods with the same name but different parameters within a class. This difference can be in the number of parameters, the types of parameters, or the order of those parameters

Example

class MathUtils {

    // Overloaded methods

    int add(int a, int b) {

        return a + b;

    }


    double add(double a, double b) {

        return a + b;

    }

}


public class Main {

    public static void main(String[] args) {

        MathUtils m = new MathUtils();

        System.out.println(m.add(5, 10));       // Outputs: 15

        System.out.println(m.add(2.5, 3.2));     // Outputs: 5.7

    }

}


5. Which data type is used to store text? 

a) int 

b) char 

c) String 

d) Boolean 

Answer : String

Reason

In Java, the String data type is used to store a sequence of characters, which means it's the correct choice for storing text.

int stores integers (numbers).

char stores a single character.

boolean stores either true or false.

String stores a group of characters — i.e., text like names, sentences, etc.

Example

public class Main {

    public static void main(String[] args) {

        String message = "Hello, Java!";

        System.out.println(message);  // Output: Hello, Java!

    }

}


6. How do you access a static method? 

a) Using object 

b) Using class name 

c) Using variable 

d) Can't access

Answer : Using class name

Reason

In Java, a static method belongs to the class itself, not to any object instance.
That means you can (and should) access it using the class name, without creating an object.

Example

class Greeting {

    // static method

    public static void sayHello() {

        System.out.println("Hello, world!");

    }

}


public class Main {

    public static void main(String[] args) {

        // Accessing the static method using class name

        Greeting.sayHello();  // Output: Hello, world!

    }

}


7. What is the size of an int in Java? 

a) 2 bytes 

b) 4 bytes 

c) 8 bytes 

d) 1 byte 

Answer : 4 bytes


Reason : In Java, the int data type is always a 32-bit signed integer, regardless of the operating system or processor.

. 1 byte = 8 bits

. 4 bytes = 32 bits

It can store values from -2,147,483,648 to 2,147,483,647.

Example:

public class Main {

    public static void main(String[] args) {

        int number = 100;

        System.out.println("Value: " + number);  // Output: Value: 100

    }

}


8. What is the default value of a boolean variable? 

a) true 

b) false 

c) 0 

d) null 

Answer : false

Reason

In Java, if a boolean variable is declared as a class-level (instance) variable and not explicitly initialized, it is automatically assigned the default value false.

1) true is a possible value, but not the default.

2) 0 is for numeric types like int.

3) null is for object references (like String, Integer).

Example: 

public class Test {

    boolean isActive;  // not initialized


    public void showStatus() {

        System.out.println("isActive: " + isActive);

    }


    public static void main(String[] args) {

        Test t = new Test();

        t.showStatus();  // Output: isActive: false

    }

}


9. Which keyword is used to stop inheritance? 

a) static 

b) private 

c) final 

d) super 

Answer: final 

Reason: 

In Java, the final keyword is used to prevent a class from being inherited (i.e., extended).

If a class is declared as final, no other class can subclass or extend it.


Example

final class Vehicle {

    void display() {

        System.out.println("This is a vehicle.");

    }

}


// This will cause an error:

// class Car extends Vehicle {}  Not allowed

                                                or
// Main class
class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Final primitive variable
        final int i = 10;
        i = 30;
 
        // Error will be generated above
    }
}

10. How many objects are created in: Student s1 = new Student();? 

a) 1 

b) 0 

c) 2 

d) None

Answer: 1

Reason:  

In the statement Student s1 = new Student();, one object is created. The new Student() part creates a new instance of the Student class, and s1 is a reference variable that stores a reference to this newly created object. 

. The new Student() part creates one object in memory (on the heap).

. The s1 is just a reference variable that points to that object.

. So only one actual object is created

Example

class Student {

    Student() {

        System.out.println("Student object created!");

    }

}


public class Main {

    public static void main(String[] args) {

        Student s1 = new Student();  // Output: Student object created!

    }

}


QUESTION - 2

1. Which of the following is used for polymorphism? 

 a) Method overloading 

 b) Variables 

 c) final keyword 

 d) Static blocks

Answer: Method overloading

Reason :

Polymorphism is a concept in object-oriented programming that allows objects to take on many forms. One type of polymorphism is compile-time polymorphism, which is achieved using method overloading.

  • Method Overloading means defining multiple methods with the same name but different parameters within the same class.

  • It helps the program decide which method to invoke at compile time based on the method signature (number and type of parameters).


Example:

class PolymorphismExample {
    void display() {
        System.out.println("No parameters");
    }

    void display(String name) {
        System.out.println("Name: " + name);
    }

    void display(int age) {
        System.out.println("Age: " + age);
    }

    public static void main(String[] args) {
        PolymorphismExample obj = new PolymorphismExample();
        obj.display();             // Calls method with no parameters
        obj.display("Alice");      // Calls method with String parameter
        obj.display(25);           // Calls method with int parameter
    }
}
 
                                           or

class Calculator {
    // Method 1: Adds two integers
    int add(int a, int b) {
        return a + b;
    }

    // Method 2: Adds three integers
    int add(int a, int b, int c) {
        return a + b + c;
    }

    // Method 3: Adds two double numbers
    double add(double a, double b) {
        return a + b;
    }

    public static void main(String[] args) {
        Calculator calc = new Calculator();
        
        System.out.println("Sum of 2 and 3: " + calc.add(2, 3));
        System.out.println("Sum of 1, 2 and 3: " + calc.add(1, 2, 3));
        System.out.println("Sum of 2.5 and 3.5: " + calc.add(2.5, 3.5));
    }
}

2. How do you create an object in Java? 

 a) ClassName obj = new ClassName(); 

 b) new ClassName(); 

 c) ClassName(); 

 d) Object obj = ClassName();

Answer: ClassName obj = new ClassName(); 

Reason: 

In Java, to create an object

  1. Declare a reference variable of the class type.

  2. Instantiate the object using the new keyword.

  3. Assign the new object to the reference variable.


    This is the correct way to create an object in Java.
    It means:

    • ClassName – the type of object you want.

    • obj – the name of the object.

    • new – keyword to create a new object.

    • ClassName() – calls the class constructor.

Example:

class Car {
    void drive() {
        System.out.println("Driving...");
    }

    public static void main(String[] args) {
        Car myCar = new Car();  // Object creation
        myCar.drive();          // Calling method using the object
    }
}

                                      or

class Person {
    String name;
    int age;

    // Constructor with parameters
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Method to display person info
    void display() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }

    public static void main(String[] args) {
        // Creating an object with name and age
        Person obj = new Person("Alice", 25);
        obj.display();
    }
}


3.  Which keyword is used to define a constant value in Java? 
 a) static 
 b) final 
 c) const 
 d) constant

Answer: final

Reason :

In Java, the final keyword is used to define a constant — a variable whose value cannot be changed after it's assigned.

The final keyword is used to define a constant value in Java. When a variable is declared with the final keyword, its value cannot be changed after it has been initialized. This makes it a constant.

Example :

final using not changed after it's assigned

final int MAX_VALUE = 100;


4. Which keyword is used to inherit a class? 
 a) implements 
 b) extends 
 c) inherits
 d) super

Answer: extends 

Reason: In Java, the extends keyword is used when one class inherits another class.

Example:

class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Dog barks");
    }
}


5. What is inheritance in Java? 
a) Reusing fields and methods of another class 
b) Creating private variables 
c) Declaring static methods 
d) Defining interfaces 

Answer: Reusing fields and methods of another class

Reason: 

Inheritance in Java means one class gets the properties and behaviors (fields and methods) of another class. It helps in code reuse.

Example: 

// Superclass (Parent)
class Animal {
    void eat() {
        System.out.println("Animal is eating...");
    }

    void sleep() {
        System.out.println("Animal is sleeping...");
    }
}

// Subclass (Child) - Inherits from Animal
class Dog extends Animal {
    void bark() {
        System.out.println("Dog is barking!");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();

        // Inherited methods (from Animal)
        myDog.eat();    
        myDog.sleep();  

        // Child class method
        myDog.bark();   
    }
}

                           or


class Animal {
    void eat() {
        System.out.println("This animal eats food");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.eat();   // Inherited method
        d.bark();  // Dog's own method
    }
}

6. Which data type is used to store text? 
a) int 
b) Char 
c) String 
d) Boolean 

Answer: String

Reason :

In Java, the String data type is used to store text — a sequence of characters.

 Use String to store text in Java.

Example:

String name = "Alice";
System.out.println(name);


7. Which keyword is used to stop inheritance? 
a) static 
b) private 
c) final 
d) super-That     

Answer: Final

Reason:
In Java, the final keyword is used to stop inheritance.
If you make a class final, no other class can extend it.

Example:

final class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}

// This will cause an error
class Dog extends Animal {  // ❌ Error: cannot inherit from final class
    void bark() {
        System.out.println("Dog barks");
    }
}

8. What does polymorphism allow? 
a) One method with many forms 
b) One class only 
c) Data hiding
d) object creation

Answer: One method with many forms

Reason: 

Polymorphism in Java means "many forms"
It allows a method to behave differently based on input or object type.


Example: 


class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    void sound() {
        System.out.println("Dog barks");
    }
}

class Cat extends Animal {
    void sound() {
        System.out.println("Cat meows");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a;

        a = new Dog();
        a.sound();  // Dog barks

        a = new Cat();
        a.sound();  // Cat meows
    }
}

                                                        or


class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a = new Dog();  // Parent class reference, child class object
        a.sound();             // Calls Dog's version of sound()
    }
}


9. What is a setter method used for? 
a) Assign values 
b) Retrieve values 
c) Print 
d) Compile 

Answer: Assign values

Reason: 

A setter method is used to assign values to a class's private variables.

Setter → set/assign values 

Getter → get/retrieve values

Example: 

class Person {
    private String name;

    // Setter method
    public void setName(String newName) {
        name = newName;
    }

    // Getter method (just for reference)
    public String getName() {
        return name;
    }
}

public class Main {
    public static void main(String[] args) {
        Person p = new Person();
        p.setName("Alice");  // Using setter to assign value
        System.out.println(p.getName());  // Output: Alice
    }
}


10. What does method overriding mean? 
a) Redefining inherited method 
b) Duplicating method 
c) Creating error 
d) Calling constructor 

Answer: Redefining inherited method

Reason: 

Method overriding, in object-oriented programming (OOP), is a mechanism where a subclass (child class) provides its own specific implementation of a method that is already defined in its superclass (parent class).

Method overriding means a subclass provides its own version of a method that is already defined in its parent class.

Example:

class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a = new Dog();  // Creating a Dog object
        a.sound();  // Calls Dog's version of sound (method overriding)
    }
}

                                    or

class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound();  // Calls Dog's sound method
    }
}


Question - 3


1. Which of the frilowing is a valid class declaration? 

a) class my-class ( 
b) Class MyClass() 
c) class MyClass() 
d) myclass class() 

Answer: lass MyClass()

Reason: 

class Keyword:
This keyword is mandatory and indicates that you are declaring a class.


Example:


// Class Declaration 
class Student 
        class body

// Class Declaration 
class Test 
public static void main(String[] args) 
System.out.println("Class File Structure"); 
                                     or

class MyClass {
    // class body
}


2. What is the default access modifier for class members in Java? 
a) private 
b) public 
c) default 
d) protected 

Answer: default

Reason: 

When no access modifier is specified, the member has package-private (default) access, meaning it is accessible within the same package.

Example: 

// File: Animal.java
package zoo;

class Animal {
    int age = 5; // default access modifier

    void displayAge() {  // also has default access
        System.out.println("Age: " + age);
    }
}

// File: ZooTest.java
package zoo;

public class ZooTest {
    public static void main(String[] args) {
        Animal a = new Animal();
        a.displayAge();  // ✅ Works fine, same package
    }
}

                                       or

error

// File: SafariTest.java
package safari;

import zoo.Animal;

public class SafariTest {
    public static void main(String[] args) {
        Animal a = new Animal();  // ❌ Error: Animal is not public
        a.displayAge();           // ❌ Error: displayAge() not visible
    }
}




3. Which keyword is used to define a constant value? 
a) static 
b) final 
c) const 
d) constant 

Answer: final

Reason :

In Java, the final keyword is used to define a constant — a variable whose value cannot be changed after it's assigned.

The final keyword is used to define a constant value in Java. When a variable is declared with the final keyword, its value cannot be changed after it has been initialized. This makes it a constant.

Example :

final using not changed after it's assigned

final int MAX_VALUE = 100;

4. What will be the output of System.out.printin(10+"Java")? 
a) 10Java 
b) Java 10 
c) Error 
d) 10 Java 

Answer: 10java

Reason: 

The + operator combines (concatenates) the number 10 and the string "Java" into a new string.

Example:

System.out.println(10 + "Java");  // Output: 10Java

                  or

// Declare a class named ClassName
class ClassName {
    // Declare the main method (starting point)
    public static void main(String[] args) {
        // Print 10 concatenated with "Java"
        System.out.println(10 + "Java");
    }
}


5. An object in Java is created using: 
a) method 
b) constructor 
c) interface 
d) class loader 

Answer: constructor

Reason: 

A constructor is a special method used to instantiate (create) an object.

Example: 

MyClass obj = new MyClass();

                                   or

class GFG {

    // Declaring and initializing string
    // Custom input string
    String name = "GeeksForGeeks";

    // Main driver method
    public static void main(String[] args)
    {
        // As usual and most generic used we will
        // be creating object of class inside main()
        // using new keyword
        GFG obj = new GFG();

        // Print and display the object
        System.out.println(obj.name);
    }
}


6. What does the static keyword indicate? 
a) Constant value 
b) Belongs to instance
c) Belongs to class 
d) Can't be accessed 

Answer: Belongs to class

Reason: 

A static member is shared across all instances and can be accessed without creating an object

Example:

class Test
{
    // static method
    static void m1()
    {
        System.out.println("from m1");
    }

    public static void main(String[] args)
    {
          // calling m1 without creating
          // any object of class Test
           m1();
    }
}

                       or

class Test {
    static int count = 0;
}


7. Which method is used to retrieve private variables? 
a) getter 
b) fetcher 
c) scanner 
d) retriever 

Answer: getter

Reason:

The method used to retrieve private variables is called a getter.

In Java, private variables cannot be accessed directly from outside the class (this is part of the concept called encapsulation).
To safely access (read) the value of a private variable, we create a getter method.

A getter:

Is usually public.

Returns the value of the private variable.

Typically starts with the word get followed by the variable name in CamelCase.

Example:

private int age;

public int getAge() {
    return age;
}
 
                            or

class Student {
    // Private variable
    private int age;

    // Getter method to retrieve private variable
    public int getAge() {
        return age;
    }

    // Setter method (optional) to set private variable
    public void setAge(int age) {
        this.age = age;
    }
}

class MainClass {
    public static void main(String[] args) {
        Student s = new Student();
        s.setAge(20); // setting the age
        System.out.println(s.getAge()); // getting the age
    }
}



8. Java arrays are: 
a) Dynamic 
b) Objects 
c) Functions 
d) Variables 

Answer: Objects

Reason: 

In Java, arrays are treated as objects, no matter if they store primitive types (int, char, etc.) or objects (String, Integer, etc.).

This means arrays:

1. Are created on the heap memory.

2. Have a built-in .length property (not a method).

3. Can be used like any object — assigned, passed to methods, returned from methods.

Example:

Object type array (String)

public class StringArray {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Mango"};

        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

                   or

public class CheckObject {
    public static void main(String[] args) {
        int[] arr = new int[5];
        System.out.println(arr instanceof Object);  // true
    }
}


9. What is the correct way to declare an array? 
a) int arr-new int[5], 
b) array arr new array(5); 
c) int[] arr = 5; 
d) int arr = new int[]; 

Answer:  int arr = new int[5];

Reason:

The correct way to declare an array involves specifying the data type, the array name, and the size (number of elements) the array will hold. This is often done with the syntax: dataType[] arrayName = new dataType[size];.

Here's a breakdown of the process with examples:
1. Declaration (specifying the type and name):
dataType[] arrayName;
dataType: The type of data the array will hold (e.g., int, String, double, etc.).
arrayName: The name you choose for your array (e.g., myArray, numbers, names).

2. Initialization (allocating memory and potentially assigning values):

Option 1: Using the new keyword and size:
dataType[] arrayName = new dataType[size];
size: The number of elements the array will store.
Example: int[] numbers = new int[5]; (This declares an array named numbers to hold 5 integers)

Option 2: Initializing with values directly (shortcut for smaller arrays):
dataType[] arrayName = {value1, value2, ...};
Example: String[] names = {"Alice", "Bob", "Charlie"};

Example:

public class MyArray {
    public static void main(String[] args) {
        int[] arr = new int[5];
        arr[0] = 10;
        System.out.println(arr[0]);  // Output: 10
    }
}

                           or

// Declare an array to hold integers
int[] numbers;

// Create an array of size 5 (memory allocated)
numbers = new int[5];

// Initialize an array with some values
int[] scores = {85, 92, 78, 95, 89};

// Accessing an element (index starts from 0)
System.out.println(scores[0]); // Output: 85


10. Which OOP principle allows methods to behave differently based on parameters? 
a) Encapsulation 
b) Abstraction 
c) Polymorphism 
d) Inheritance

Answer: Polymorphism 

Reason:


Polymorphism means "many forms". In Java, this allows:

Method Overloading – same method name, different parameter types.

Method Overriding – same method in a subclass behaves differently.



Example:


Method Overloading – same method name, different parameter types.

class Greet {

    void sayHello() {

        System.out.println("Hello!");

    }



    void sayHello(String name) {

        System.out.println("Hello, " + name + "!");

    }

}



public class Demo {

    public static void main(String[] args) {

        Greet g = new Greet();

        g.sayHello();           // Output: Hello!

        g.sayHello("Alice");    // Output: Hello, Alice!

    }

}

                    or

Method Overriding – same method in a subclass behaves differently.


// Parent class

class Animal {

    void sound() {

        System.out.println("Animal makes a sound");

    }

}



// Child class

class Dog extends Animal {

    // Overriding the sound() method of Animal

    @Override

    void sound() {

        System.out.println("Dog barks");

    }

}



// Main class

public class TestOverride {

    public static void main(String[] args) {

        Animal myAnimal = new Animal();

        myAnimal.sound();   // Output: Animal makes a sound



        Dog myDog = new Dog();

        myDog.sound();      // Output: Dog barks



        Animal obj = new Dog(); 

        obj.sound();        // Output: Dog barks (runtime polymorphism)

    }

}



Question - 4


1. Which keyword is used to define a constant value in Java? 
a) static 
b) final  
c) const 
d) constant
 
Answer: final

Reason :

In Java, the final keyword is used to define a constant — a variable whose value cannot be changed after it's assigned.

The final keyword is used to define a constant value in Java. When a variable is declared with the final keyword, its value cannot be changed after it has been initialized. This makes it a constant.

Example :

final using not changed after it's assigned

final int MAX_VALUE = 100;

2. What does 'static' mean in Java? 
a) Belongs to object 
b) Belongs to class 
c) Constant 
d) Variable 

Answer: Belongs to class

Reason: 

When a variable or method is declared static, it belongs to the class, not to any specific object.
This means you don't need to create an object to access it.

Example:

class Example {
    static int count = 0; // static variable

    static void display() { // static method
        System.out.println("Count is: " + count);
    }
}

// Accessing without creating an object
Example.display(); 


3. How do you create an object in Java? 
a) ClassName obj = new ClassName(); 
b) new 
c) ClassName(); 
d) Object obj = ClassName(); 

nswer: ClassName obj = new ClassName(); 

Reason: 

In Java, to create an object

  1. Declare a reference variable of the class type.

  2. Instantiate the object using the new keyword.

  3. Assign the new object to the reference variable.


    This is the correct way to create an object in Java.
    It means:

    • ClassName – the type of object you want.

    • obj – the name of the object.

    • new – keyword to create a new object.

    • ClassName() – calls the class constructor.

Example:

class Car {
    void drive() {
        System.out.println("Driving...");
    }

    public static void main(String[] args) {
        Car myCar = new Car();  // Object creation
        myCar.drive();          // Calling method using the object
    }
}

                                      or

class Person {
    String name;
    int age;

    // Constructor with parameters
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Method to display person info
    void display() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }

    public static void main(String[] args) {
        // Creating an object with name and age
        Person obj = new Person("Alice", 25);
        obj.display();
    }
}


4. Which keyword is used to inherit a class? 
a) implements 
b) extends
c) inherits 
d) super 

Answer: extends

Reason: 

In Java, inheritance is done using the extends keyword

Example:

class Animal {
    void eat() { System.out.println("This animal eats food."); }
}

class Dog extends Animal {
    void bark() { System.out.println("Dog barks."); }
}


5. Which method used is to access private variables? 
a) getters 
b) public
c) accessors 
d) openers 
Answer: getters

Reason :

Private variables can't be accessed directly. We create getter methods (and sometimes setters) to read them.

Private variables in Java are designed to be accessed only within the class in which they are declared. Direct access from outside the class is not allowed, ensuring data encapsulation and security.

However, there are two primary methods to indirectly access and modify private variables:

    Getter and Setter Methods (Accessors and Mutators):

Getter methods: (also known as accessors) provide a way to retrieve the value of a private variable. They are typically public methods that return the variable's value.

Setter methods: (also known as mutators) allow you to modify the value of a private variable. They are typically public methods that take a new value as a parameter and update the variable.

Example:

class Person {
    private String name;

    public String getName() {
        return name;
    }
}


6. What is the return type of a constructor? 
a) void 
b) int 
c) none 
d) It has no return type 

Answer: It has no return type

Reason:

No Return Type: Constructors do not have any return type, not even void. The main purpose of a constructor is to initialize the object, not to return a value. Automatically Called on Object Creation: When an object of a class is created, the constructor is called automatically to initialize the object's attributes

Example:

class Car {
    Car() {  // Constructor without return type
        System.out.println("Car is created");
    }
}


7. How do you declare an integer array? 
a) int arr[] = new int[5];
b) arr int = new int[5]; 
c) int arr = int[5]; 
d) new int = arr[5]; 

Answer: int arr[] = new int[5];

Reason:

Reason:

The correct way to declare an array involves specifying the data type, the array name, and the size (number of elements) the array will hold. This is often done with the syntax: dataType[] arrayName = new dataType[size];.

Here's a breakdown of the process with examples:
1. Declaration (specifying the type and name):
dataType[] arrayName;
dataType: The type of data the array will hold (e.g., int, String, double, etc.).
arrayName: The name you choose for your array (e.g., myArray, numbers, names).

2. Initialization (allocating memory and potentially assigning values):

Option 1: Using the new keyword and size:
dataType[] arrayName = new dataType[size];
size: The number of elements the array will store.
Example: int[] numbers = new int[5]; (This declares an array named numbers to hold 5 integers)

Option 2: Initializing with values directly (shortcut for smaller arrays):
dataType[] arrayName = {value1, value2, ...};
Example: String[] names = {"Alice", "Bob", "Charlie"};

Example:

public class MyArray {
    public static void main(String[] args) {
        int[] arr = new int[5];
        arr[0] = 10;
        System.out.println(arr[0]);  // Output: 10
    }
}

                           or

// Declare an array to hold integers
int[] numbers;

// Create an array of size 5 (memory allocated)
numbers = new int[5];

// Initialize an array with some values
int[] scores = {85, 92, 78, 95, 89};

// Accessing an element (index starts from 0)
System.out.println(scores[0]); // Output: 85



8. which key word is used to inheritance? 
a) static 
b) private 
c) final 
d) super

Answer: final

Reason:

When you declare a class as final, it cannot be extended by any other class
Similarly, if you mark a method as final, it cannot be overridden by subclasses

Example:

final class Vehicle {
    void drive() {
        System.out.println("Driving...");
    }
}

// This will cause an error:
// class Car extends Vehicle { }  //  Error: Cannot inherit from final class



9. Which class is used for dynamic arrays in Java? 
a) Array 
b) List 
c) ArrayList 
d) DynamicArray 

Answer: ArrayList

Reason:

In Java, the ArrayList class is the most commonly used class for implementing dynamic arrays. It belongs to the java.util package and provides a resizable array implementation of the List interface.

Example:

import java.util.ArrayList;

public class DynamicArrayExample {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        System.out.println(numbers); // Output: [10, 20, 30]
        numbers.remove(1);
        System.out.println(numbers); // Output: [10, 30]
    }
}

10. What does the keyword 'this' refer to? 
a) Current class 
b) Parent class 
c) New object 
d) Static method 

Answer: Current class

Reason:
this refers to the current object's instance — especially used when local variables hide instance variables.
In Java, the this keyword refers to the current object within a class

Example:

class Student {
    int age;

    Student(int age) {
        this.age = age;  // this refers to the instance variable
    }
}



Question - 5

1. What is method overloading? 
a) Same method name, different parameters 
b) Same class 
c) Same variable 
d) None 

Answer: Same method name, different parameters

Reason:

Method overloading means having multiple methods with the same name but different parameter lists (different type, number, or order of parameters) within the same class.

Example:

class MathOperation {
    int add(int a, int b) {
        return a + b;
    }
    double add(double a, double b) {
        return a + b;
    }
}


2. What is the use of getter methods? 
a) Retrieve values 
b) Set values 
c) Call methods 
d) Run loops 

Answer: Retrieve values

Reason:

Getter methods are used to get or retrieve the value of private fields from a class.

Example:

class Student {
    private String name;
    
    public String getName() {
        return name;
    }
}


3. What is the name of the method that runs when object is created? 
a) init()     
b) constructor 
c) get() 
d) new() 

Answer: constructor

Reason:

In Java, the method that runs when an object is created is called a constructor

The constructor is a special method that automatically runs when an object of a class is created.

Example:

class Car {
    Car() {
        System.out.println("Car is created");
    }
}

                                                 or

public class MyClass {
    int x;

    // Constructor with no arguments
    public MyClass() {
        x = 0; // Initialize x to 0
    }

    // Constructor with one argument
    public MyClass(int value) {
        x = value; // Initialize x to the given value
    }

    public static void main(String[] args) {
        MyClass obj1 = new MyClass(); // Calls the no-argument constructor
        MyClass obj2 = new MyClass(10); // Calls the one-argument constructor

        System.out.println(obj1.x); // Output: 0
        System.out.println(obj2.x); // Output: 10
    }
}


4. What does JVM stand for? 
a) Java Virtual Method 
b) Java Variable Machine 
c) Java Virtual Machine 
d) Java Verified Machine 

Answer: Java Virtual Machine

Reason:

JVM is responsible for running Java programs by converting bytecode into machine code at runtime.

Example:

When you run java MyProgram, the JVM executes the compiled .class file


5. Which symbol is used for comments in Java? 
a) # 
b) //
c)\ 
d) !! 

Answer: //

Reason:

// is used for single-line comments in Java.

Example:

// This is a comment
System.out.println("Hello");



6. Can we overload the constructor in Java? 
a) Yes 
b) No 
c) Only once
d) Only for static class 

Answer: Yes

Reason:

Yes, constructors in Java can be overloaded. This means you can have multiple constructors within the same class, as long as they have different parameter lists.

You can have multiple constructors with different parameter lists (constructor overloading).

Example:

class Box {
    Box() { }
    Box(int length) { }
    Box(int length, int breadth) { }
}


7. What is the default value of a boolean variable? 
a) true 
b) false 
c) 0 
d) null 

Answer: false

Reason: In Java, the default value for boolean fields is fasle.

Example:

class Test {
    boolean flag;
    public static void main(String[] args) {
        Test t = new Test();
        System.out.println(t.flag); // prints false
    }
}


8. What is the output of: System.out.println(10 + "20"); 
a) 30 
b) 1020 
c) Error 
d) 10 20 

Answer: 1020

Reason:

Java reads from left to right; 10 is converted to string and concatenated with "20".

Example: System.out.println(10 + "20"); // Output: 1020

9. What is a class in Java? 
a) Blueprint 
b) Object 
c) Method 
d) Variable 

Answer: Blueprint

Reason:
A class is a blueprint or template for creating objects with predefined properties and behaviors.

Example:

class Car {
  String model;
  String color;
  int year;

  // Constructor
  Car(String model, String color, int year) {
    this.model = model;
    this.color = color;
    this.year = year;
  }

  // Method
  void displayDetails() {
    System.out.println("Model: " + model);
    System.out.println("Color: " + color);
    System.out.println("Year: " + year);
  }
}


10. How do you define a constructor? 
a) Same name as class 
b) Must be static 
c) Has return type 
d) Uses void

Answer: Same name as class

Reason:

A constructor must have the same name as the class and no return type (not even void).

A constructor in Java is a special method used to initialize objects of a class. It has the same name as the class and does not have a return type, not even void. Constructors are automatically called when an object of the class is created using the new keyword. They are primarily used to set initial values for the object's attributes. 

Example:

public class MyClass {
    private int myNumber;
    private String myString;

    public MyClass() { // This is the constructor
        myNumber = 0;
        myString = "Default";
    }
}


Question - 6

1. What is a setter method used for? 
a) Assign values 
b) Retrieve values 
c) Print 
d) Compile 

Answer: Assign values

Reason:

A setter method sets (assigns) a value to a private variable of a class

Example:

class Student {
    private int age;
    public void setAge(int age) {
        this.age = age;
    }
}


2. How to create a final class? 
a) final class ClassName() 
b) class final () 
c) static final () 
d) class ClassName final 

Answer: final class ClassName()

Reason:    A final class cannot be extended (inherited).

Example:

final class ClassName { }

              and

final class Animal {
    // code
}
class Dog extends Animal { } //  Error: Cannot inherit from final class


3. Which of these is not a Java data type? 
a) int 
b) double 
c) real 
d) boolean 

Answer: real

Reason:    Java has int, double, boolean etc., but no "real" data type.

Example:

int number = 10;
double price = 99.99;
boolean isAvailable = true;


4. What is the keyword to define a class variable? 
a) static 
b) final 
c) private 
d) constant 

Answer: static

Reason:  Static variables belong to the class, not to objects

In many programming languages like Java, the keyword "static" is used to define class variables. These variables belong to the class itself, not to any specific instance (object) of the class.

Example:

class Example {
    static int count = 0;
}

                  or

    public class MyClass {
        // Class variable (static)
        static int classVariable = 0;

        // Instance variable
        int instanceVariable = 0;

        // Method to access the class variable
        public static void incrementClassVariable() {
            classVariable++;
        }
    }

5. How to make variable accessible in all classes? 
a) public static 
b) private 
c) final 
d) object variable

Answer: public static 

Reason:     public makes it accessible anywhere, static makes it class-level.

Meaning of public static:

  • public ➔ Anyone, anywhere in the program can use it.

  • static ➔ It belongs to the class, not individual objects. No need to create an object to access it.


Example:

public class Example {
    public static int number = 10;
}

public class Example {
    public static void main(String[] args) {
        System.out.println(Example.number); // Output: 10
    }
}



6. What is the output of: System.out.println("Hello"+100);? 
a) Hello100
b) Error 
c) Hello 
d) 100Hello 

Answer: Hello100

Reason:  "Hello" is a string, and 100 will be converted to string automatically and concatenated.

Example:  

Hello100


7. Can a method return an array? 
a) Yes 
b) No 
c) Only object array 
d) Only int 

Answer: Yes

Reason:  A method can return any array type (int[], String[], etc.).

Example:

public int[] getNumbers() {
    return new int[] {1, 2, 3};
}


8. How to access array elements? 
a) Index 
b) Name 
c) Class 
d) Static 

Answer: Index

Reason:  Arrays are accessed by index starting from 0.

Example:

int[] numbers = {10, 20, 30};
System.out.println(numbers[1]); // Output: 20



9. What does method overriding mean? 
a) Redefining inherited method 
b) Duplicating method 
c) Creating error 
d) Calling constructor 

Answer: Redefining inherited method 

Reason: Child class redefines a method from the parent class with the same signature.

Example: 

class Animal {
    void sound() {
        System.out.println("Animal makes sound");
    }
}
class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}


10. Which keyword creates subclass? 
a) extends 
b) implements 
c) class 
d) super

Answer: extends

Reason:  extends keyword is used for inheritance (subclass creation)

Example:

class Animal {
    // code
}
class Dog extends Animal {
    // Dog inherits Animal
}


Question - 7

1. Can we call non-static method from static? 
a) No 
b) Yes using object 
c) Yes direct
d) Only in main 

Answer: Yes using object

Reason:
Static methods belong to the class, not to any specific object.

Non-static methods belong to objects.

So, from a static method (like main), you cannot call a non-static method directly — you need to create an object first.

Example:

class Example {
    void nonStaticMethod() {
        System.out.println("Non-static method called");
    }

    static void staticMethod() {
        Example obj = new Example();
        obj.nonStaticMethod(); // Called using object
    }

    public static void main(String[] args) {
        staticMethod();
    }
}


2. How do we declare an ArrayList of Shing? 
a) ArrayList <String> list = new ArrayList<>(); 
b) List <String> list = new ArayList<>(); 
c) Both a and b 
d) Array <String> list 

Answer:  Both a and b

Reason:

1) Both ways are valid: using ArrayList directly or via the List interface.

2} ArrayList implements List.

Example:

import java.util.ArrayList;
import java.util.List;

class Example {
    public static void main(String[] args) {
        ArrayList<String> list1 = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
    }
}
                                   or

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        // Declare and initialize an ArrayList of Strings
        ArrayList<String> names = new ArrayList<>();

        // Add elements to the ArrayList
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");

        // Print the ArrayList
        System.out.println(names);
    }
}


3. What is the advantage of method overloading ?
a) Code readability 
b) Speed 
c) Data hiding 
d) Security 

Answer: Code readability

Reason:

Method overloading means having multiple methods with the same name but different parameters.

It makes the code clean and easy to understand.

Example:

class Calculator {
    int add(int a, int b) {
        return a + b;
    }
    double add(double a, double b) {
        return a + b;
    }
}



4. How to make variable accessible in all classes? 
a) public static 
b) private 
c) final 
d) object variable 

Answer: public static

Reason:

public makes it accessible everywhere.

static
means it belongs to the class itself, not objects.

Example:

class A {
    public static int number = 100;
}

class B {
    public static void main(String[] args) {
        System.out.println(A.number); // Accessing directly
    }
}


5. How to create a final class? 
a) final class ClassName{}
b) class final {}
c) static final {}
d) class ClassName final 

Answer: final class ClassName{}

Reason:

final keyword before class prevents it from being inherited (no subclasses)

Example:

final class Animal {
    void sound() {
        System.out.println("Animal Sound");
    }
}

// class Dog extends Animal {} // ERROR: Cannot inherit from final class




7. How do you store multiple strings in jave? 
a) Array of Strings 
b) ArrayList 
c) HashMap 
d) All of these 

Answer: All of these

Reason:

You can store multiple strings using:

  • Array of Strings

  • ArrayList

  • HashMap (key-value pairs, if you need mapping)


Example:

String[] array = {"Apple", "Banana", "Cherry"};

ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Apple");
arrayList.add("Banana");

HashMap<Integer, String> map = new HashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");


8. What is a class in Java? 
a) Blueprint 
b) Object 
c) Method 
d) Variable 

Answer: Blueprint 

Reason:
 
A class is a blueprint for objects.

It defines properties and behaviors.

Example:

class Car {
    String color;
    void drive() {
        System.out.println("Car is driving");
    }
}


9. Which of the following allows multiple methods with the same name? 
a) Method Overloading 
b) Method Overriding 
c) Inheritance 
d) Encapsulation 

Answer: Method Overloading

Reason:

Overloading
= Same method name, different parameters.

Overriding
= Same method in child class.

Example:

class Printer {
    void print(String text) {
        System.out.println(text);
    }
    void print(int number) {
        System.out.println(number);
    }
}


10. How do you access a static method? 
a) Using object 
b) Using class name 
c) Using variable 
d) Can't access

Answer: Using class name

Reason:

Static methods belong to the class, not an object.

You can call it directly using the class name.

Example:

class MathUtil {
    static int add(int a, int b) {
        return a + b;
    }
}

class Test {
    public static void main(String[] args) {
        int result = MathUtil.add(5, 10); // Accessed using class name
        System.out.println(result);
    }
}


Comments

Popular posts from this blog

Group finance

Favorite