Q: 1 Which of the following is true about JSP?
JSP pages are interpreted at runtime.
JSP pages are compiled into servlets.
JSP is not used to make interactive web pages.
JSP pages cannot use Java code.
[ Option B ]
In JSP (Java Server Pages) technology, JSP pages are first translated into Java servlets. These servlets are then compiled and executed by the web server. This allows JSP to create dynamic and interactive web pages.
<%@ page language="java" %>
<html>
<body>
<h1>Hello, JSP Example</h1>
<%
String name = "Suresh";
out.println("Welcome, " + name);
%>
</body>
</html>
When you save this file as myfile.jsp and run it on a server like Tomcat, the server automatically converts it into a servlet like this:
public final class myfile_jsp extends HttpJspBase {
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
JspWriter out = response.getWriter();
out.write("<html><body>");
out.write("<h1>Hello, JSP!</h1>");
String name = "Suresh";
out.write("Welcome, " + name);
out.write("</body></html>");
}
}
Q: 2 Which of the following is the most important feature that makes Java suitable for Internet applications?
Faster Execution
Object oriented and Robust
Portable and Distributed
Simple and Secure
[ Option C ]
Java is widely used for Internet and web-based applications because of several important features. One of the key requirements for Internet applications is that programs must run on different platforms without modification and support networked or distributed computing.
Java fulfills these requirements through its Portability, meaning compiled Java bytecode can run on any system with a Java Virtual Machine (JVM), and its ability to work in a Distributed environment, allowing objects and programs to communicate over networks.
Q: 3 What will be the output of the following program?
public class Demo {
public static void main(String[] args) {
int[] arr = {120, 200, 016};
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " "); }
}
}
120 200 14
120 200 016
Compilation Error
120 200 16
[ Option A ]
In Java, numbers can be represented in different formats, such as decimal, octal, hexadecimal, and binary. By default, numbers written without any prefix are decimal numbers (base 10).
However, if a number starts with a 0, Java treats it as an octal number (base 8). Octal numbers use digits from 0 to 7 only.
If a number starts with 0x, Java treats it as an hexadecimal number (base 16). Hexadecimal numbers use digits from 0 to 9 and a to f.
In the given program, the array is declared as int[] arr = {120, 200, 016};. Here, 120 and 200 are standard decimal numbers. The third element, 016, starts with a 0, so Java interprets it as an octal number. To understand its decimal value, we convert octal 16 to decimal, 1×81+6×80 = 8+6 = 14. Therefore, the array actually contains the values {120, 200, 14}.
The for loop then iterates through this array and prints each element followed by a space. As a result, the output of the program is 120 200 14.
Q: 4 What do you mean by Method Overloading in Java?
Having two methods with the same name in different packages.
Having two methods with the same name and same parameters.
Having two methods with the same name but different parameters.
Having two methods with the same name in different classes.
[ Option C ]
In Java, a method is a block of code that performs a specific task. One of the core features of Java is Polymorphism, which allows objects or methods to take multiple forms.
Method overloading is a type of compile-time polymorphism where a class has two or more methods with the same name but different parameter lists.
It allows programmers to use the same method name for related actions, improving readability and organization.
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(15, 25));
System.out.println(calc.add(15, 12, 30));
System.out.println(calc.add(2.5, 7.5));
}
}
Q: 5 What does the following code do?
public class Example {
private int var;
public Example(int var) { this.var = var; }
}
Creates a new instance of the class Example.
Throws an error because 'this' cannot be used.
Assigns the parameter var to the instance variable var.
Compilation Error.
[ Option C ]
In this code, the class Example has a private instance variable named var. The constructor Example(int var) receives a parameter with the same name. Inside the constructor, the statement this.var = var; is used to distinguish between the instance variable and the constructor parameter.
Here, this.var refers to the instance variable of the current object, while var refers to the parameter. Therefore, the code simply assigns the value passed into the constructor to the object's own variable.
Q: 6 What is the main role of Java Development Kit (JDK)?
To provide only runtime environment for Java Applications
To provide a Graphical User Interface
To only compile and run Java Applications
To create, compile and execute Java Applications
[ Option D ]
The Java Development Kit (JDK) is a software development kit provided by Java to help programmers develop Java applications. It contains tools for writing, compiling, and running Java programs.
The JDK includes the Java Compiler (javac) to convert source code into bytecode, the Java Runtime Environment (JRE) to execute Java programs, and other development tools such as debuggers and documentation generators.
Q: 7 Which of the following is a commonly used Object-Oriented Programming Language?
PROLOG
C Language
JAVA
COBOL
[ Option C ]
Java is a widely used Object-Oriented Programming (OOP) language that supports core OOP principles such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation.
Q: 8 Which of the following correctly declares a method that accepts one dimensional array of double as a parameter?
public void fun(double *arr[])
public void fun(double[] arr)
public void fun(arr double[])
public void fun(double arr)
[ Option B ]
When a method needs to accept an array as a parameter, the arrays type must be specified correctly. For a one-dimensional array of double, the syntax is double[] arr, where double[] indicates an array of double values and arr is the name of the parameter.
Q: 9 Which of the following is false about Vector class in Java?
It is part of java.util package.
It is synchronized.
It can grow or shrink as needed.
It is part of java.io package.
[ Option D ]
In Java, a Vector is a class that implements a dynamic array, which means it can grow or shrink automatically as elements are added or removed.
Q: 10 What will be the value of ‘val’ displayed when JSP page is accessed for the third time since server startup?
<%! int val = 0; %>
<% val++; %>
<html><body><p>val : <% = val %></p></body></html>
1
2
3
The value of val will remain 0
[ Option C ]
In JSP (Java Server Pages), understanding how variables behave across multiple requests is essential. JSP provides different scripting elements such as declarations <%! %>, scriptlets <% %>, and expressions <%= %>, each with a specific role and scope.
Declarations <%! %>
Scriptlets <% %>
| Request Number | Initial val | Operation (val++) | Value Displayed |
|---|---|---|---|
| 1st Request | 0 | 0 to 1 | 1 |
| 2nd Request | 1 | 1 to 2 | 2 |
| 3rd Request | 2 | 2 to 3 | 3 |
Q: 11 Which of the following statement is true about public and private members in Java?
Private members can be accessed from any other class.
Private members can be accessed from subclasses.
Public members can only be accessed within the same class.
Public members can be accessed from any other class.
[ Option D ]
In Java, access modifiers determine the visibility of class members. The two commonly used modifiers are public and private.
Private members are accessible only within the same class in which they are declared, they cannot be accessed from subclasses or other classes.
Public members are accessible from any other class, regardless of the package or subclass relationship.
MEMBER ACCESS RULE TABLE:
| ACCESS MODIFIER → ACCESS LOCATION ↓ | PUBLIC | PROTECTED | DEFAULT | PRIVATE |
|---|---|---|---|---|
| Same class. | Yes | Yes | Yes | Yes |
| Subclass in same package. | Yes | Yes | Yes | No |
| Other classes in same package. | Yes | Yes | Yes | No |
| Subclass in others package. | Yes | Yes | No | No |
| Non-subclasses in others package. | Yes | No | No | No |
Q: 12 What will be the output of the following code?
public class Demo {
public static void main(String[] args) {
String str = “Hello”;
str = str+”World”;
str = str.substring(5,10);
System.out.println(str);
}
}
Hello
Hello World
ello
World
[ Option D ]
The initial string str is assigned the value "Hello". Then, str is concatenated with "World" resulting in the string "HelloWorld". Next, the substring(5, 10) method extracts characters starting at index 5 to index 9 (10 is excluded).
The string str = "HelloWorld" has indices:
| Index | str[0] | str[1] | str[2] | str[3] | str[4] | str[5] | str[6] | str[7] | str[8] | str[9] |
|---|---|---|---|---|---|---|---|---|---|---|
| Value | H | e | l | l | o | W | o | r | l | d |
So, in "HelloWorld", index 5 corresponds to the character 'W' and index 9 corresponds to 'd'. Thus, the substring "World" is extracted and printed.
Q: 13 In the statement ‘System.out.println("Hello World!")’, the keyword 'out' stands for the following—
Static member of the ‘System’ class
An interface in the Java standard library
A method in the ‘System’ class
Class in the Java standard library
[ Option A ]
In Java, System.out.println("Hello World!") is used to print messages to the console.
| COMPONENT | TYPE | DESCRIPTION |
|---|---|---|
| System | System is a class, defined in java.lang package. | Provides access to standard input, output, and error streams; part of Java core library. |
| out | public static member of System class. | The out is an instance of the PrintStream class, which provides methods like println() to display output. |
| println() | Method of PrintStream class. | Prints the given message or value to the console and moves to the next line. |
Q: 14 What will be the result of following Java code?
public class MyString {
public static void main(String[] args) {
String s1 = “Program”;
String s2 = “Program”;
System.out.println(s1==s2);
}
}
True
Compilation Error
Runtime Error
False
[ Option A ]
In Java, string literals are stored in a special memory area called the String Constant Pool (SCP). When we create two strings using literals like
Java checks the pool first. Since the literal "Program" already exists, s2 does not create a new object and both s1 and s2 point to the same memory location.
The expression s1 == s2 compares references, not string content. Because both variables refer to the same object in the pool, the result is true.
If the strings were created using new String("Program"), then == would return false because two different objects would be created.
Q: 15 Choose the incorrect statement—
If a method is declared as final, that method cannot be overridden in sub class.
The finalize() is a method of Java, which is called by garbage collector thread before removing an object from the memory.
If a class is declared final, it cannot be inherited. If you do so it will give you compile-time error.
If we declare any variable as final, the value of the variable can be modified in final method.
[ Option D ]
In Java, the final keyword is used to restrict modification and ensure immutability where needed. A method declared as final cannot be overridden in subclasses, which helps in maintaining consistent behavior.
class Parent {
final void show() {
System.out.println("This is a final method");
}
}
class Child extends Parent {
void show() {} // Compile-Time Error.
}A class declared as final cannot be inherited, which is useful for creating immutable classes or preventing extension.
final class MyClass {
int value = 100;
}
class NewClass extends MyClass { } //Compile-Time Error.If a variable is declared final, its value cannot be changed, regardless of whether it is inside a final method.
final int p = 33;
final void modifyValue() {
p = 20; //Compile-Time Error.
}The finalize() method in Java is a special method of the Object class that is called by the garbage collector before an object is removed from memory. It can be used to perform cleanup tasks, such as closing file streams, releasing network connections, or freeing other system resources held by the object.
class MyClass {
protected void finalize()throws Throwable {
System.out.println("Object is being Garbage Collected");
}
}
Q: 16 What is Encapsulation in Java?
The ability of one class to inherit the properties of another class.
The ability of an object to take many forms.
Integrating data (variables) and code (methods) into a single unit.
The ability to overload methods.
[ Option C ]
Encapsulation in Java is one of the fundamental principles of Object-Oriented Programming (OOP). An act of combining data (variables) and the methods that operate on that data into a single unit called a class.
Through encapsulation, the internal details of an object are hidden from the outside world, allowing controlled access via getter and setter methods. This helps maintain data security, ensures better control over the data, and prevents unintended modification.
| CONCEPT | DESCRIPTION | KEY FEATURES |
|---|---|---|
| Encapsulation | The OOP principle of combining data (variables) and methods (functions) into a single unit and restricting direct access to it. |
|
| Class | A blueprint or template from which objects are created. It defines properties (variables) and behaviors (methods). |
|
| Object | An instance of a class that has its own identity, state, and behavior. It occupies memory. |
|
Q: 17 If A is a superclass and B is a subclass of it and C is subclass of B, in what order the constructors that make up the classes be called?
A, C, B
A, B, C
C, A, B
C, B, A
[ Option B ]
In Java, constructors are special methods used to initialize objects when they are created. When dealing with inheritance, constructors follow a specific order to ensure that the parent class is properly initialized before the child class.
If a class A is a superclass, B is a subclass of A, and C is a subclass of B, then creating an object of class C triggers constructor calls in a Top-Down order, starting from the highest superclass down to the actual subclass.
This happens because the subclass constructor implicitly calls the constructor of its parent class using the super().
class A {
A() {
System.out.println("Constructor of Class A.");
}
}
class B extends A {
B() {
System.out.println("Constructor of Class B.");
}
}
class C extends B {
C() {
System.out.println("Constructor of Class C.");
}
}
public class Main {
public static void main(String args[]) {
C obj = new C();
}
}
OUTPUT
Constructor of Class A.
Constructor of Class B.
Constructor of Class C.
Q: 18 What is Polymorphism in Java?
The ability of a single method to perform different tasks.
The ability of different methods to perform different tasks.
The ability of a class to inherit properties of another class.
The ability of a single variable to hold multiple values.
[ Option A ]
The word Polymorphism means Many Forms. It allows objects or methods to take multiple forms, enabling flexibility and reusability in code. Polymorphism improves code flexibility, readability, and maintainability. There are two main types of polymorphism in Java:
Compile-Time Polymorphism (Method Overloading):
Runtime Polymorphism (Method Overriding):
Q: 19 Which of the following statements is/are true regarding Java?
(A) Constants that cannot be changed are declared using the ‘static’ keyword.
(B) A class can only inherit one class that can implement multiple interfaces.
(A) is true
(B) is true
Both (A) and (B) are true
Neither (A) nor (B) is true
[ Option B ]
In Java, constants that cannot be changed are declared using final, often combined with static for class-level constants, example, static final int P = 33;. Simply using static does not make a variable constant.
Java supports single inheritance for classes, meaning a class can extend only one superclass. However, a class can implement multiple interfaces, allowing it to inherit behavior from multiple sources like multiple inheritance.
class Super {}
interface A {}
interface B {}
class Sub extends Super implements A, B
{
}
Q: 20 What is the role of content Providers in Android?
Controls the life cycle of activities
Provides a consistent and non-intrusive mechanism for signaling to users
Share data between applications
Supports non-code resources like strings and graphics
[ Option C ]
In Android, Content Providers are mainly used to share data between applications in a secure and structured way. They provide a standard interface for accessing and managing data like contacts, images, videos, etc., and apps can query or modify this data using URIs.
Q: 21 Which of the following is the correct way to create an abstract class in Java?
class Demo { abstract void fun(); }
class abstract Demo { void abstract fun(); }
abstract class Demo { abstract void fun(); }
abstract class Demo { void fun() { abstract; } }
[ Option C ]
In Java, an abstract class must be declared using the abstract keyword before the class name, and any abstract method inside it must also be declared with the abstract keyword and cannot have a method body.
Q: 22 Choose the correct statement with respect to interfaces:
(i) Java does not support "multiple inheritance" however, it can be achieved by using interfaces.
(ii) Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.
(iii) To implement multiple interfaces, separate them with a comma (,).
Only (i)
(i) and (ii)
(ii) and (iii)
(i), (ii) and (iii)
[ Option D ]
Java does not support multiple inheritance with classes, i.e., a class cannot extend more than one class. However, Java allows a class to implement multiple interfaces. This provides a way to achieve multiple inheritance in Java.
When a class implements an interface, it must provide concrete definitions of all abstract methods defined in the interface. If the class does not implement all methods, it must be declared as abstract.
A class can implement multiple interfaces by separating them with a comma in the implements clause.
class Demo implements MyInterfaceP, MyInterfaceQ {
// Implementation of methods from both interfaces
}
interface MyInterfaceP {
void methodOne();
}
interface MyInterfaceQ {
void methodTwo();
}
class MyClass implements MyInterfaceP, MyInterfaceQ {
public void methodOne() {
System.out.println("Method One from MyInterfaceP implemented.");
}
public void methodTwo() {
System.out.println("Method Two from MyInterfaceQ implemented.");
}
}
public class Driver {
public static void main(String args[]) {
MyClass obj = new MyClass();
obj.methodOne();
obj.methodTwo();
}
}
Q: 23 What does the .NET framework primarily consist of?
JVM and Web forms
CLR and Web forms
CLR and .NET framework class libraries
JVM and Base class libraries
[ Option C ]
The .NET framework primarily consists of two major components, the Common Language Runtime (CLR) and the .NET Framework Class Libraries.
The CLR is the Execution Engine that runs applications and provides services such as memory management, security, and exception handling.
The Class Libraries provide a rich set of reusable types and APIs for common programming tasks like file handling, database interaction, and user interface creation.
Q: 24 What output is produced for the command: “java cmd a b c d”, when following code is run?
class cmd {
public static void main(String args[]) {
System.out.println(args[2]);
}
}
c
cmd
b
a
[ Option A ]
Command Line Argument are parameters that are supplied to the application program at the time of invoking it for execution. We can customize the behavior of the main() method using command-line arguments.
When command line arguments are supplied to JVM, JVM wraps these and supply to args[ ]. It can be confirmed that they are actually wrapped up in args array by checking the length of args using args.length.
For the command java cmd a b c d the arguments are assigned as follows:
The statement System.out.println(args[2]); will print the value stored at index 2, which is "c".
Q: 25 Which of these exceptions is thrown in cases when the file specified for writing is not found?
FileOutputException
FileException
FileNotFoundException
IOException
[ Option C ]
In Java, when a program attempts to open a file for reading or writing and that file does not exist or cannot be located in the specified path, Java throws a FileNotFoundException. This exception is a subclass of IOException and specifically indicates problems related to missing files.
Q: 26 Which syntax is incorrect to initialize a two-dimensional array in Java?
int myarr[][] = new int[3][4];
int[][] myarr = {{1, 2, 3},{4, 5, 6}};
int[][] myarr = new int[3][4];
int myarr = new int[3][4];
[ Option D ]
The incorrect syntax for initializing a two-dimensional array in Java is int myarr = new int[3][4];. This statement is wrong because it declares myarr as a simple integer variable, not as an array.
A two-dimensional (2-D) array must always be declared using two sets of square brackets [ ][ ] to indicate rows and columns.
Q: 27 In Java, what is a Base Class?
A class that is used as a template to create other classes and can be instantiated directly.
A class that is used as a foundation for other classes to inherit properties and methods.
A class that contains only static methods and variables.
A class that cannot be inherited by other classes and is only used for creating objects.
[ Option B ]
In Java, a Base Class (Parent Class or Super Class) is a class whose properties and methods are inherited by other classes. It serves as a foundation from which new classes (derived classes or subclasses) can extend functionality. This helps in reusing common code, reducing duplication, and implementing object-oriented feature like inheritance.
Syntax:
class BaseClass
{
……………..;
……………..;
}
class DerivedClass extends BaseClass
{
……………..;
……………..;
}
Q: 28 A class that exhibits a high degree of primitiveness encapsulates only ______________ operations.
Volatility
Primitive
Cohesive
Similarity
[ Option B ]
In object-oriented programming, a class is a blueprint for creating objects and can encapsulate (combine) data (variable) and operations (methods). The degree of primitiveness of a class refers to how basic or elementary its responsibilities are.
Q: 29 Which command is used to convert the code written in Java to bytecode?
javap
java
javadoc
javac
[ Option D ]
Compilation : Converting the Java source code (.java file) into bytecode (.class file) that can run on the Java Virtual Machine (JVM). The javac command is used to compile Java source code into bytecode.
javac FirstExample.java
Execution : Running the bytecode on the JVM. The java command is used to run the bytecode on the JVM.
java FirstExample
| COMMAND | USED FOR |
|---|---|
| javac | Compiles Java source code (.java) into bytecode (.class). |
| java | Runs the compiled Java bytecode on the Java Virtual Machine (JVM). |
| javadoc | Generates HTML documentation from Java source code comments. |
| javap | Disassembles bytecode (.class file) to view class structure, methods, and fields. |
| jar | Creates, views, or extracts Java Archive (.jar) files. |
| jdb | Java debugger. Used to debug Java programs. |
| jconsole | Java monitoring and management console for running Java applications. |
| jshell | Java REPL (Read-Eval-Print Loop) for running snippets of Java code interactively. |
Q: 30 Which of the following methods will create string in Java?
(i) String S = “Hello Java”;
(ii) String S2 = New string(“Hello Java”);
Only (i)
Only (ii)
Both (i) and (ii)
Neither (i) nor (ii)
[ Option A ]
In Java, strings can be created in two ways. The first method is by using string literals, for example: String s = "Hello Java";. In this case, the string is stored in the String Constant Pool (SCP), which allows Java to reuse memory efficiently.
The second method is by using the new keyword, for example: String s2 = new String("Hello Java");. This approach creates a new String object in heap memory, separate from the SCP, even if an identical string already exists in the pool.
However, in the given question, option (ii) is written as String S2 = New string("Hello Java");. This is incorrect due to Java’s case sensitivity:
Because of these errors, option (ii) will cause a Compile-Time Error (CTE), and only option (i) is valid as written.
Q: 31 What will be the value of arr[2] in the following code?
String[] arr = new String[3];
arr[0] = “Maths”;
arr[1] = “Science”;
Null
“Science”
“Maths”
“”
[ Option A ]
In the given code, a string array of size 3 is created using new String[3]. In Java, when an array of objects is created, all elements are automatically initialized to null unless explicitly assigned a value.
Here, only arr[0] and arr[1] are assigned the values "Maths" and "Science" respectively. The third element, arr[2], is never given any value. Therefore, it retains its default initialization, which is null.
Q: 32 Which protocol does RMI use to communicate between objects distributed across a network?
HTTP
TCP/IP
SMTP
FTP
[ Option B ]
In Java, RMI (Remote Method Invocation) is a technology that allows an object running in one Java virtual machine (JVM) to invoke methods on an object located in another JVM, possibly on a different machine over a network.
To enable this communication, RMI relies on a network protocol that provides reliable, ordered, and error-checked delivery of data between applications.
The protocol used for this purpose is TCP/IP (Transmission Control Protocol / Internet Protocol), which is a standard suite of communication protocols used for transmitting data over networks, including the Internet.
Q: 33 What is the right syntax to read an integer from the user in Java?
Scanner sc = new Scanner(System.in); int num = sc.readInt();
Scanner sc = new Scanner(System.in); int num = sc.inputInt();
Scanner sc = new Scanner(System.in); int num = sc.nextInt();
Scanner sc = new Scanner(System.in); int num = sc.getInt();
[ Option C ]
In Java, to read input from the user, we commonly use the Scanner class, which is part of the java.util package. First, a Scanner object is created using new Scanner(System.in), which connects the scanner to standard input like keyboard.
The Scanner class provides several methods to read different types of data. To read an integer, the correct method is nextInt().
Q: 34 Which of the following is a correct statement about constructors in Java?
Constructors cannot be overloaded.
A constructor can be called directly like a regular method.
A constructor does not have a return type, not even void type.
A class can have only one constructor.
[ Option C ]
In Java, a constructor is a special block of code that is automatically executed when an object of a class is created. Its main purpose is to initialize the object, that is, to assign initial values to variables or run setup code.
class MyClass
{
MyClass() //This is a constructor.
{
System.out.println("Constructor called.");
}
void MyClass() //Not a constructor, this is a method.
{
System.out.println("This is a method.");
}
}
Q: 35 Which statement is true about an Interface in Java?
An interface cannot extend another interface.
An interface can contain implemented methods.
An interface can contain instance variables.
A class can implement multiple interfaces.
[ Option D ]
The abstract class is used for achieving partial abstraction. Unlike abstract class an interface is used for full abstraction.
Interface looks like a class but it is not a class. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract (only method signature, no body). Also, the variables declared in an interface are public, static and final by default.
A class extends another class, an interface extends another interface, but a class implements an interface.
A class can implement more than one interface which is one of the key features of interfaces in Java.
interface MyInterface1
{
void fun1();
}
interface MyInterface2
{
void fun2();
}
class Demo implements MyInterface1,MyInterface2
{
public void fun1()
{
System.out.println("Inside fun1() Method");
}
public void fun2()
{
System.out.println("Inside fun2() Method");
}
void fun3()
{
System.out.println("Inside fun3() Method");
}
}
class InterfaceExample
{
public static void main(String args[])
{
Demo obj1=new Demo();
obj1.fun1();
obj1.fun2();
obj1.fun3();
MyInterface1 obj2=new Demo();
obj2.fun1();
//obj2.fun2(); Error.
//obj2.fun3(); Error.
MyInterface2 obj3=new Demo();
//obj3.fun1(); Error.
obj3.fun2();
//obj3.fun3(); Error.
}
}
OUTPUT
Inside fun1() Method
Inside fun2() Method
Inside fun3() Method
Inside fun1() Method
Inside fun2() Method
Q: 36 Which component of Java platform is responsible for converting bytecode into machine-specific code?
Java Runtime Environment (JRE)
Java Development Kit (JDK)
Java Compiler
Java Virtual Machine (JVM)
[ Option D ]
Java is a platform-independent programming language, which means Java programs can run on any operating system without modification. This is possible because Java does not compile code directly into machine-specific instructions.
Instead, Java source code (.java files) is first compiled by the Java Compiler into an intermediate form called bytecode (.class files). Bytecode is platform-independent and cannot be executed directly by the operating system. To run a Java program, the Java Virtual Machine (JVM) is used.
The JVM is a part of the Java Runtime Environment (JRE), and it is responsible for interpreting or converting the bytecode into machine-specific code that the operating system can execute.
Q: 37 Which of the following is true about Java applets?
No plugin is required to run an applet.
They run within a web browser and work at server side.
Applets are not secured.
They run within a web browser and work at client side.
[ Option D ]
In Java, an applet is a small program designed to be embedded in a web page. The core idea of applets is that they run inside a web browser on the client’s machine, not on the server. This allows interactive features, animations, or graphics to be displayed on the user’s browser.
import java.applet.Applet;
import java.awt.Graphics;
public class MyApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello, Suraku", 60, 60);
}
}
HTML FILE TO RUN THE APPLET:
<html>
<body>
<applet code="MyApplet.class" width="250" height="100"></applet>
</body>
</html>
Q: 38 What is the purpose of the ‘new’ keyword in Java?
Defines a new method
Imports a package
Creates a new object instance
Declares a new variable
[ Option C ]
In Java, the new keyword is used to create new objects at runtime. When a class is defined, it serves as a blueprint, but no memory is allocated until an object of that class is created. The new keyword allocates memory for the object on the heap and calls the constructor of the class to initialize it.
Q: 39 What is bytecode in Java?
Machine-dependent code in Java.
Source code in Java.
Intermediate machine-independent code generated by Java compiler.
Machine code specified to a processor.
[ Option C ]
In Java, when you compile a .java file using the javac compiler, it does not directly generate machine code. Instead, it produces an intermediate code known as bytecode, stored in .class files.
This bytecode is platform-independent, meaning it can run on any device that has the Java Virtual Machine (JVM). The JVM then converts this bytecode into machine-specific instructions depending on the operating system and hardware. This is the main reason Java is called Write Once, Run Anywhere (WORA).
| TYPE OF CODE | DESCRIPTION |
|---|---|
| Source Code | Human-readable, high-level program written by the developer using programming languages like Java, C, C++, Java, Python. It contains logic, statements, and comments. It cannot be executed directly by the computer and must be compiled or interpreted. |
| Bytecode | Intermediate, platform-independent code generated by the Java compiler. It is stored in .class files. Bytecode is not machine code, but it can run on any system that has a Java Virtual Machine (JVM), which converts bytecode into machine code at runtime. |
| Object Code | Low-level code produced by a compiler. It contains machine instructions plus unresolved references, placeholders, and symbol tables. Object code is not executable on its own and must be linked with other object files and libraries.
|
| Machine Code | The final binary instruction set understood directly by the CPU. Produced after linking all object files. It contains fully resolved addresses and ready-to-execute commands. Represented in 0s and 1s.
|
| Executable Code | The complete, linked, and ready-to-run program created by combining machine code, libraries, and metadata. This is the file that users can double-click or run from the terminal. It loads directly into memory and executes on the operating system.
|
Q: 40 What is the primary purpose of using Intents in Android?
To manage the app’s memory allocation
To execute background threads
Message passing framework
To compile and build the Android project
[ Option C ]
In Android, Intents are used as a messaging object that allows communication between different components of an app such as Activities, Services, and Broadcast Receivers, or even between different apps.
Intents can be used to start a new activity, launch a service, deliver a broadcast, or request an action like opening a web page or sharing content.
Q: 41 Which of the following is NOT an advantage of Java bytecode?
Portability
Security
Platform Independent
Faster execution than machine code
[ Option D ]
Java programs are compiled into bytecode, which is an intermediate, platform-independent code. This bytecode is executed by the Java Virtual Machine (JVM), which interprets [Just-In-Time (JIT)] compiles it for the underlying hardware. The advantages of Java bytecode include:
However, bytecode is generally slower than native machine code because it must be interpreted or compiled at runtime.
Q: 42 What is the access specifier used to make members of a class accessible only within the same package?
private
public
package-private
More than one of the above
[ Option C ]
In Java, access specifiers control the visibility of class members. To make members accessible only within the same package, we use package-private (default) access.
Q: 43 What is the output of the following code?
public class Demo {
public static void main(String[] args) {
int x = 5;
System.out.println(++x*2);
}
}
12
11
10
Compile Time Error
[ Option A ]
In this code, the variable x is initially assigned the value 5. The expression ++x * 2 uses the pre-increment operator, which means x is increased before it is used in the calculation. So, ++x changes the value of x from 5 to 6, and then the multiplication 6 * 2 is performed. Therefore, the output printed by System.out.println(++x * 2); is 12.
Q: 44 Which keyword is used in Java to implement inheritance?
extends
inherits
implements
None of the above
[ Option A ]
In Java, extends keyword is used for class inheritance where a subclass inherits properties and methods from a superclass. Syntax for inheritance in Java is class Child extends Parent {}.
Q: 45 Which of the following code gives error of “outofbounds” in array?
int[] a = new int[5]; a[4] = 5;
int[] a = {1, 2, 3, 4, 5}; System.out.print(a[2]);
int[] a = new int[10]; for (int I = 0; i < a.length; i++) { a[i] = i*2; }
int[] a = new int[3]; a[3] = 9;
[ Option D ]
In Java, an ArrayIndexOutOfBoundsException occurs when a program tries to access an array index that does not exist. Java arrays always start with index 0, and the last valid index is always length − 1.
So, if you create an array like int[] a = new int[3];. This array has 3 elements, and their valid indexes are a[0], a[1], and a[2]. Any attempt to access a[3], a[4], etc., will cause an ArrayIndexOutOfBoundsException.
Q: 46 Which of the following streams is used to deserialize the primitive data and objects in Java?
PrintWriter
BufferedReader
FileWriter
ObjectInputStream
[ Option D ]
In Java, streams are used to handle input and output of data. The core concept here is serialization and deserialization:
Serialization: Converting an object into a byte stream so it can be saved to a file or sent over a network.
Deserialization: Reconstructing the object from the byte stream back into a Java object.
To handle deserialization of primitive data types and objects, Java provides the ObjectInputStream class.
Q: 47 Which of the following Java technology is used for server-side programming in Internet applications?
Java Servlet
Java Swing
JavaFX
Java Applets
[ Option A ]
In Java, Java Servlets are used for server-side programming. Servlets run on a web server or application server and generate responses, usually in the form of HTML, to be sent to web browsers.
Java Swing and JavaFX are used for creating desktop GUI applications, and Java Applets are designed for client-side execution within web browsers.
Q: 48 What is the output of following code?
public class ex {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5};
printn(a);
}
public static void printn(int[] a){
for(int n : a) {
System.out.print(n+” “);
}
}
}
Compilation error
5 4 3 2 1
Runtime error
1 2 3 4 5
[ Option D ]
In this Java code, an integer array a is created with the elements {1, 2, 3, 4, 5}. The method printn(a) is called, which receives this array and uses a for-each loop to iterate through each element. The for-each loop processes elements in the same order in which they appear in the array. Therefore, the values are printed sequentially: 1 2 3 4 5.
Q: 49 What will be the output of the code after the given code executes?
int a = 5;
int b = a++;
System.out.println(“a = ”+a+”b = ”+b);
a = 6 b = 5
a = 5 b = 6
a = 6 b = 6
a = 5 b = 5
[ Option A ]
In this code, the variable a is first assigned the value 5. When the statement int b = a++; executes, the operator used is the post-increment operator (a++).
In post-increment, the current value of the variable is used first, and then the increment happens afterward. This means that the value of a is first assigned to b, and only after this assignment does a increase by 1. As a result, after the statement executes, a becomes 6 while b remains 5.
Q: 50 Which of the following is not an access modifier in Java language?
public
private
protected
external
[ Option D ]
In Java, access modifiers are keywords used to define the visibility and accessibility of classes, methods, and variables. They control which parts of a program can access a particular class member. Java provides four main access levels, public, private, protected, and the default (no modifier).
The public modifier allows access from anywhere, private restricts access to within the same class, and protected allows access within the same package and subclasses.
Q: 51 Which keyword is used in Java to inherit a class?
inherits
extends
implements
super
[ Option B ]
To inherit a class, Java provides the extends keyword, which indicates that the subclass will acquire all non-private (private members are never inherited) fields and methods of the superclass.
Q: 52 What is the correct sequence of steps for handling a client in a Java servlet lifecycle of a servlet?
init method, service method, doPost/doGet method
init method, doPost/doGet method, service method
service method, doPost/doGet method, destroy method
init method, service method, destroy method
[ Option D ]
The lifecycle of a Java servlet involves these key steps in sequence:
Q: 53 What will be the output of the following code?
class Vehicle {
public void move() {
System.out.println("Vehicle is moving");
}
}
class Car extends Vehicle {
public void move() {
System.out.println("Car is moving");
}
}
public class Main {
public static void main(String[] args) {
Vehicle v = new Car();
v.move();
}
}
Runtime error
Vehicle is moving
Compilation error
Car is moving
[ Option D ]
When a class inherits another class using the extends keyword, it can reuse or modify the methods of the parent class. This concept is called inheritance.
Java also supports Method Overriding, which allows a subclass to provide its own implementation of a method defined in the parent class.
When a method is overridden, the version of the method that belongs to the actual object (not the reference type) is called at runtime, this is known as Runtime Polymorphism.
In the given code, the Vehicle class has a method move() that prints "Vehicle is moving". The Car class extends Vehicle and overrides the move() method to print "Car is moving".
In the main method, a reference of type Vehicle is used to create an object of type Car: Vehicle v = new Car();. When v.move() is called, Java checks the actual object type at runtime, sees that it is a Car, and executes the overridden move() method in the Car class. Therefore, the program prints "Car is moving".
Q: 54 Which of the following is not a valid variable name in Java language?
x15
rate
rate_of_taxi
rate-of-taxi
[ Option D ]
Java naming convention is a mechanism to follow as you decide what to name your identifiers such as class, package, variable, constant, method, etc.
Rules For Writing Variable Name:
The variable name rate-of-taxi contains hyphens (-), which Java treats as subtraction operators and it is invalid variable name.
Q: 55 What is the correct way to close a file in Java after writing to it?
fileInput.close();
file.close();
fileWriter.close();
fileStream.close();
[ Option C ]
The correct way to close a file in Java after writing to it is to use the close() method of the FileWriter class. This method is called on the FileWriter object after all writing operations are complete.
Closing the file writer releases any system resources associated with it, flushes buffers, and ensures that data is properly saved to the file. For example, fileWriter.close(); is the standard way to close the file after writing.
Q: 56 Which of these classes are the direct subclasses of the Throwable Class?
Exception and VirtualMachineError Class
Error and Exception Class
IOException and VirtualMachineError Class
RuntimeException and Error Class
[ Option B ]
In Java, Throwable is the root class for all exceptions and errors that can occur during program execution. It defines the common behavior for objects that can be thrown using the throw keyword. It has two direct subclasses, Error and Exception.

Note:
Q: 57 ______________ is a standard machine language into which Java source is compiled.
Interpreter
Object Oriented
Byte Code
Assembly
[ Option C ]
In Java programming, the Java source code (.java) is first compiled by the Java Compiler into Byte Code (.class). Byte Code is a standardized machine-independent code that can be executed on any platform using the Java Virtual Machine (JVM).
Q: 58 Consider the following class definition:
public class Test {
int var;
String myString;
public Test() {
this(0, “Default”); }
public Test(int var, String myString) {
this.var = var;
this.myString = myString;
}
}
What will the following code do?
Test test = new Test();
Create an object test with var = 0 and myString =”Default”
Throw a runtime exception
Create an object test with var = 0 and myString = null
Throw a compilation error
[ Option A ]
The class Test contains two constructors, a zero argument constructor and a parameterized constructor. When the zero argument constructor is called, it does not directly initialize the variables. Instead, it uses the keyword this(0, "Default") to explicitly call the parameterized constructor. This means the execution is transferred to the constructor Test(int var, String myString), which assigns the values var = 0 and myString = "Default" to the object.
As a result, the object is successfully created, and both instance variables receive valid initial values. Therefore, the object test is created with the expected initialized properties.
Q: 59 Size of “int” data type in Java language is—
64-bits
16-bits
8-bits
32-bits
[ Option D ]
In Java, the size of each primitive data type is fixed, regardless of the operating system or machine architecture. The int data type always occupies 32 bits (4 bytes) of memory. This consistency is a key feature of Java Portability across different platforms.

| DATA TYPE | SIZE | DEFAULT VALUE | WRAPPER CLASS |
|---|---|---|---|
| boolean | 1 Bit | false | Boolean |
| char | 2 Byte | ‘u0000’ | Character |
| byte | 1 Byte | 0 | Byte |
| short | 2 Byte | 0 | Short |
| int | 4 Byte | 0 | Integer |
| long | 8 Byte | 0 | Long |
| float | 4 Byte | 0.0 | Float |
| double | 8 Byte | 0.0 | Double |
Q: 60 Which of the following class in Java is responsible for handling files in Java?
FileStream
FileHandler
File
FileManager
[ Option C ]
In Java, the File class (java.io package) is responsible for handling operations related to files and directories. It allows you to create files, check whether a file exists, delete files, get file information (size, name, path), and work with folders as well.
Although File does not directly read or write data, it plays the key role in managing and accessing files. For reading or writing content, Java uses other classes like FileInputStream, FileOutputStream, FileReader, and FileWriter.
Thank you so much for taking the time to read my Computer Science MCQs section carefully. Your support and interest mean a lot, and I truly appreciate you being part of this journey. Stay connected for more insights and updates! If you'd like to explore more tutorials and insights, check out my YouTube channel.
Don’t forget to subscribe and stay connected for future updates.