[go: up one dir, main page]

0% found this document useful (0 votes)
5 views67 pages

JAVA

The document provides a comprehensive overview of Object Oriented Programming (OOP) concepts in Java, including principles such as encapsulation, inheritance, polymorphism, and abstraction. It also covers Java's history, key features, and the architecture of the Java Virtual Machine (JVM), along with multiple-choice questions and answers related to these topics. Key Java buzzwords like portability, security, and dynamic capabilities are also discussed, highlighting Java's design goals and functionalities.

Uploaded by

Shanmuga Priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views67 pages

JAVA

The document provides a comprehensive overview of Object Oriented Programming (OOP) concepts in Java, including principles such as encapsulation, inheritance, polymorphism, and abstraction. It also covers Java's history, key features, and the architecture of the Java Virtual Machine (JVM), along with multiple-choice questions and answers related to these topics. Key Java buzzwords like portability, security, and dynamic capabilities are also discussed, highlighting Java's design goals and functionalities.

Uploaded by

Shanmuga Priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 67

Object Oriented Concepts in Java

1. Which of the following is NOT one of the four main principles of Object Oriented Programming
(OOP)?
A) Encapsulation
B) Inheritance
C) Polymorphism
D) Compilation
Answer: D) Compilation

2. What is the main purpose of encapsulation in Java?


A) To allow data to be shared between objects
B) To hide the internal state and require all interaction to be performed through object methods
C) To allow inheritance of behavior from other classes
D) To allow polymorphism in methods
Answer: B) To hide the internal state and require all interaction to be performed through object
methods

3. Which of the following is the correct syntax for creating an object of a class in Java?
A) `ClassName objectName = new ClassName();`
B) `objectName = ClassName();`
C) `ClassName = new objectName();`
D) `new ClassName objectName;`
Answer: A) `ClassName objectName = new ClassName();`

4. Which keyword is used to refer to the current object in Java?


A) `this`
B) `self`
C) `super`
D) `object`
Answer: A) `this`

5. In Java, what is the output of the following code?


```java
class Dog {
int age;
String name;

Dog(int age, String name) {


this.age = age;
this.name = name;
}

void display() {
System.out.println(name + " is " + age + " years old.");
}
}

public class Main {


public static void main(String[] args) {
Dog dog1 = new Dog(5, "Buddy");
dog1.display();
}
}
```
A) Buddy is 5 years old.
B) Dog1 is 5 years old.
C) Compilation error.
D) Runtime error.
Answer: A) Buddy is 5 years old.

6. What is inheritance in Java?


A) The ability of a class to inherit methods and properties from another class
B) The ability of a class to hide its internal data
C) The ability of a class to create new classes
D) The ability of a class to inherit properties from a parent object
Answer: A) The ability of a class to inherit methods and properties from another class

7. What is the result of the following code?


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

class Dog extends Animal {


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

public class Test {


public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}
```
A) Animal sound
B) Bark
C) Compilation error
D) Runtime error
Answer: B) Bark

8. Which of the following is the correct definition of polymorphism?


A) The ability to inherit properties from another class
B) The ability of a method to perform different tasks based on the object calling it
C) The ability of objects to communicate with each other
D) The ability to have multiple constructors in a class
Answer: B) The ability of a method to perform different tasks based on the object calling it
9. What is the access level of a method defined as `protected` in Java?
A) Accessible only within the same package
B) Accessible from any other class
C) Accessible only by classes in the same package and subclasses
D) Accessible only within the defining class
Answer: C) Accessible only by classes in the same package and subclasses

10. What is the purpose of the `super` keyword in Java?


A) To refer to the parent class constructor
B) To call a parent class method
C) To create a superclass object
D) All of the above
Answer: D) All of the above

11. Which of the following is a feature of abstraction in Java?


A) Hiding the implementation details and showing only functionality
B) Inheriting the methods and properties of a superclass
C) Defining the properties of a class
D) Implementing an interface
Answer: A) Hiding the implementation details and showing only functionality

12. Which of the following modifiers can be applied to methods in Java?


A) `public`
B) `private`
C) `protected`
D) All of the above
Answer: D) All of the above

13. What does the `instanceof` operator in Java check?


A) If a class is an instance of another class
B) If an object is a subclass of another class
C) If an object is an instance of a specific class or subclass
D) Both B and C
Answer: D) Both B and C

14. What is the output of the following code?


```java
class A {
void display() {
System.out.println("Class A");
}
}

class B extends A {
void display() {
System.out.println("Class B");
}
}

public class Test {


public static void main(String[] args) {
A obj = new B();
obj.display();
}
}
```
A) Class A
B) Class B
C) Compilation error
D) Runtime error
Answer: B) Class B

15. In Java, what is method overloading?


A) A method with the same name but different signatures (parameters or return type)
B) A method in a subclass that overrides the method in the superclass
C) A method that is invoked multiple times
D) A method that throws an exception
Answer: A) A method with the same name but different signatures (parameters or return type)

16. In Java, which of the following is true about a constructor?


A) It is invoked when an object is created
B) It has no return type
C) It must have the same name as the class
D) All of the above
Answer: D) All of the above

17. What is an abstract class in Java?


A) A class that can have only abstract methods
B) A class that cannot be instantiated and may contain abstract methods
C) A class that can only contain concrete methods
D) A class that implements an interface
Answer: B) A class that cannot be instantiated and may contain abstract methods

18. Which of the following is true about an interface in Java?


A) It can have methods with a body
B) It can have constructors
C) It can only have abstract methods
D) It can have instance variables
Answer: C) It can only have abstract methods

19. Which of the following is the correct way to implement an interface in Java?
A) `class MyClass implements MyInterface{}`
B) `class MyClass extends MyInterface{}`
C) `interface MyClass implements MyInterface{}`
D) `interface MyClass extends MyInterface{}`
Answer: A) `class MyClass implements MyInterface{}`

20. What is the purpose of the `final` keyword in Java?


A) To define an unchangeable method
B) To prevent inheritance of a class
C) To define constants
D) All of the above
Answer: D) All of the above

21. Which of the following statements is true about constructors in Java?


A) Constructors are invoked explicitly
B) A constructor can return a value
C) A constructor can be overloaded
D) A constructor cannot be overloaded
Answer: C) A constructor can be overloaded

22. Which of the following is true about the `toString()` method in Java?
A) It is used to provide a string representation of an object
B) It must be implemented in every class
C) It returns the hashcode of the object
D) It is automatically called when printing an object
Answer: A) It is used to provide a string representation of an object

23. What will be the output of the following code?


```java
class Test {
public void display() {
System.out.println("Test");
}
}

public class Main {


public static void main(String[] args) {
Test t = null;
t.display

();
}
}
```
A) Test
B) NullPointerException
C) Compilation error
D) Runtime error
Answer: B) NullPointerException

24. In Java, which of the following is true about method overriding?


A) The method signature must be the same as the parent class method
B) The method in the child class must have a different name
C) The method in the parent class must be static
D) The return type of the method can be changed in the child class
Answer: A) The method signature must be the same as the parent class method

25. Which of the following is the correct way to handle exceptions in Java?
A) `try { ... } catch(Exception e) { ... }`
B) `try { ... } finally { ... }`
C) `catch(Exception e) { ... }`
D) `try { ... } exception { ... }`
Answer: A) `try { ... } catch(Exception e) { ... }`

History of Java & Java Buzzwords

1. Who is considered the father of the Java programming language?


A) Bjarne Stroustrup
B) Dennis Ritchie
C) James Gosling
D) Guido van Rossum
Answer: C) James Gosling

2. Java was initially developed by which company?


A) Microsoft
B) Oracle
C) Sun Microsystems
D) IBM
Answer: C) Sun Microsystems

3. What year was Java officially released?


A) 1990
B) 1995
C) 2000
D) 2005
Answer: B) 1995

4. What was Java originally called?


A) Oak
B) Coffee
C) Bytecode
D) SunScript
Answer: A) Oak

5. Which version of Java introduced the concept of "Write Once, Run Anywhere"?
A) Java 1.0
B) Java 5
C) Java 7
D) Java 8
Answer: A) Java 1.0

6. Which year did Oracle acquire Sun Microsystems?


A) 2005
B) 2009
C) 2010
D) 2013
Answer: C) 2010

7. Java was designed to be platform independent by using which of the following?


A) Virtual Machine
B) Native Compilation
C) Compiled code
D) Network
Answer: A) Virtual Machine

8. What was the original goal of Java when it was developed?


A) To develop an operating system
B) To create a platform independent programming language for consumer electronics
C) To improve the C++ programming language
D) To create web applications
Answer: B) To create a platform independent programming language for consumer electronics

9. Which feature of Java allows it to run on any platform?


A) Simplicity
B) Security
C) Portability
D) Object Oriented Nature
Answer: C) Portability

10. Which of the following is NOT a feature of Java?


A) Dynamic typing
B) Simple syntax
C) Secure and robust
D) Platform independence
Answer: A) Dynamic typing

11. Java was designed to be a(n) _____ language.


A) Interpreted
B) Compiled
C) Hybrid
D) Both A and B
Answer: D) Both A and B

12. Which Java version introduced generics?


A) Java 1.1
B) Java 5
C) Java 6
D) Java 8
Answer: B) Java 5

13. Java is platform independent because it uses a _____?


A) JVM (Java Virtual Machine)
B) JDK (Java Development Kit)
C) JRE (Java Runtime Environment)
D) Compiler
Answer: A) JVM (Java Virtual Machine)

14. Which of the following Java buzzwords means the language hides unnecessary details from the
user?
A) Simplicity
B) Object Oriented
C) Encapsulation
D) Robustness
Answer: A) Simplicity
15. What is meant by the term "Multithreaded" in Java?
A) Running multiple applications at the same time
B) Running multiple processes within the same application
C) Having a single process with many threads of execution
D) Running on multiple platforms simultaneously
Answer: C) Having a single process with many threads of execution

16. What is the meaning of the term "Robust" in Java?


A) The language has built in security features
B) It has built in memory management
C) It ensures that code will not crash under unexpected conditions
D) It has high performance
Answer: C) It ensures that code will not crash under unexpected conditions

17. Which Java buzzword emphasizes the concept of "reusability" of code?


A) Object Oriented
B) Distributed
C) Multithreaded
D) Dynamic
Answer: A) Object Oriented

18. Which Java version introduced Lambda expressions and Streams API?
A) Java 5
B) Java 6
C) Java 7
D) Java 8
Answer: D) Java 8

19. Which of the following buzzwords reflects Java's capability to interact with other languages and
platforms?
A) Distributed
B) Dynamic
C) Secure
D) Portable
Answer: B) Dynamic

20. What does the term "Secure" in Java refer to?


A) Java applications can run only on secure servers
B) Java provides features like bytecode verification and secure communication for reliable
applications
C) Java prevents any form of coding errors
D) Java applications are free from malware attacks
Answer: B) Java provides features like bytecode verification and secure communication for reliable
applications

21. What does the Java keyword `transient` do?


A) Prevents a variable from being serialized
B) Ensures a variable can be accessed only by the class it belongs to
C) Denotes a method that is part of an interface
D) Makes an object thread safe
Answer: A) Prevents a variable from being serialized

22. Which of the following buzzwords refers to Java's ability to be modified and extended easily?
A) Distributed
B) Dynamic
C) Secure
D) Portable
Answer: B) Dynamic

23. What is the significance of the "Distributed" buzzword in Java?


A) Java can be used for building desktop applications
B) Java can be used to build applications that run across multiple machines
C) Java can be used to compile code
D) Java can be used to create only network based applications
Answer: B) Java can be used to build applications that run across multiple machines

24. What does the term "Architecture Neutral" refer to in Java?


A) Java's ability to run on any hardware architecture without modification
B) Java's ability to handle multiple architectures within a system
C) Java can be run on any platform with different operating systems
D) Java uses a specific architecture for handling memory management
Answer: A) Java's ability to run on any hardware architecture without modification

25. Which Java version introduced the module system (Jigsaw)?


A) Java 6
B) Java 7
C) Java 8
D) Java 9
Answer: D) Java 9

JVM Architecture 25 MCQ Questions

1. What does JVM stand for?


A) Java Variable Management
B) Java Visual Machine
C) Java Virtual Machine
D) Java Version Manager
Answer: C) Java Virtual Machine

2. Which of the following is NOT part of the JVM architecture?


A) Class Loader Subsystem
B) Execution Engine
C) Stack Memory
D) Java Development Kit
Answer: D) Java Development Kit

3. Which of the following components is responsible for loading classes in JVM?


A) Class Loader
B) Garbage Collector
C) Execution Engine
D) Native Method Interface
Answer: A) Class Loader

4. What is the role of the Execution Engine in JVM?


A) Load classes into the memory
B) Convert bytecode to machine code
C) Handle garbage collection
D) Manage the threads in the application
Answer: B) Convert bytecode to machine code

5. Which of the following memory areas is shared by all threads in a Java application?
A) Heap
B) Stack
C) Method Area
D) Program Counter Register
Answer: A) Heap

6. What is the function of the Garbage Collector in JVM?


A) Collect and store objects in memory
B) Convert bytecode to machine code
C) Automatically reclaim unused memory
D) Load and initialize classes
Answer: C) Automatically reclaim unused memory

7. Which of the following registers holds the address of the current instruction being executed in
JVM?
A) Program Counter Register (PC)
B) Stack Pointer
C) Execution Register
D) Address Register
Answer: A) Program Counter Register (PC)

8. Where does the JVM store the bytecode of a Java program?


A) Heap
B) Stack
C) Method Area
D) Register
Answer: C) Method Area

9. Which part of the JVM is responsible for running Java bytecode?


A) Java Class Loader
B) Execution Engine
C) JVM Heap
D) Native Method Interface
Answer: B) Execution Engine

10. The JVM consists of how many memory areas?


A) 4
B) 5
C) 6
D) 7
Answer: B) 5
11. Which of the following is stored in the JVM’s Stack?
A) Object instances
B) Local variables and method calls
C) Class metadata
D) Bytecode
Answer: B) Local variables and method calls

12. Which of the following is NOT part of the Execution Engine?


A) Interpreter
B) Just In Time Compiler (JIT)
C) Garbage Collector
D) Native Interface
Answer: C) Garbage Collector

13. What happens when the JVM's Garbage Collector detects an unused object?
A) It releases the memory and removes the object from the heap
B) It moves the object to another memory area
C) It stores the object in a cache
D) It keeps the object for future use
Answer: A) It releases the memory and removes the object from the heap

14. Which of the following is true about the Method Area in JVM?
A) It stores local variables
B) It stores class metadata, method data, and static variables
C) It stores bytecode for execution
D) It stores objects created by classes
Answer: B) It stores class metadata, method data, and static variables

15. What is the purpose of the Class Loader Subsystem in JVM?


A) It loads Java source code
B) It loads Java bytecode into the JVM
C) It stores the bytecode of classes
D) It compiles Java bytecode into native machine code
Answer: B) It loads Java bytecode into the JVM

16. Which part of JVM is responsible for method invocation and return?
A) Stack
B) Heap
C) Method Area
D) Program Counter
Answer: A) Stack

17. What does JIT stand for in JVM architecture?


A) Java Interface Translation
B) Just In Time Compilation
C) Java Integrated Translator
D) Java Interactive Translation
Answer: B) Just In Time Compilation

18. Which part of the JVM performs garbage collection?


A) Stack
B) Execution Engine
C) Garbage Collector
D) Class Loader
Answer: C) Garbage Collector

19. How does the JVM execute Java programs?


A) By interpreting bytecode at runtime
B) By compiling the code into machine code before execution
C) By running the Java code on a remote server
D) By executing native machine code directly
Answer: A) By interpreting bytecode at runtime

20. What is the role of the Native Method Interface (JNI) in JVM?
A) It allows Java code to interface with native applications written in other languages
B) It compiles Java source code into bytecode
C) It manages memory for native objects
D) It handles garbage collection for native memory
Answer: A) It allows Java code to interface with native applications written in other languages

21. Where are method calls and local variables stored in JVM?
A) Heap
B) Method Area
C) Stack
D) Program Counter Register
Answer: C) Stack

22. In JVM, what is the main function of the garbage collector?


A) To collect and load classes into the JVM
B) To clear unused objects from memory and free up resources
C) To optimize code execution
D) To compile bytecode into native machine code
Answer: B) To clear unused objects from memory and free up resources

23. Which memory area is used by the JVM to store references to objects created in Java?
A) Stack
B) Heap
C) Method Area
D) Program Counter Register
Answer: B) Heap

24. What is stored in the "Program Counter Register" in JVM?


A) The address of the current method being executed
B) The current instruction being executed
C) The address of the next instruction
D) The status of the JVM process
Answer: C) The address of the next instruction

25. Which of the following is a key feature of JVM?


A) Portability
B) Compiles Java code into machine language
C) Directly executes machine code
D) It is platform dependent
Answer: A) Portability

Java Data Types

1. Which of the following is a primitive data type in Java?


A) String
B) Integer
C) int
D) Array
Answer: C) int

2. Which of the following data types can store a decimal number in Java?
A) int
B) float
C) boolean
D) char
Answer: B) float

3. What is the size of a `long` data type in Java?


A) 32 bit
B) 64 bit
C) 16 bit
D) 128 bit
Answer: B) 64 bit

4. Which of the following data types can store a true/false value in Java?
A) int
B) char
C) boolean
D) float
Answer: C) boolean

5. What is the default value of a `boolean` variable in Java?


A) 1
B) true
C) false
D) null
Answer: C) false

6. Which of the following is the correct way to declare a character variable in Java?
A) char ch = 'A';
B) char ch = "A";
C) char ch = A;
D) character ch = 'A';
Answer: A) char ch = 'A';

7. Which data type would you use to store a large decimal number in Java?
A) double
B) int
C) char
D) boolean
Answer: A) double

8. Which of the following is an example of a reference data type?


A) int
B) boolean
C) String
D) double
Answer: C) String

9. Which data type can store the largest integer value in Java?
A) int
B) long
C) double
D) byte
Answer: B) long

10. Which of the following is the default value of an `int` variable in Java?
A) 0
B) 1
C) null
D) false
Answer: A) 0

11. What is the size of the `char` data type in Java?


A) 8 bit
B) 16 bit
C) 32 bit
D) 64 bit
Answer: B) 16 bit

12. Which of the following is NOT a valid Java primitive data type?
A) int
B) boolean
C) String
D) byte
Answer: C) String

13. How much memory does the `int` data type take up in Java?
A) 2 bytes
B) 4 bytes
C) 8 bytes
D) 16 bytes
Answer: B) 4 bytes

14. What is the maximum value a `byte` variable can store in Java?
A) 128
B) 255
C) 32767
D) 2147483647
Answer: A) 128

15. Which of the following is used to define a constant value in Java?


A) final
B) constant
C) static
D) immutable
Answer: A) final

16. What is the default value of a reference type in Java?


A) null
B) 0
C) false
D) empty string
Answer: A) null

17. Which data type is used to represent a single character in Java?


A) char
B) String
C) int
D) byte
Answer: A) char

18. Which of the following is the correct declaration of a `double` variable in Java?
A) double num = 3.14;
B) double num = 3.14f;
C) double num = 3.14d;
D) double num = 3;
Answer: A) double num = 3.14;

19. Which of the following is the default value of an instance variable of type `String` in Java?
A) null
B) empty string
C) "undefined"
D) "null"
Answer: A) null

20. What will be the value of an uninitialized local `int` variable in Java?
A) 0
B) null
C) Compilation error
D) Garbage value
Answer: C) Compilation error

21. Which of the following data types can store the smallest range of values?
A) int
B) byte
C) long
D) double
Answer: B) byte
22. What is the correct way to declare a float variable with a value of 5.75 in Java?
A) float f = 5.75;
B) float f = 5.75f;
C) float f = 5.75F;
D) Both B and C
Answer: D) Both B and C

23. Which of the following is used to store large integer values in Java?
A) int
B) long
C) double
D) BigInteger
Answer: D) BigInteger

24. What is the result of the following operation: `int x = 10 / 3;` in Java?
A) 3.333
B) 3
C) 3.0
D) Compilation error
Answer: B) 3

25. Which of the following data types can be assigned a value of `true` or `false` in Java?
A) int
B) boolean
C) String
D) char
Answer: B) boolean
Here are 25 MCQ questions with answers on Variables in Java:

### Java Variables 25 MCQ Questions

1. Which of the following is a valid variable declaration in Java?


A) int 1x = 10;
B) int x = 10;
C) 10 = int x;
D) int x 10;
Answer: B) int x = 10;

2. What is the scope of a local variable in Java?


A) It can be accessed throughout the program.
B) It is accessible only within the method in which it is declared.
C) It is accessible within the class, but not methods.
D) It can be accessed from any other class in the program.
Answer: B) It is accessible only within the method in which it is declared.

3. Which of the following is a valid variable name in Java?


A) int $value = 5;
B) int 2value = 5;
C) int @value = 5;
D) int value# = 5;
Answer: A) int $value = 5;

4. What will be the output of the following code?


`int x = 5;
System.out.println(x);`
A) 0
B) 5
C) x
D) Compilation error
Answer: B) 5

5. What is the default value of an instance variable of type `int` in Java?


A) 0
B) null
C) 1
D) Garbage value
Answer: A) 0

6. What type of variable is declared within a method in Java?


A) Local variable
B) Instance variable
C) Static variable
D) Constant variable
Answer: A) Local variable

7. Which of the following variables has the highest precedence in Java?


A) Local variable
B) Instance variable
C) Class variable
D) Global variable
Answer: A) Local variable

8. What is the default value of an instance variable of type `boolean` in Java?


A) 0
B) true
C) false
D) null
Answer: C) false

9. What is the scope of a class level variable (also known as an instance variable)?
A) It can be accessed within the method only.
B) It can be accessed anywhere in the class.
C) It can be accessed in other classes.
D) It cannot be accessed at all.
Answer: B) It can be accessed anywhere in the class.

10. Which keyword is used to declare a constant variable in Java?


A) const
B) final
C) constant
D) static
Answer: B) final

11. Which of the following is NOT a valid variable type in Java?


A) int
B) float
C) string
D) double
Answer: C) string (should be `String` with a capital 'S')

12. What will be the output of the following code?


`int a = 10;
int b = a;
b = 20;
System.out.println(a);`
A) 10
B) 20
C) 0
D) Compilation error
Answer: A) 10

13. Can you declare two variables with the same name in Java?
A) Yes, if they are in different methods.
B) Yes, if they are of different data types.
C) No, variable names must be unique in a class.
D) Yes, if one is static and the other is non static.
Answer: C) No, variable names must be unique in a class.

14. Which of the following is a valid variable name in Java?


A) int 3a = 5;
B) int a# = 5;
C) int _a = 5;
D) int 5a = 5;
Answer: C) int _a = 5;

15. What is the default value of an instance variable of type `char` in Java?
A) 0
B) '\0'
C) 'a'
D) null
Answer: B) '\0' (Null character)

16. Which of the following will result in a compilation error in Java?


A) int number = 5;
B) String name = "Java";
C) float pi = 3.14;
D) int 1value = 10;
Answer: D) int 1value = 10;

17. Which type of variable is shared by all instances of a class in Java?


A) Instance variable
B) Local variable
C) Static variable
D) Final variable
Answer: C) Static variable

18. What will be the output of the following code?


`int x = 10;
x = x + 5;
System.out.println(x);`
A) 10
B) 15
C) 5
D) Compilation error
Answer: B) 15

19. What type of variable can be accessed directly from a class without creating an object in Java?
A) Instance variable
B) Static variable
C) Local variable
D) Constant variable
Answer: B) Static variable

20. What is the result of the following code snippet in Java?


`int a = 5;
int b = 5;
System.out.println(a == b);`
A) true
B) false
C) 5
D) Compilation error
Answer: A) true

21. Which type of variable is declared with the `final` keyword in Java?
A) Local variable
B) Constant variable
C) Static variable
D) Instance variable
Answer: B) Constant variable

22. What is the main purpose of the `static` keyword in Java when applied to variables?
A) To make the variable constant
B) To make the variable accessible across all methods
C) To share the variable between all instances of the class
D) To make the variable accessible in other classes
Answer: C) To share the variable between all instances of the class

23. Which of the following is NOT a valid variable type modifier in Java?
A) static
B) final
C) public
D) dynamic
Answer: D) dynamic

24. What is the default value of an instance variable of type `Object` in Java?
A) null
B) 0
C) false
D) undefined
Answer: A) null

25. What will be the output of the following code?


`int a = 10;
int b = 20;
System.out.println(a + b);`
A) 10
B) 20
C) 30
D) Compilation error
Answer: C) 30
Here are 25 MCQ questions with answers on Scope and Lifetime of Variables in Java:

### Scope and Lifetime of Variables 25 MCQ Questions

1. What is the scope of a local variable in Java?


A) It is accessible only within the method where it is declared.
B) It is accessible throughout the class.
C) It is accessible from any class.
D) It is accessible only within the constructor.
Answer: A) It is accessible only within the method where it is declared.

2. When is a local variable in Java created and destroyed?


A) Created when the class is loaded, destroyed when the method is finished.
B) Created when the method is invoked, destroyed when the method finishes execution.
C) Created when the object is created, destroyed when the class is unloaded.
D) Created when the variable is referenced, destroyed after the method returns.
Answer: B) Created when the method is invoked, destroyed when the method finishes execution.

3. What is the lifetime of an instance variable in Java?


A) The lifetime is limited to the method where it is declared.
B) The lifetime is limited to the block in which it is declared.
C) The lifetime is the same as the object it is part of.
D) Instance variables do not have a lifetime.
Answer: C) The lifetime is the same as the object it is part of.

4. What is the default value of an instance variable in Java?


A) 0 for numeric types, `false` for `boolean`, `null` for objects.
B) 0 for numeric types, `null` for all types.
C) `null` for all types.
D) Garbage value.
Answer: A) 0 for numeric types, `false` for `boolean`, `null` for objects.
5. What is the scope of a static variable in Java?
A) It is accessible only within the method it is declared in.
B) It is accessible from anywhere within the class, including static and non static methods.
C) It is accessible from anywhere in the program.
D) It is accessible only from other classes.
Answer: B) It is accessible from anywhere within the class, including static and non static
methods.

6. When does a class variable (static variable) in Java get created?


A) When the class is loaded into memory.
B) When an instance of the class is created.
C) When the variable is assigned a value.
D) When the method where the variable is declared is called.
Answer: A) When the class is loaded into memory.

7. What happens to an instance variable when the object is destroyed?


A) The instance variable is destroyed.
B) The instance variable becomes null.
C) The instance variable's value is lost.
D) The instance variable is reset to its default value.
Answer: A) The instance variable is destroyed.

8. Can a local variable in Java access instance or static variables?


A) Yes, a local variable can access any variable in the class.
B) No, a local variable cannot access any class level variables.
C) Yes, a local variable can access only instance variables.
D) Yes, a local variable can access static variables.
Answer: D) Yes, a local variable can access static variables.

9. Which variable has the longest lifetime in Java?


A) Local variables
B) Instance variables
C) Static variables
D) Constructor parameters
Answer: C) Static variables

10. What happens when a local variable goes out of scope in Java?
A) It is automatically deleted from memory.
B) Its value is reset to its default value.
C) Its value is lost, but it is not deleted until garbage collection.
D) The program will throw a runtime error.
Answer: A) It is automatically deleted from memory.

11. How can the lifetime of an object be extended in Java?


A) By passing the object as an argument to another method.
B) By assigning the object to a static variable.
C) By creating a reference to the object in another class.
D) By invoking the object's method repeatedly.
Answer: B) By assigning the object to a static variable.
12. What is the lifetime of a static variable?
A) The lifetime is limited to the method in which it is declared.
B) The lifetime is the same as the class.
C) The lifetime is the same as the object that the static variable belongs to.
D) The lifetime is limited to the block in which it is declared.
Answer: B) The lifetime is the same as the class.

13. When does an instance variable in Java get initialized?


A) When the class is loaded into memory.
B) When the object is created.
C) When the constructor is called.
D) When the method where it is declared is called.
Answer: B) When the object is created.

14. What is the scope of a variable declared within a constructor in Java?


A) The scope is the entire class.
B) The scope is limited to the constructor.
C) The scope is limited to the method.
D) The scope is the entire program.
Answer: B) The scope is limited to the constructor.

15. Which of the following can hold the longest lived value in a Java program?
A) Local variables
B) Instance variables
C) Static variables
D) Constructor parameters
Answer: C) Static variables

16. Which of the following is true about variable scope in Java?


A) A variable can only be accessed within the block in which it is declared.
B) A variable can be accessed from anywhere in the program.
C) A variable can be accessed anywhere within its method and in other methods.
D) A variable can only be accessed within the class.
Answer: A) A variable can only be accessed within the block in which it is declared.

17. How does Java handle memory for instance variables?


A) Instance variables are stored in stack memory.
B) Instance variables are stored in heap memory as part of the object.
C) Instance variables are stored in method memory.
D) Instance variables are stored in constant memory.
Answer: B) Instance variables are stored in heap memory as part of the object.

18. What is the lifetime of a static variable in Java?


A) It lasts only until the method ends.
B) It lasts as long as the class is loaded into memory.
C) It lasts until the object is destroyed.
D) It lasts until the thread ends.
Answer: B) It lasts as long as the class is loaded into memory.

19. Can a local variable be accessed outside the method where it is declared?
A) Yes, if it is assigned to an instance variable.
B) No, local variables are only accessible within the method.
C) Yes, if it is a static variable.
D) Yes, if it is returned from the method.
Answer: B) No, local variables are only accessible within the method.

20. What happens when a static variable is accessed in Java?


A) It creates a new instance of the variable.
B) It is shared across all instances of the class.
C) It gets a new value each time it is accessed.
D) It is created every time the class is loaded.
Answer: B) It is shared across all instances of the class.

21. What happens if an instance variable is not initialized in Java?


A) It gets a garbage value.
B) The program throws a compile time error.
C) It is automatically initialized to the default value.
D) It is initialized to 0.
Answer: C) It is automatically initialized to the default value.

22. Which of the following is true about the lifetime of a local variable in Java?
A) It is created when the method starts and destroyed when the method ends.
B) It is created when the class is loaded and destroyed when the class is unloaded.
C) It remains in memory as long as the program runs.
D) It is created when an object is created and destroyed when the object is destroyed.
Answer: A) It is created when the method starts and destroyed when the method ends.

23. Which keyword is used to declare a variable that cannot be reassigned in Java?
A) static
B) final
C) const
D) immutable
Answer: B) final

24. Can a static variable be modified after initialization in Java?


A) Yes, as long as it is not declared `final`.
B) No, once initialized, it

cannot be modified.
C) Yes, but only by the class constructor.
D) Yes, only if it is an instance variable.
Answer: A) Yes, as long as it is not declared `final`.

25. How can a static variable be accessed in Java?


A) It can be accessed only from instance methods.
B) It can be accessed through an instance or directly by the class name.
C) It can be accessed only from static methods.
D) It cannot be accessed directly, only through the object.
Answer: B) It can be accessed through an instance or directly by the class name.
Here are 25 MCQ questions with answers on Arrays in Java :
### Arrays in Java 25 MCQ Questions

1. Which of the following is the correct way to declare an array in Java?


A) `int arr[];`
B) `int arr[] = new int[10];`
C) `int[] arr = new int[10];`
D) All of the above
Answer: D) All of the above

2. What is the default value of an element in an integer array in Java?


A) 1
B) 0
C) null
D) NaN
Answer: B) 0

3. Which of the following is the correct way to access the first element of an array in Java?
A) `arr[1]`
B) `arr[0]`
C) `arr.first()`
D) `arr.get(1)`
Answer: B) `arr[0]`

4. What is the output of the following code?


`int[] arr = {1, 2, 3, 4};
System.out.println(arr.length);`
A) 3
B) 4
C) 5
D) Compilation error
Answer: B) 4

5. How do you declare a 2D array in Java?


A) `int arr[][];`
B) `int[] arr[];`
C) `int[][] arr;`
D) All of the above
Answer: D) All of the above

6. What is the output of the following code?


`int[] arr = {1, 2, 3, 4};
System.out.println(arr[2]);`
A) 1
B) 2
C) 3
D) 4
Answer: C) 3

7. How do you initialize an array of size 5 in Java?


A) `int arr[] = new int[5];`
B) `int arr[] = new int(5);`
C) `int arr[5];`
D) `int arr[5] = new int[];`
Answer: A) `int arr[] = new int[5];`

8. Which of the following is used to get the length of an array in Java?


A) `arr.length()`
B) `arr.size()`
C) `arr.length`
D) `arr.size()`
Answer: C) `arr.length`

9. Which of the following methods can be used to sort an array in Java?


A) `Arrays.sort(arr);`
B) `arr.sort();`
C) `Arrays.order(arr);`
D) None of the above
Answer: A) `Arrays.sort(arr);`

10. What will be the output of the following code?


`int[] arr = new int[5];
System.out.println(arr[0]);`
A) 1
B) 0
C) null
D) ArrayIndexOutOfBoundsException
Answer: B) 0

11. Which of the following is the correct way to declare and initialize an array in Java?
A) `int arr = {1, 2, 3};`
B) `int[] arr = new int[3] {1, 2, 3};`
C) `int[] arr = {1, 2, 3};`
D) `int[] arr = new int[3]; arr = {1, 2, 3};`
Answer: C) `int[] arr = {1, 2, 3};`

12. Which statement correctly accesses the last element of the array `arr` in Java?
A) `arr[arr.length];`
B) `arr[arr.length 1];`
C) `arr[arr.length + 1];`
D) `arr[arr.length 2];`
Answer: B) `arr[arr.length 1];`

13. What will be the output of the following code?


`int[] arr = {10, 20, 30, 40, 50};
System.out.println(arr[4]);`
A) 10
B) 20
C) 40
D) 50
Answer: D) 50
14. Which of the following will result in a runtime error in Java?
A) `int[] arr = new int[5]; arr[5] = 10;`
B) `int[] arr = {1, 2, 3, 4}; arr[2] = 5;`
C) `int[] arr = new int[10]; arr[9] = 20;`
D) `int[] arr = {}; arr[0] = 10;`
Answer: A) `int[] arr = new int[5]; arr[5] = 10;`

15. How do you access an element in a 2D array in Java?


A) `arr[x][y]`
B) `arr[x, y]`
C) `arr[x,y]`
D) `arr.get(x, y)`
Answer: A) `arr[x][y]`

16. What will be the output of the following code?


`int[] arr = {1, 2, 3, 4};
arr[0] = 100;
System.out.println(arr[0]);`
A) 1
B) 2
C) 3
D) 100
Answer: D) 100

17. How do you create a 3D array in Java?


A) `int[][][] arr = new int[2][3][4];`
B) `int[][][] arr = new int[3][4][5];`
C) `int[] arr = new int[3][4][5];`
D) Both A and B
Answer: D) Both A and B

18. What is the correct way to copy the contents of one array to another in Java?
A) `arr.copy(arr2);`
B) `arr = arr2;`
C) `System.arraycopy(arr, 0, arr2, 0, arr.length);`
D) `arr.copyOf(arr2);`
Answer: C) `System.arraycopy(arr, 0, arr2, 0, arr.length);`

19. Which of the following is the correct way to create a 2D array with 3 rows and 2 columns in Java?
A) `int[][] arr = new int[3][2];`
B) `int[][] arr = new int[3, 2];`
C) `int[][] arr = new int[2][3];`
D) `int[3, 2] arr = new int[][];`
Answer: A) `int[][] arr = new int[3][2];`

20. What will be the output of the following code?


`int[] arr = {1, 2, 3, 4};
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}`
A) 1 2 3 4
B) 1 2 3
C) 1 2 3 4 5
D) Compilation error
Answer: A) 1 2 3 4

21. Which of the following is true about arrays in Java?


A) Arrays in Java can only store objects.
B) Arrays in Java are fixed in size once created.
C) Arrays in Java can store primitive data types and objects.
D) Arrays in Java are resizable at runtime.
Answer: B) Arrays in Java are fixed in size once created.

22. What will be the output of the following code?


`int[] arr = {10, 20, 30};
arr[1] = 100;
System.out.println(arr[1]);`
A) 10
B) 20
C) 30
D) 100
Answer: D) 100

23. How do you declare and initialize an array of strings in Java?


A) `String[] arr = new String[3];`
B) `String[] arr = {"apple", "banana", "cherry"};`
C) `String arr[] = new String[3

];`
D) All of the above
Answer: D) All of the above

24. How can you find the index of an element in an array in Java?
A) Use `indexOf()` method.
B) Use `Arrays.indexOf()` method.
C) Use `Arrays.binarySearch()` method.
D) Use `find()` method.
Answer: C) Use `Arrays.binarySearch()` method.

25. What is the time complexity of accessing an element in an array by index?


A) O(1)
B) O(log n)
C) O(n)
D) O(n^2)
Answer: A) O(1)
Here are 25 MCQ questions with answers on Operators in Java :

### Operators in Java 25 MCQ Questions

1. Which of the following is not an arithmetic operator in Java?


A) `+`
B) ` `
C) `*`
D) `&`
Answer: D) `&`

2. Which operator is used to compare two values in Java?


A) `=`
B) `==`
C) `>`
D) `&&`
Answer: B) `==`

3. What is the result of the following expression in Java:


`5 + 3 * 2`?
A) 11
B) 16
C) 13
D) 23
Answer: A) 11

4. Which operator is used to perform logical AND in Java?


A) `&`
B) `&&`
C) `|`
D) `||`
Answer: B) `&&`

5. What does the `++` operator do in Java?


A) It increments the variable by 2.
B) It increments the variable by 1.
C) It decrements the variable by 1.
D) It performs modulo operation.
Answer: B) It increments the variable by 1.

6. What is the result of the following expression in Java:


`10 % 3`?
A) 3
B) 1
C) 0
D) 10
Answer: B) 1

7. Which of the following is the correct syntax for the ternary operator in Java?
A) `condition ? expression1 : expression2`
B) `condition ? expression2 : expression1`
C) `condition ? expression1 : (expression2)`
D) None of the above
Answer: A) `condition ? expression1 : expression2`

8. Which of the following operators is used to perform logical OR in Java?


A) `&&`
B) `||`
C) `!`
D) `^`
Answer: B) `||`

9. What does the `=` operator do in Java?


A) It checks equality.
B) It assigns a value to a variable.
C) It compares two values.
D) It performs addition.
Answer: B) It assigns a value to a variable.

10. What is the result of the following expression in Java:


`5 > 3`?
A) `true`
B) `false`
C) `5`
D) `3`
Answer: A) `true`

11. What is the result of the following expression in Java:


`5 == 5`?
A) `true`
B) `false`
C) `1`
D) `0`
Answer: A) `true`

12. Which of the following is the correct usage of the `&&` (AND) operator in Java?
A) `true && false`
B) `false && false`
C) `true && true`
D) All of the above
Answer: D) All of the above

13. What is the result of the following expression in Java:


`(2 == 2) && (3 > 1)`?
A) `false`
B) `true`
C) `0`
D) `1`
Answer: B) `true`

14. Which operator is used to check the type of a variable in Java?


A) `instanceof`
B) `is`
C) `type`
D) `typeof`
Answer: A) `instanceof`
15. What is the result of the following expression in Java:
`!true`?
A) `true`
B) `false`
C) `1`
D) `0`
Answer: B) `false`

16. What is the output of the following code?


`int x = 10;
x++;
System.out.println(x);`
A) 10
B) 11
C) 9
D) Compilation error
Answer: B) 11

17. Which operator is used to concatenate strings in Java?


A) `+`
B) `&`
C) `.concat()`
D) `|`
Answer: A) `+`

18. Which of the following is the correct result of the following expression:
`5 + 3 * 2 1`?
A) 10
B) 12
C) 9
D) 11
Answer: C) 9

19. What is the result of the following expression in Java:


`(true && false) || true`?
A) `false`
B) `true`
C) `0`
D) `1`
Answer: B) `true`

20. What is the correct syntax to perform bitwise AND in Java?


A) `&`
B) `&&`
C) `&&&`
D) `|`
Answer: A) `&`

21. What is the result of the following operation in Java:


`(5 & 3)`?
A) 7
B) 5
C) 1
D) 3
Answer: C) 1

22. What is the correct syntax for using the bitwise OR operator in Java?
A) `|`
B) `&&`
C) `^`
D) `!!`
Answer: A) `|`

23. Which operator is used for modulo division in Java?


A) `/`
B) `%`
C) `*`
D) `//`
Answer: B) `%`

24. Which of the following is an example of a relational operator in Java?


A) `>`
B) `&&`
C) `==`
D) Both A and C
Answer: D) Both A and C

25. What is the result of the expression `++x * 2` when `x = 3`?


A) 6
B) 8
C) 4
D) 2
Answer: B) 8
Here are 25 MCQ questions with answers on Control Statements in Java :

### Control Statements in Java 25 MCQ Questions

1. Which of the following is a valid control statement in Java?


A) `if`
B) `for`
C) `while`
D) All of the above
Answer: D) All of the above

2. What is the purpose of the `break` statement in Java?


A) To stop the execution of the current loop
B) To skip the current iteration of the loop
C) To exit from the current method
D) To pause the loop for a specified time
Answer: A) To stop the execution of the current loop
3. Which of the following loops in Java is guaranteed to execute at least once?
A) `for`
B) `while`
C) `do while`
D) All of the above
Answer: C) `do while`

4. What is the output of the following code?


`int i = 0;
if (i == 0) {
System.out.println("Zero");
} else {
System.out.println("Non zero");
}`
A) `Zero`
B) `Non zero`
C) `Compilation error`
D) No output
Answer: A) `Zero`

5. Which statement is used to exit a loop prematurely in Java?


A) `continue`
B) `exit`
C) `return`
D) `break`
Answer: D) `break`

6. Which of the following is the correct syntax for a `for` loop in Java?
A) `for (int i = 0; i < 10; i++)`
B) `for (i = 0, i < 10, i++)`
C) `for (int i = 0; i < 10)`
D) `for (int i = 0; i++)`
Answer: A) `for (int i = 0; i < 10; i++)`

7. Which of the following is a correct syntax for an `if` statement in Java?


A) `if condition { statement; }`
B) `if (condition) { statement; }`
C) `if condition: statement;`
D) `if (condition): statement;`
Answer: B) `if (condition) { statement; }`

8. What is the output of the following code?


`int i = 10;
if (i == 10) {
System.out.println("Ten");
} else if (i > 10) {
System.out.println("Greater than ten");
} else {
System.out.println("Less than ten");
}`
A) `Ten`
B) `Greater than ten`
C) `Less than ten`
D) Compilation error
Answer: A) `Ten`

9. What will be the output of the following code?


`int x = 5;
if (x == 5) {
System.out.println("Five");
} else if (x == 10) {
System.out.println("Ten");
} else {
System.out.println("Other");
}`
A) `Five`
B) `Ten`
C) `Other`
D) Compilation error
Answer: A) `Five`

10. Which of the following is the correct way to use the `continue` statement in Java?
A) `continue;`
B) `continue loop;`
C) `continue to next;`
D) `continue next;`
Answer: A) `continue;`

11. Which control structure in Java allows you to choose between multiple options?
A) `if`
B) `switch`
C) `while`
D) `for`
Answer: B) `switch`

12. How does a `switch` statement differ from an `if else` statement?
A) `switch` allows you to check multiple conditions without repetition.
B) `switch` can only be used with numeric data types.
C) `switch` supports logical conditions, unlike `if else`.
D) `switch` is faster than `if else` for all types of conditions.
Answer: A) `switch` allows you to check multiple conditions without repetition.

13. What is the output of the following code?


`int x = 2;
switch (x) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
default:
System.out.println("Default");
}`
A) `One`
B) `Two`
C) `Three`
D) `Default`
Answer: B) `Two`

14. What will be the output of the following code?


`int i = 0;
while (i < 3) {
System.out.println(i);
i++;
}`
A) 0 1 2
B) 1 2 3
C) 0 1 2 3
D) Compilation error
Answer: A) 0 1 2

15. What is the purpose of the `default` keyword in a `switch` statement?


A) It is used to specify the default case.
B) It exits the `switch` statement.
C) It marks the end of the `switch` block.
D) It defines a default value for a variable.
Answer: A) It is used to specify the default case.

16. Which statement in Java can be used to transfer control to the beginning of a loop?
A) `continue`
B) `break`
C) `return`
D) `exit`
Answer: A) `continue`

17. Which of the following is a valid `switch` case type in Java?


A) `char`
B) `int`
C) `String`
D) All of the above
Answer: D) All of the above

18. How many times will the following code print "Hello"?
`int i = 0;
do {
System.out.println("Hello");
i++;
} while (i < 3);`
A) 1
B) 2
C) 3
D) Infinite loop
Answer: C) 3

19. What is the result of the following code?


`int i = 10;
do {
i++;
} while (i < 10);`
A) The loop runs 0 times.
B) The loop runs 1 time.
C) The loop runs indefinitely.
D) The loop runs 10 times.
Answer: B) The loop runs 1 time.

20. Which of the following control statements does not need an expression or condition?
A) `if`
B) `for`
C) `switch`
D) `break`
Answer: D) `break`

21. What will the following code output?


`int x = 5;
if (x < 10) {
System.out.println("Less than 10");
} else if (x == 10) {
System.out.println("Equal to 10");
} else {
System.out.println("Greater than 10");
}`
A) Less than 10
B) Equal to 10
C) Greater than 10
D) Compilation error
Answer: A) Less than 10

22. What is the condition for the `while` loop to terminate in Java?
A) The condition becomes `true`.
B) The condition becomes `false`.
C) The loop will run indefinitely unless `break` is used.
D) Both A and C
Answer: B) The condition becomes `false`.

23. Which of the following statements is used to skip the current iteration of a loop in Java?
A) `exit`
B) `continue`
C) `break`
D) `return`
Answer: B) `continue`

24. Which control statement is used to handle multiple conditions in Java?


A) `if else`
B) `for`
C) `switch`
D) `while`
Answer: A) `if

else`

25. Which of the following is true about the `for` loop in Java?
A) It is used when the number of iterations is known.
B) It can only be used with numeric types.
C) It must always have a condition to terminate.
D) It can only loop through arrays.
Answer: A) It is used when the number of iterations is known.
Here are 25 MCQ questions with answers on Type Conversion and Casting in Java :

### Type Conversion and Casting in Java 25 MCQ Questions

1. What is the result of the following expression:


`int x = 10;
double y = x;`?
A) `x` is cast to `double` automatically.
B) A compilation error occurs.
C) The value of `x` is truncated to `double`.
D) None of the above
Answer: A) `x` is cast to `double` automatically.

2. What is the term for converting a larger data type to a smaller one?
A) Implicit Casting
B) Explicit Casting
C) Downcasting
D) Upcasting
Answer: C) Downcasting

3. What happens if you try to assign a `double` to an `int` variable without casting?
A) The value is automatically converted to `int`.
B) A compilation error occurs.
C) The value is rounded down.
D) The value is truncated.
Answer: B) A compilation error occurs.

4. Which type of casting is used when you convert a smaller data type to a larger data type?
A) Implicit Casting
B) Explicit Casting
C) Downcasting
D) Narrowing Conversion
Answer: A) Implicit Casting

5. What is the correct way to convert a `double` to `int` in Java?


A) `int x = (double) 10.5;`
B) `int x = (int) 10.5;`
C) `int x = double(10.5);`
D) `int x = 10.5;`
Answer: B) `int x = (int) 10.5;`

6. What is the output of the following code?


`double d = 9.7;
int x = (int) d;
System.out.println(x);`
A) 9
B) 9.7
C) 10
D) Compilation error
Answer: A) 9

7. What is the result of casting a larger numeric type to a smaller one?


A) The value is automatically converted without loss of information.
B) The value might lose precision.
C) The value is truncated.
D) A runtime exception occurs.
Answer: B) The value might lose precision.

8. Which of the following is a valid cast?


A) `double d = 10.5; int x = d;`
B) `int x = (int) 10.5;`
C) `float f = (int) 10.5;`
D) `double d = (float) 10.5;`
Answer: B) `int x = (int) 10.5;`

9. What is the output of the following code?


`float f = 10.5f;
long l = (long) f;
System.out.println(l);`
A) 10
B) 10.5
C) 11
D) Compilation error
Answer: A) 10

10. What does the term "narrowing conversion" refer to in Java?


A) Converting from a larger type to a smaller type.
B) Converting from a smaller type to a larger type.
C) Converting a boolean to an integer.
D) Converting a `char` to a `string`.
Answer: A) Converting from a larger type to a smaller type.

11. What is the correct syntax to convert a `char` to an `int` in Java?


A) `int x = (char) 65;`
B) `int x = (int) 'A';`
C) `int x = (char) 'A';`
D) `int x = 65;`
Answer: B) `int x = (int) 'A';`

12. What happens when you try to assign a larger type value to a smaller type without casting?
A) The value is automatically truncated.
B) The value is rounded.
C) A compilation error occurs.
D) The program runs but produces incorrect results.
Answer: C) A compilation error occurs.

13. What is the result of the following expression in Java?


`int i = 257;
byte b = (byte) i;`
A) 257
B) 1
C) 1
D) 0
Answer: B) 1

14. What happens when you cast a `double` to `int`?


A) The fractional part is rounded.
B) The fractional part is truncated.
C) A compilation error occurs.
D) The value is rounded to the nearest even number.
Answer: B) The fractional part is truncated.

15. Which of the following is the correct order of casting in Java from smallest to largest data types?
A) `byte > short > int > long > float > double`
B) `double > float > long > int > short > byte`
C) `short > byte > int > float > double > long`
D) `byte > long > int > double > float`
Answer: A) `byte > short > int > long > float > double`

16. What will be the result of the following code?


`int a = 200;
byte b = (byte) a;
System.out.println(b);`
A) 200
B) 0
C) 56
D) Compilation error
Answer: C) 56

17. What is the output of the following code?


`double a = 12.34;
int b = (int) a;
System.out.println(b);`
A) 12
B) 12.34
C) 13
D) Compilation error
Answer: A) 12

18. What does "implicit casting" mean in Java?


A) Manual conversion from one data type to another.
B) Automatic conversion of a smaller data type to a larger one.
C) Converting non numeric types to numeric types.
D) None of the above
Answer: B) Automatic conversion of a smaller data type to a larger one.

19. Which of the following will cause a Compilation error in Java?


A) `int x = 10; double y = x;`
B) `double x = 10.5; int y = (int) x;`
C) `byte x = 128;`
D) `char x = 'A'; int y = x;`
Answer: C) `byte x = 128;`

20. What is the result of casting the following expression:


`int x = 1000;
byte b = (byte) x;`
A) 1000
B) 56
C) 24
D) 44
Answer: C) 24

21. What will be the output of the following code?


`long l = 123456789L;
int i = (int) l;
System.out.println(i);`
A) 123456789
B) 123456789L
C) Compilation error
D) 539222987
Answer: D) 539222987

22. Which of the following is true about casting between primitive data types in Java?
A) Casting from a smaller data type to a larger one is always done implicitly.
B) You cannot cast between primitive types in Java.
C) Casting from a larger data type to a smaller one may result in data loss.
D) Both A and C are correct.
Answer: D) Both A and C are correct.

23. What happens when you cast a larger numeric type to a smaller one?
A) You lose the precision and can get unexpected results.
B) The result is rounded up to the nearest integer.
C) No change occurs.
D) A compilation error occurs.
Answer: A) You lose the precision and can get unexpected results.
24. How do you convert a `String` to an `int` in Java?
A) `int x = String.valueOf("10");`
B) `int x = (int) "10";`
C) `int x = Integer.parseInt("10");`
D) `int x = Integer.toString(

10);`
Answer: C) `int x = Integer.parseInt("10");`

25. Which of the following statements is correct about type casting in Java?
A) Implicit casting is used for narrowing conversions.
B) Explicit casting is used for widening conversions.
C) Widening conversions do not lose data.
D) Narrowing conversions are automatically handled by Java.
Answer: C) Widening conversions do not lose data.
Here are 25 MCQ questions with answers on Constructors in Java :

### Constructors in Java 25 MCQ Questions

1. What is the primary purpose of a constructor in Java?


A) To initialize objects of a class
B) To define methods in a class
C) To destroy objects of a class
D) To create a copy of an object
Answer: A) To initialize objects of a class

2. Which of the following is true about constructors in Java?


A) Constructors do not have a return type.
B) Constructors must return a value.
C) Constructors can have a return type.
D) Constructors are optional.
Answer: A) Constructors do not have a return type.

3. What is the default constructor in Java?


A) A constructor that is provided by the programmer.
B) A constructor that has no parameters.
C) A constructor that initializes all fields with default values.
D) A constructor that is automatically called when an object is created.
Answer: C) A constructor that initializes all fields with default values.

4. Can a constructor be overloaded in Java?


A) Yes, constructors can be overloaded with different parameters.
B) No, constructors cannot be overloaded.
C) Yes, but only if they have the same number of parameters.
D) Yes, but only if they have the same return type.
Answer: A) Yes, constructors can be overloaded with different parameters.

5. Which of the following is NOT a valid constructor declaration?


A) `public MyClass() {}`
B) `private MyClass() {}`
C) `MyClass() {}`
D) `public void MyClass() {}`
Answer: D) `public void MyClass() {}`

6. What is the result of the following code?


```
class MyClass {
MyClass() {
System.out.println("Constructor called");
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
}
}
```
A) Compilation error due to incorrect constructor name.
B) "Constructor called" will be printed to the console.
C) A runtime error will occur.
D) Nothing will be printed.
Answer: B) "Constructor called" will be printed to the console.

7. Which constructor type is automatically called when an object of a class is created?


A) Default constructor
B) Parameterized constructor
C) Private constructor
D) Copy constructor
Answer: A) Default constructor

8. Can a constructor have the same name as the class name?


A) Yes, the constructor must always have the same name as the class name.
B) No, constructors cannot have the same name as the class name.
C) Yes, but only in case of inheritance.
D) Yes, but only if the constructor is static.
Answer: A) Yes, the constructor must always have the same name as the class name.

9. What is the default behavior of a constructor if no constructor is defined in a class?


A) The class will not compile.
B) A default constructor is automatically provided.
C) An error occurs when the object is created.
D) The class will have no constructor at all.
Answer: B) A default constructor is automatically provided.

10. Can constructors be called explicitly in Java?


A) No, constructors are invoked automatically when an object is created.
B) Yes, constructors can be invoked using the `super()` keyword.
C) Yes, constructors can be called using the `this()` keyword.
D) Both B and C
Answer: D) Both B and C

11. Which of the following constructor is called when a subclass object is created?
A) The default constructor of the subclass
B) The parameterized constructor of the subclass
C) The constructor of the superclass is always called first.
D) The constructor of the subclass is called first.
Answer: C) The constructor of the superclass is always called first.

12. In which scenario is the `this()` constructor called in Java?


A) To call the default constructor.
B) To call another constructor in the same class.
C) To call the constructor of the superclass.
D) To invoke a parameterized constructor from the subclass.
Answer: B) To call another constructor in the same class.

13. Which constructor is invoked when an object of a class is created with parameters?
A) The default constructor
B) The parameterized constructor
C) A copy constructor
D) No constructor is invoked.
Answer: B) The parameterized constructor

14. What happens when `super()` is used in a constructor?


A) It invokes the default constructor of the current class.
B) It invokes the constructor of the superclass.
C) It creates a copy of the object.
D) It terminates the constructor execution.
Answer: B) It invokes the constructor of the superclass.

15. What will happen if a class has a constructor with parameters and no default constructor is
provided?
A) The class will not compile.
B) The default constructor is automatically provided.
C) The class will compile, but you must use the constructor with parameters.
D) The program will crash at runtime.
Answer: C) The class will compile, but you must use the constructor with parameters.

16. What is the role of the `super()` keyword in a subclass constructor?


A) It calls the default constructor of the subclass.
B) It calls the constructor of the superclass.
C) It creates a copy of the superclass object.
D) It calls the private constructor of the superclass.
Answer: B) It calls the constructor of the superclass.

17. In which situation is a constructor NOT required in a class?


A) If the class is abstract.
B) If the class has no fields.
C) If the class does not need to initialize any state.
D) All of the above.
Answer: D) All of the above.
18. Can a constructor be private in Java?
A) Yes, it can be private, and it is often used in Singleton design patterns.
B) No, constructors cannot be private.
C) Yes, but only in abstract classes.
D) Yes, but only for static classes.
Answer: A) Yes, it can be private, and it is often used in Singleton design patterns.

19. What is the result of the following code?


```
class MyClass {
MyClass() {
System.out.println("Constructor of MyClass");
}
}
class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
}
}
```
A) "Constructor of MyClass" will be printed.
B) A runtime exception occurs.
C) Compilation error occurs.
D) Nothing will be printed.
Answer: A) "Constructor of MyClass" will be printed.

20. What is the difference between a default constructor and a parameterized constructor?
A) A default constructor takes no arguments, while a parameterized constructor takes arguments.
B) A default constructor is used to initialize variables, while a parameterized constructor is not.
C) A default constructor must always be provided.
D) A parameterized constructor initializes default values, while a default constructor does not.
Answer: A) A default constructor takes no arguments, while a parameterized constructor takes
arguments.

21. What will happen if no constructor is defined in a class?


A) The class will not compile.
B) The class will automatically use the default constructor.
C) An error will occur when the object is created.
D) The program will use the parameterized constructor by default.
Answer: B) The class will automatically use the default constructor.

22. What is the significance of `this` keyword in constructors?


A) It refers to the current object of the class.
B) It is used to invoke the superclass constructor.
C) It is used to create a new object.
D) It is used to call a static method.
Answer: A) It refers to the current object of the class.

23. What happens if you explicitly invoke a constructor from a superclass in a subclass constructor?
A) The subclass constructor will be skipped.
B) The superclass constructor will be called first, followed by the subclass constructor.
C) The subclass constructor will be called first, followed by the superclass constructor.
D) It causes a compilation error.
Answer: B) The superclass constructor will be called first, followed by the subclass constructor.

24. Which of the following is NOT a valid

reason to use a constructor?


A) To assign initial values to fields.
B) To execute logic when an object is created.
C) To initialize final fields.
D) To return a value to the calling function.
Answer: D) To return a value to the calling function.

25. What is the output of the following code?


```
class Example {
Example(int x) {
System.out.println("Value: " + x);
}
}
public class Main {
public static void main(String[] args) {
Example obj = new Example(10);
}
}
```
A) Value: 10
B) Compilation error
C) No output
D) Value: null
Answer: A) Value: 10
Here are 25 MCQ questions with answers on Methods in Java :

### Methods in Java 25 MCQ Questions

1. What is the purpose of a method in Java?


A) To create objects
B) To store data
C) To define the behavior of an object
D) To handle exceptions
Answer: C) To define the behavior of an object

2. Which of the following is a valid method signature in Java?


A) `void method() {}`
B) `method void() {}`
C) `method() void {}`
D) `void: method() {}`
Answer: A) `void method() {}`
3. How do you call a method in Java?
A) By using the `new` keyword
B) By using the method name followed by parentheses
C) By using the `call` keyword
D) By using the `invoke` method
Answer: B) By using the method name followed by parentheses

4. What is the default return type of a method in Java if not specified?


A) `void`
B) `null`
C) `int`
D) `Object`
Answer: A) `void`

5. Which method declaration is correct for a method that returns an integer?


A) `int method() {}`
B) `int method[] {}`
C) `method(int) {}`
D) `method() int {}`
Answer: A) `int method() {}`

6. In Java, what is the return type of a method that does not return any value?
A) `void`
B) `null`
C) `Object`
D) `empty`
Answer: A) `void`

7. Which of the following is true about method overloading in Java?


A) Methods must have the same name but different parameter types or numbers.
B) Methods must have different return types.
C) Methods must have the same number of parameters.
D) Methods must have different names.
Answer: A) Methods must have the same name but different parameter types or numbers.

8. Which of the following is true about method overriding in Java?


A) The method in the subclass must have the same signature as the method in the superclass.
B) The return type must be different from the superclass method.
C) The method in the subclass can have any number of parameters.
D) Method overriding cannot be used with abstract methods.
Answer: A) The method in the subclass must have the same signature as the method in the
superclass.

9. What is the purpose of the `this` keyword in a method?


A) To refer to the current object
B) To refer to the superclass object
C) To invoke a method from another class
D) To access static members
Answer: A) To refer to the current object
10. What happens if a method with a non void return type does not return a value?
A) Compilation error
B) The method returns `null` by default
C) The method returns `0` by default
D) The method returns `false` by default
Answer: A) Compilation error

11. Can a method be static in Java?


A) Yes, a method can be static, meaning it belongs to the class rather than an instance.
B) No, methods cannot be static in Java.
C) Yes, but only if the method is private.
D) Yes, but only if the method has no parameters.
Answer: A) Yes, a method can be static, meaning it belongs to the class rather than an instance.

12. Which of the following can be used to call a static method in Java?
A) `object.method()`
B) `Class.method()`
C) `this.method()`
D) `super.method()`
Answer: B) `Class.method()`

13. What is method chaining in Java?


A) Calling multiple methods in a sequence, where each method returns an object that invokes another
method.
B) Calling a method inside another method.
C) A method calling itself recursively.
D) A method calling another method with the same parameters.
Answer: A) Calling multiple methods in a sequence, where each method returns an object that
invokes another method.

14. What is the keyword used to invoke the method of the parent class in Java?
A) `this`
B) `super`
C) `call`
D) `parent`
Answer: B) `super`

15. Can you call a method before an object is instantiated in Java?


A) Yes, if the method is static.
B) Yes, if the method is non static.
C) No, you need an object to call a method.
D) No, methods can only be called inside the constructor.
Answer: A) Yes, if the method is static.

16. What does the following code output?


```
class Example {
void display(int x) {
System.out.println("Value: " + x);
}
}
public class Main {
public static void main(String[] args) {
Example obj = new Example();
obj.display(5);
}
}
```
A) Compilation error
B) Value: 5
C) 5
D) Nothing will be printed
Answer: B) Value: 5

17. What is the scope of a local variable in a method?


A) The local variable is available throughout the class.
B) The local variable is only accessible within the method where it is defined.
C) The local variable is accessible throughout the entire program.
D) The local variable is available to other methods in the same class.
Answer: B) The local variable is only accessible within the method where it is defined.

18. Which type of method can be used to return a value in Java?


A) Static method
B) Non static method
C) Constructor
D) Both static and non static methods
Answer: D) Both static and non static methods

19. What will happen if a method is called with incorrect arguments in Java?
A) A compilation error will occur.
B) The program will execute, but return an unexpected value.
C) A runtime exception will occur.
D) The method will return `null`.
Answer: A) A compilation error will occur.

20. What is a recursive method?


A) A method that calls another method in a sequence.
B) A method that calls itself directly or indirectly.
C) A method that executes a loop.
D) A method that returns a default value.
Answer: B) A method that calls itself directly or indirectly.

21. Can a method in Java be overloaded with different return types?


A) Yes, methods can be overloaded based on return types.
B) No, overloading is based only on the method signature, not the return type.
C) Yes, but only for void return types.
D) Yes, but only for primitive return types.
Answer: B) No, overloading is based only on the method signature, not the return type.

22. What is the default value of a method's argument if it is not provided in Java?
A) `null`
B) The method argument is required and cannot be left empty.
C) Default values for arguments like `0` for integers.
D) The argument remains uninitialized.
Answer: B) The method argument is required and cannot be left empty.

23. How can a method in Java return multiple values?


A) By using `return` with multiple values separated by commas.
B) By using an array or a collection to return multiple values.
C) By using multiple return statements in the method.
D) Methods cannot return multiple values in Java.
Answer: B) By using an array or a collection to return multiple values.

24. What will happen if a non static method is called from a static context in Java?
A) The non static method will be executed normally.
B) Compilation error occurs.
C) A runtime error will occur.
D) The static context will be ignored.
Answer: B) Compilation error occurs.

25. Which of the following statements is true about method parameters in Java?
A) Parameters can be passed by reference only.
B) Parameters can be passed by value or reference.
C) All parameters are passed by reference.
D) Parameters are always passed by value.
Answer: D) Parameters are always passed

by value.
Here are 25 MCQ questions with answers on Static Block and Static Data in Java:

### Static Block and Static Data 25 MCQ Questions

1. What is the purpose of a static block in Java?


A) To initialize non static variables
B) To initialize static variables
C) To call constructors
D) To execute code that runs when an object is created
Answer: B) To initialize static variables

2. Where is a static block executed in Java?


A) It is executed when an object of the class is created.
B) It is executed when the class is loaded into memory.
C) It is executed when a method of the class is called.
D) It is never executed.
Answer: B) It is executed when the class is loaded into memory.

3. How many times is a static block executed in a program?


A) Once for each instance of the class
B) Twice, once for the class and once for the object
C) Once when the class is loaded into memory
D) Every time the class is used
Answer: C) Once when the class is loaded into memory

4. What happens if an exception occurs in a static block?


A) The static block is skipped
B) The class loading fails and a runtime exception is thrown
C) The exception is caught automatically
D) The program stops immediately
Answer: B) The class loading fails and a runtime exception is thrown

5. What is the correct syntax to define a static block in Java?


A) `static { // code }`
B) `static() { // code }`
C) `public static { // code }`
D) `private static { // code }`
Answer: A) `static { // code }`

6. Can a static block access non static members directly?


A) Yes, it can access all members directly.
B) No, a static block can only access static members.
C) Yes, but only if the class instance is created inside the static block.
D) Yes, but only through instance methods.
Answer: B) No, a static block can only access static members.

7. Can we have multiple static blocks in Java?


A) Yes, multiple static blocks can be defined and they are executed in the order they appear in the
code.
B) No, only one static block is allowed.
C) Yes, but they must be in different classes.
D) No, the first static block will override the others.
Answer: A) Yes, multiple static blocks can be defined and they are executed in the order they
appear in the code.

8. What is a static variable in Java?


A) A variable that belongs to the class rather than to any specific instance of the class
B) A variable that cannot be modified once initialized
C) A variable that is shared by all objects of the class
D) A variable that is declared inside a method
Answer: A) A variable that belongs to the class rather than to any specific instance of the class

9. Which of the following is true about static variables in Java?


A) Static variables are initialized every time an object is created.
B) Static variables are shared among all instances of the class.
C) Static variables cannot be changed once initialized.
D) Static variables can only be initialized in the constructor.
Answer: B) Static variables are shared among all instances of the class.

10. How do you declare a static variable in Java?


A) `int static x;`
B) `static int x;`
C) `static x = 0;`
D) `var static x = 0;`
Answer: B) `static int x;`

11. Can a static variable be initialized directly in the class definition?


A) Yes, static variables can be initialized directly in the class.
B) No, static variables must be initialized inside a method.
C) Yes, but only inside the constructor.
D) No, static variables can only be initialized using the `static` keyword.
Answer: A) Yes, static variables can be initialized directly in the class.

12. What is the main advantage of using static data members?


A) They can hold different values for each instance.
B) They reduce memory usage as they are shared across all instances.
C) They allow methods to be inherited by subclasses.
D) They are executed after the object is created.
Answer: B) They reduce memory usage as they are shared across all instances.

13. Which method can access static variables in a class?


A) Only static methods can access static variables.
B) Non static methods can access static variables directly.
C) Both static and non static methods can access static variables.
D) Static variables can only be accessed by the `main` method.
Answer: C) Both static and non static methods can access static variables.

14. What will happen if you try to access a static variable before the class is loaded into memory?
A) Compilation error
B) Runtime error
C) It will work as long as the class is loaded at some point
D) The static variable will return `null`
Answer: B) Runtime error

15. Which of the following statements is correct about static blocks and static variables in Java?
A) Static blocks are used to initialize static variables.
B) Static blocks can only access instance variables.
C) Static variables cannot be initialized in a static block.
D) Static variables are initialized when the object is created.
Answer: A) Static blocks are used to initialize static variables.

16. What happens when a class is loaded in Java?


A) The static block is executed once.
B) The constructor is executed.
C) Instance variables are initialized.
D) A new instance of the class is created.
Answer: A) The static block is executed once.

17. What is the result of accessing a static variable using an object reference?
A) It throws a `NullPointerException`.
B) The static variable is accessed as a normal instance variable.
C) The variable can still be accessed but it's not recommended.
D) Compilation error occurs.
Answer: C) The variable can still be accessed but it's not recommended.
18. What is the default value of a static variable if not initialized?
A) `0` for numbers, `false` for booleans, and `null` for objects
B) `null` for all types of static variables
C) `undefined` for all types of static variables
D) No default value; it will cause a runtime error.
Answer: A) `0` for numbers, `false` for booleans, and `null` for objects

19. Can a static block be inherited in Java?


A) Yes, a static block can be inherited by subclasses.
B) No, static blocks are not inherited.
C) Yes, but only if it’s a public static block.
D) No, but static methods are inherited.
Answer: B) No, static blocks are not inherited.

20. Which of the following is true about the order of execution of static blocks in Java?
A) Static blocks are executed in the reverse order in which they are written.
B) Static blocks are executed in the order in which they are written in the class.
C) Static blocks are executed after the main method.
D) Static blocks are never executed.
Answer: B) Static blocks are executed in the order in which they are written in the class.

21. Which of the following statements is true about static variables?


A) Static variables cannot be changed once initialized.
B) Static variables can be accessed only from static methods.
C) Static variables are shared by all instances of the class.
D) Static variables can be accessed only through object references.
Answer: C) Static variables are shared by all instances of the class.

22. What is the scope of a static variable in Java?


A) It is scoped to the entire program.
B) It is scoped only within the method where it is declared.
C) It is scoped to the class where it is declared.
D) It is scoped to the main method only.
Answer: C) It is scoped to the class where it is declared.

23. Can a static block be used to handle exceptions in Java?


A) Yes, exceptions can be handled in a static block using `try catch` blocks.
B) No, static blocks cannot handle exceptions.
C) Yes, but only in case of `ArithmeticException`.
D) Yes, but only during class loading.
Answer

: A) Yes, exceptions can be handled in a static block using `try catch` blocks.

24. What will happen if there is a return statement in a static block?


A) The static block will terminate, but the class will still be loaded.
B) The program will terminate immediately.
C) The return statement will be ignored.
D) The static block will throw an exception.
Answer: A) The static block will terminate, but the class will still be loaded.
25. What is the main difference between static and instance variables?
A) Static variables are initialized every time an object is created, instance variables are not.
B) Static variables belong to the class, while instance variables belong to the object.
C) Instance variables are shared across all instances, static variables are not.
D) Static variables are declared within methods, instance variables are declared outside methods.
Answer: B) Static variables belong to the class, while instance variables belong to the object.
Here are 25 MCQ questions on Static Methods, String, and StringBuffer Classes in Java:

### Static Methods, String, and StringBuffer Classes 25 MCQ Questions

1. What is the purpose of a static method in Java?


A) It can be called without creating an instance of the class.
B) It can only be called from an instance of the class.
C) It can only modify static variables.
D) It is only used inside constructors.
Answer: A) It can be called without creating an instance of the class.

2. Which of the following can a static method access directly?


A) Only static variables and static methods.
B) Non static variables and non static methods.
C) Instance variables of other objects.
D) None of the above.
Answer: A) Only static variables and static methods.

3. Which of the following is the correct syntax for calling a static method in Java?
A) `methodName();`
B) `Class.methodName();`
C) `this.methodName();`
D) `new Class().methodName();`
Answer: B) `Class.methodName();`

4. In which of the following cases can a static method be used?


A) When no object of the class has been created.
B) When you need to access instance variables.
C) When you want to modify instance data.
D) When you need access to both instance and static variables.
Answer: A) When no object of the class has been created.

5. Which of the following is true about the String class in Java?


A) Strings in Java are mutable.
B) The String class is final, so it cannot be subclassed.
C) String objects are passed by reference.
D) Strings are stored in a mutable buffer.
Answer: B) The String class is final, so it cannot be subclassed.

6. What is the result of calling the `length()` method on a String object in Java?
A) It returns the memory address of the string.
B) It returns the total number of characters in the string.
C) It returns the number of words in the string.
D) It returns the index of the last character.
Answer: B) It returns the total number of characters in the string.

7. Which of the following methods is used to convert a string to uppercase in Java?


A) `toUpperCase()`
B) `toUpper()`
C) `convertUpper()`
D) `upperCase()`
Answer: A) `toUpperCase()`

8. Which method is used to concatenate strings in Java?


A) `concat()`
B) `add()`
C) `merge()`
D) `combine()`
Answer: A) `concat()`

9. Which of the following is the correct way to create a String object in Java?
A) `String s = "Hello";`
B) `String s = new String("Hello");`
C) `String s = new String();`
D) All of the above.
Answer: D) All of the above.

10. What will the following code print?


```java
String str = "hello";
System.out.println(str.substring(1, 4));
```
A) `ell`
B) `hello`
C) `hel`
D) `h`
Answer: A) `ell`

11. What does the `equals()` method do in the String class?


A) Compares two strings by their memory address.
B) Compares two strings by their contents.
C) Compares the length of two strings.
D) Converts one string to another.
Answer: B) Compares two strings by their contents.

12. What will the following code print?


```java
String s1 = "Java";
String s2 = "Java";
System.out.println(s1 == s2);
```
A) `true`
B) `false`
C) Compilation error
D) `null`
Answer: A) `true`

13. Which of the following methods is used to replace characters in a string in Java?
A) `replace()`
B) `change()`
C) `swap()`
D) `substitute()`
Answer: A) `replace()`

14. What will be the result of the following code snippet?


```java
String s = "Hello";
s = s + " World";
```
A) The string `"World"` is concatenated to the string `"Hello"`.
B) A new String object is created.
C) The StringBuilder is used for concatenation.
D) All of the above.
Answer: D) All of the above.

15. Which of the following is true about the StringBuffer class?


A) StringBuffer is immutable.
B) StringBuffer objects are not thread safe.
C) StringBuffer is mutable and allows modification of the string.
D) StringBuffer is not a class in Java.
Answer: C) StringBuffer is mutable and allows modification of the string.

16. How do you initialize a StringBuffer object in Java?


A) `StringBuffer sb = "Hello";`
B) `StringBuffer sb = new StringBuffer();`
C) `StringBuffer sb = new StringBuffer("Hello");`
D) Both B and C are correct.
Answer: D) Both B and C are correct.

17. Which method is used to append data to a StringBuffer object?


A) `append()`
B) `add()`
C) `concat()`
D) `insert()`
Answer: A) `append()`

18. What will be the output of the following code?


```java
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb);
```
A) `Hello World`
B) `HelloWorld`
C) `WorldHello`
D) `null`
Answer: A) `Hello World`

19. Which method of the StringBuffer class is used to reverse the characters in a string?
A) `reverse()`
B) `flip()`
C) `invert()`
D) `reverseString()`
Answer: A) `reverse()`

20. What is the default capacity of a StringBuffer in Java?


A) 8 characters
B) 16 characters
C) 32 characters
D) 64 characters
Answer: B) 16 characters

21. What will be the output of the following code?


```java
StringBuffer sb = new StringBuffer("Java");
sb.insert(2, "X");
System.out.println(sb);
```
A) `JXava`
B) `JaXva`
C) `JavaX`
D) `JXXva`
Answer: B) `JaXva`

22. Which method is used to remove a portion of a string in StringBuffer?


A) `delete()`
B) `remove()`
C) `cut()`
D) `trim()`
Answer: A) `delete()`

23. Can you use StringBuffer to perform string concatenation in Java?


A) Yes, StringBuffer is efficient for string concatenation.
B) No, StringBuffer cannot be used for string concatenation.
C) Only for small strings.
D) Only if the string is not very long.
Answer: A) Yes, StringBuffer is efficient for string concatenation.

24. What will be the output of the following code?


```java
StringBuffer sb = new StringBuffer("Hello");
sb.delete(1, 3);
System.out.println(sb);
```
A) `Heo`
B) `Helo`
C) `Ho`
D) `Hello`
Answer: A) `Heo`

25. How can you convert a StringBuffer object to a String object in Java?
A) `sb.toString()`
B) `String.valueOf(sb)`
C) `sb.convert()`
D) Both A and B are correct.
Answer: D) Both A and B are correct.
Below are 25 MCQs for each topic you mentioned in Java:

### Inheritance: Basic Concepts, Types, Member Access Rules, etc.

1. Which of the following best defines inheritance in Java?


A) A way to create new classes based on existing ones
B) A method to access variables of another class
C) A way to override methods of a class
D) A process of class instantiation
Answer: A) A way to create new classes based on existing ones.

2. What is single inheritance in Java?


A) A class inherits from multiple classes
B) A class inherits from one class
C) A class cannot inherit from another class
D) A class inherits from abstract classes only
Answer: B) A class inherits from one class.

3. Which of the following is an example of multilevel inheritance?


A) Class B extends Class A, and Class C extends Class B
B) Class B extends Class A and Class C extends Class A
C) Class A extends Class B and Class B extends Class C
D) None of the above
Answer: A) Class B extends Class A, and Class C extends Class B.

4. What is the meaning of "method overriding" in Java?


A) A method in a subclass that has the same name and parameters as in the parent class
B) A method in the superclass with a different signature
C) A method called in the constructor
D) A method that cannot be inherited
Answer: A) A method in a subclass that has the same name and parameters as in the parent class.

5. Which keyword is used to refer to the immediate parent class object?


A) this
B) super
C) parent
D) parentClass
Answer: B) super.
6. What is the purpose of the "super" keyword in Java?
A) To refer to the superclass constructor
B) To call methods of the superclass
C) To refer to superclass variables
D) All of the above
Answer: D) All of the above.

7. What is the use of the "this" keyword in Java?


A) To refer to the current object of the class
B) To invoke another constructor in the same class
C) Both A and B
D) None of the above
Answer: C) Both A and B.

8. Which type of inheritance is not allowed in Java?


A) Multiple inheritance
B) Single inheritance
C) Multilevel inheritance
D) Hierarchical inheritance
Answer: A) Multiple inheritance.

9. What is the output of the following code?


```java
class A {
void display() {
System.out.println("A display");
}
}
class B extends A {
void display() {
System.out.println("B display");
}
}
public class Test {
public static void main(String[] args) {
A obj = new B();
obj.display();
}
}
```
A) A display
B) B display
C) Compilation error
D) Runtime exception
Answer: B) B display.

10. What is the result of calling `super()` in a subclass constructor?


A) It calls the superclass constructor.
B) It calls a method in the superclass.
C) It prevents the subclass constructor from being called.
D) It returns an object of the superclass.
Answer: A) It calls the superclass constructor.

11. Can a constructor be overridden in Java?


A) Yes
B) No
C) Yes, if it's marked `abstract`
D) Yes, if it has a different parameter list
Answer: B) No.

12. What is method overloading?


A) Changing the return type of the method
B) Defining multiple methods with the same name but different parameter lists
C) Changing the visibility of a method
D) Overriding a method from the parent class
Answer: B) Defining multiple methods with the same name but different parameter lists.

13. What is the output of the following code snippet?


```java
class Test {
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) {
Test obj = new Test();
System.out.println(obj.add(10, 20));
System.out.println(obj.add(10.5, 20.5));
}
}
```
A) Compilation error
B) 30, 31.0
C) 30, 30.5
D) 31.0, 30
Answer: B) 30, 31.0.

14. What happens if the `final` keyword is used with a method in Java?
A) The method can be overridden.
B) The method cannot be overridden.
C) The method will be abstract.
D) The method is deprecated.
Answer: B) The method cannot be overridden.

15. Which of the following is true about abstract classes in Java?


A) Abstract classes cannot have constructors.
B) Abstract classes cannot be instantiated.
C) Abstract classes must implement all methods of the superclass.
D) Abstract classes can only have static methods.
Answer: B) Abstract classes cannot be instantiated.

16. What will happen if a subclass does not implement all abstract methods of a parent class?
A) Compilation error
B) Runtime exception
C) No error will occur
D) The subclass will be abstract
Answer: A) Compilation error.

17. Which of the following is true for dynamic method dispatch in Java?
A) It refers to the method call resolution at compile time.
B) It refers to the method call resolution at runtime.
C) It works only with static methods.
D) None of the above.
Answer: B) It refers to the method call resolution at runtime.

18. In which of the following situations is the `final` keyword used in Java?
A) To define a constant variable
B) To prevent method overriding
C) To prevent inheritance
D) All of the above
Answer: D) All of the above.

19. Can an abstract class have a constructor in Java?


A) Yes, an abstract class can have a constructor.
B) No, abstract classes cannot have constructors.
C) Only if the constructor is private.
D) Only if the constructor is static.
Answer: A) Yes, an abstract class can have a constructor.

20. Which access modifier is used by default for class members in Java?
A) public
B) private
C) protected
D) package private (no modifier)
Answer: D) package private (no modifier).

21. Which of the following is true about method overriding in Java?


A) The method signature must be the same in both parent and child classes.
B) The return type must be different in the parent and child classes.
C) The child method cannot throw exceptions.
D) Method overriding is not possible in Java.
Answer: A) The method signature must be the same in both parent and child classes.

22. What is the significance of the `super()` constructor call in a subclass constructor?
A) It invokes a constructor of the immediate parent class.
B) It invokes the constructor of the grandparent class.
C) It prevents the subclass constructor from being invoked.
D) It is unnecessary in a subclass constructor.
Answer: A) It invokes a constructor of the immediate parent class.
23. What does the `instanceof` keyword do in Java?
A) It checks if an object is an instance of a class.
B) It creates an instance of a class.
C) It invokes a method from a class.
D) It checks for method overriding.
Answer: A) It checks if an object is an instance of a class.

24. Can a method be both static and abstract?


A) Yes
B) No
C) Only if it’s a final method
D) Only if the method is private
Answer: B) No.

25. Which of the following is the correct statement about inheritance in Java?
A) A child class can inherit from multiple classes.
B) A child class can inherit from only one class.
C) A class can inherit from another class and implement an interface.
D) Both B and C are correct.
Answer: D) Both B and C are correct.
Here are 25 MCQs with answers for each topic you mentioned: Multithreaded Programming and
I/O Streams in Java.

### Multithreaded Programming: Thread Class, Runnable Interface, Synchronization, Deadlock, etc.

1. Which of the following is the correct way to create a thread in Java?


A) By implementing the Runnable interface
B) By extending the Thread class
C) By both implementing the Runnable interface and extending the Thread class
D) Both A and B are correct
Answer: D) Both A and B are correct.

2. Which method is used to start a thread in Java?


A) run()
B) start()
C) thread()
D) execute()
Answer: B) start()

3. Which of the following methods are defined in the Runnable interface?


A) run()
B) start()
C) execute()
D) both A and B
Answer: A) run()

4. What is the purpose of the `Thread.sleep()` method?


A) To pause the execution of the current thread for a specified time
B) To terminate the current thread
C) To start a new thread
D) To wait for a thread to complete
Answer: A) To pause the execution of the current thread for a specified time.

5. What happens if a thread calls the `join()` method on another thread?


A) The current thread will continue executing while the other thread finishes.
B) The current thread will be paused until the other thread finishes.
C) The current thread will be destroyed.
D) Nothing happens.
Answer: B) The current thread will be paused until the other thread finishes.

6. Which of the following is true regarding thread synchronization?


A) It ensures that multiple threads do not access shared resources simultaneously.
B) It allows threads to access shared resources concurrently.
C) It prevents deadlock.
D) It ensures the threads are executed in the order they were created.
Answer: A) It ensures that multiple threads do not access shared resources simultaneously.

7. Which of the following is the correct syntax to synchronize a method in Java?


A) `synchronized void method() { }`
B) `synchronized void method() { }`
C) `synchronized public void method() { }`
D) `method synchronized() { }`
Answer: A) `synchronized void method() { }`

8. What does the `synchronized` keyword do in Java?


A) It allows multiple threads to access a method or block concurrently.
B) It ensures that only one thread at a time can execute the synchronized method or block.
C) It helps in thread creation.
D) It pauses the thread for a specified time.
Answer: B) It ensures that only one thread at a time can execute the synchronized method or block.

9. What is a deadlock in multithreaded programming?


A) When two threads share a resource
B) When two threads are blocked forever waiting for each other to release resources
C) When a thread is killed
D) When a thread does not finish its execution
Answer: B) When two threads are blocked forever waiting for each other to release resources.

10. Which of the following is the correct way to use the `synchronized` keyword on a block of code?
A) `synchronized { code }`
B) `synchronized(code) { }`
C) `synchronized(object) { code }`
D) `synchronized code { }`
Answer: C) `synchronized(object) { code }`

11. How can inter thread communication be achieved in Java?


A) Using `Thread.sleep()` method
B) Using `wait()`, `notify()`, and `notifyAll()` methods
C) Using the `start()` method
D) Using the `join()` method
Answer: B) Using `wait()`, `notify()`, and `notifyAll()` methods.

12. What is the purpose of the `wait()` method in Java?


A) To make a thread sleep for a specific amount of time
B) To block the current thread until another thread notifies it
C) To start a new thread
D) To stop a thread immediately
Answer: B) To block the current thread until another thread notifies it.

13. What is the result of using `notify()` in a multithreaded program?


A) It terminates the thread.
B) It wakes up a single thread that is waiting on the object's monitor.
C) It causes a thread to wait.
D) It creates a new thread.
Answer: B) It wakes up a single thread that is waiting on the object's monitor.

14. Which of the following classes in Java can be used to create a thread?
A) `Thread`
B) `Runnable`
C) Both A and B
D) `ExecutorService`
Answer: C) Both A and B

15. Which of the following is true about thread priorities in Java?


A) Thread priority determines the order in which threads are executed.
B) Thread priorities are not important in Java.
C) Threads are executed based on the priority of the CPU.
D) Java does not allow setting thread priorities.
Answer: A) Thread priority determines the order in which threads are executed.

16. What is the default thread priority in Java?


A) `Thread.MAX_PRIORITY`
B) `Thread.MIN_PRIORITY`
C) `Thread.NORM_PRIORITY`
D) `Thread.ANY_PRIORITY`
Answer: C) `Thread.NORM_PRIORITY`

17. What does the `Thread.yield()` method do?


A) It pauses the thread for a specified amount of time.
B) It allows the current thread to relinquish the CPU to other threads of the same priority.
C) It stops the current thread's execution.
D) It prevents thread execution.
Answer: B) It allows the current thread to relinquish the CPU to other threads of the same priority.

18. How can we prevent deadlock in Java?


A) By synchronizing only one thread at a time.
B) By using the `wait()` method in synchronized blocks.
C) By acquiring resources in the same order.
D) By increasing the thread priorities.
Answer: C) By acquiring resources in the same order.
19. What is the result of calling `Thread.interrupt()` on a thread?
A) It stops the thread immediately.
B) It causes the thread to throw an exception.
C) It interrupts the thread's execution, causing it to check for interruption.
D) It pauses the thread for a specified time.
Answer: C) It interrupts the thread's execution, causing it to check for interruption.

20. What is the difference between `sleep()` and `wait()` in Java?


A) `sleep()` is used for suspending the thread, while `wait()` is used for inter thread communication.
B) Both do the same thing.
C) `sleep()` blocks the thread forever, while `wait()` terminates the thread.
D) `sleep()` is used in event handling, while `wait()` is used for logging.
Answer: A) `sleep()` is used for suspending the thread, while `wait()` is used for inter thread
communication.

21. Which of the following methods is used to stop a thread?


A) `stop()`
B) `kill()`
C) `terminate()`
D) None of the above
Answer: D) None of the above. (Using `stop()` is deprecated)

22. Which interface does a class need to implement to create a thread in Java?
A) `Thread`
B) `Runnable`
C) `Executor`
D) `Callable`
Answer: B) `Runnable`

23. What is the thread lifecycle in Java?


A) New, Runnable, Running, Dead
B) New, Running, Waiting, Dead
C) New, Started, Finished
D) None of the above
Answer: A) New, Runnable, Running, Dead

24. Which method allows one thread to wait for another to finish in Java?
A) `join()`
B) `wait()`
C) `notify()`
D) `interrupt()`
Answer: A) `join()`

25. Which of the following is true about synchronization in Java?


A) It ensures that multiple threads can safely access shared resources.
B) It does not affect the performance of a program.
C)

It allows threads to execute in parallel without coordination.


D) It is used only in single threaded programs.
Answer: A) It ensures that multiple threads can safely access shared resources.

### I/O Streams: Concepts of Streams, File Handling, etc.

1. Which class in Java is used to read the data from a file?


A) FileReader
B) FileWriter
C) FileInputStream
D) BufferedReader
Answer: A) FileReader

2. What is the purpose of streams in Java?


A) To store data
B) To transfer data between memory and external devices
C) To compile code
D) To encrypt data
Answer: B) To transfer data between memory and external devices

3. Which of the following is the root class for all input/output streams in Java?
A) DataStream
B) IOStream
C) InputStream and OutputStream
D) FileStream
Answer: C) InputStream and OutputStream

4. Which method is used to read data from a file in Java?


A) read()
B) next()
C) readLine()
D) get()
Answer: A) read()

5. Which class is used to write data to a file in Java?


A) FileReader
B) FileWriter
C) BufferedReader
D) OutputStream
Answer: B) FileWriter

6. What is the difference between `Byte Stream` and `Character Stream`?


A) Byte streams handle raw binary data, while character streams handle data in character format.
B) Byte streams are faster than character streams.
C) Byte streams are used for text, and character streams for binary data.
D) Both streams are identical.
Answer: A) Byte streams handle raw binary data, while character streams handle data in character
format.

7. Which of the following classes is used for reading binary data?


A) FileInputStream
B) FileReader
C) ObjectInputStream
D) BufferedReader
Answer: A) FileInputStream

8. Which class is used for buffering output data for faster writing?
A) BufferedReader
B) BufferedWriter
C) PrintWriter
D) FileWriter
Answer: B) BufferedWriter

9. What does the `flush()` method do in I/O operations?


A) Clears the buffer
B) Reads data from the input stream
C) Writes data to the output stream
D) Closes the stream
Answer: A) Clears the buffer

10. Which of the following classes provides methods to read objects from a file?
A) ObjectOutputStream
B) ObjectInputStream
C) FileOutputStream
D) FileInputStream
Answer: B) ObjectInputStream

11. Which of the following is true about `PrintWriter` in Java?


A) It only works with files.
B) It can handle text and binary data.
C) It can automatically flush the buffer.
D) It is used to handle binary data.
Answer: C) It can automatically flush the buffer.

12. How does the `readLine()` method of BufferedReader work?


A) It reads the entire file content.
B) It reads the next line of text from the file.
C) It reads a single character.
D) It returns the file size.
Answer: B) It reads the next line of text from the file.

13. What is the significance of `Serializable` interface in Java I/O?


A) It allows objects to be written to and read from streams.
B) It prevents objects from being serialized.
C) It improves performance during object transfer.
D) It automatically converts objects to a file.
Answer: A) It allows objects to be written to and read from streams.

14. Which method is used to close a file stream in Java?


A) close()
B) end()
C) stop()
D) finish()
Answer: A) close()

15. What is the purpose of `FileInputStream` in Java?


A) To read data from a file byte by byte
B) To write data to a file byte by byte
C) To read characters from a file
D) To write characters to a file
Answer: A) To read data from a file byte by byte

16. Which class is used for writing binary data to a file?


A) FileReader
B) FileOutputStream
C) BufferedReader
D) PrintWriter
Answer: B) FileOutputStream

17. What does the `mark()` method do in the `Reader` class?


A) Marks a position in the stream so that it can be reset to later.
B) Starts writing to a file.
C) Marks the end of a file.
D) Reads the next byte from the stream.
Answer: A) Marks a position in the stream so that it can be reset to later.

18. Which stream is used to read and write data to a file in Java?
A) DataInputStream and DataOutputStream
B) FileInputStream and FileOutputStream
C) ObjectInputStream and ObjectOutputStream
D) BufferedReader and BufferedWriter
Answer: B) FileInputStream and FileOutputStream

19. What is the use of `FileWriter` in Java?


A) To write data to a file character by character
B) To write binary data to a file
C) To read from a file
D) To read and write objects to a file
Answer: A) To write data to a file character by character

20. What does the `File.exists()` method check?


A) If the file is being used by another program
B) If the file is empty
C) If the file exists in the system
D) If the file is locked
Answer: C) If the file exists in the system

21. Which method is used to read a single byte from a file in Java?
A) readByte()
B) readChar()
C) read()
D) nextByte()
Answer: C) read()
22. What is the purpose of `BufferedReader` in Java?
A) To write data to a file efficiently
B) To read data efficiently from a file or console
C) To read binary data from a file
D) To perform object serialization
Answer: B) To read data efficiently from a file or console

23. What is the method used to write a string to a file in Java?


A) write()
B) append()
C) print()
D) output()
Answer: A) write()

24. How do you handle exceptions while reading from a file in Java?
A) By using the `catch` block
B) By using the `throws` keyword
C) By using the `finally` block
D) All of the above
Answer: D) All of the above

25. What class is used to create file directories in Java?


A) FileReader
B) FileWriter
C) File
D) Directory
Answer: C) File

You might also like