Programming in Java
Programming in Java
QUESTION 1:
Correct Answer:
Detailed Solution:
Creating a .class file from .java using javac command is a compilation task, whereas execution of a
.class file using java is the process of interpretation.
QUESTION 2:
b. HTML tags
Correct Answer:
Detailed Solution:
A .class file is a complied version of the .java file in byte code (it is a kind of object code with JVM (Java
Virtual Machine) as the target machine.
QUESTION 3:
Which of the following is not an object-oriented programming paradigm?
a. Encapsulation
b. Inheritance
c. Polymorphism
Correct Answer:
Detailed Solution:
Dynamic memory allocation is a memory allocation strategy and not a programming paradigm.
QUESTION 4:
b. The Java compiler translates the source code directly into the machine-level language.
The compiled code (byte code) can be executed (interpreted) on any platform running a JVM.
QUESTION 5:
a. Assembler
b. Compiler
c. Interpreter
d. Fortran
Correct Answer:
d. Fortran
Detailed Solution:
A computer understands instructions in machine code i.e., in the form of 0s and 1s. Special translators
are required for this operation like Assembler, Compiler and Interpreter. Fortran is a programming
language but not a language processor.
QUESTION 6:
A platform is the hardware or software environment in which a program runs. Which of the following
is/are Java platform component(s)?
a. HTML
c. Javascript
d. HotJava
Correct Answer:
Detailed Solution:
"A platform is the hardware or software environment in which a program runs. Some of the most
popular platforms are Microsoft Windows, Linux, Solaris OS, and Mac OS. Most platforms can be
described as a combination of the operating system and underlying hardware. The Java platform differs
from other platforms as it is a software-only platform that runs on top of other hardware-based
platforms.
The Java platform has two components:
The Java Virtual Machine
The Java Application Programming Interface (API)
QUESTION 7:
I. Compile the Program: Use the javac command to compile the code into bytecode.
II. Edit the Program: Write the code in a text editor or IDE.
III. Run the Program: Use the java command to execute the
bytecode.
IV. Which of the following options represents this sequence?
Correct Answer:
Detailed Solution:
The Java development process involves writing code (Edit), converting it to bytecode (Compile), and then
executing it on the JVM (Run).
QUESTION 8:
a. javac is used to edit Java code, while java runs Java programs.
b. javac compiles Java source code to bytecode, while java executes the bytecode on the JVM.
Correct Answer:
b. javac compiles Java source code to bytecode, while java executes the bytecode on the JVM.
Detailed Solution:
The javac command converts .java source files into .class bytecode files.
The java command executes the .class file using the Java Virtual Machine (JVM).
QUESTION 9:
a. Platform Independence
b. Object-Oriented Programming
d. Supports Polymorphism
Correct Answer:
Detailed Solution:
Java is platform-independent, object-oriented, and secure. It does not support explicit pointers, as they
can lead to memory management issues and compromise security.
QUESTION 10:
class NPTEL {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
a. Hello, World!
b. HelloWorld!
c. Compilation Error
d. Runtime Error
Correct Answer:
a. Hello, World!
Detailed Solution:
Refers to the standard input stream, which is typically the keyboard by default.
Correct Answer:
Refers to the standard input stream, which is typically the keyboard by default.
Detailed Solution:
System.in refers to the standard input device and the keyboard is treated as standard input device. Thus,
the code implies reading a data from keyboard.
Please refer to chapter 3 of book Joy With Java for a more detailed explaination.
QUESTION 2:
30 99 178
30 88 129
30 99 187
88 99 178
Correct Answer:
30 99 187
Detailed Solution:
If you perform any change for instance variable these changes won’t be reflected for the remaining
objects. Because for every object a separate copy of instance variable will be there. But if you do any
change to the static variable, that change will be reflected for all objects because a static instance
maintains a single copy in memory.
Please refer to chapter 3 of book Joy With Java for a more detailed explaination.
QUESTION 3:
String foo() {
return "foo";
}
}
}
9 7 7 foo34 34foo
72 34 34 foo34 34foo
9 7 7 foo 7 7foo
Correct Answer:
839 45foo45 9foo
Detailed Solution:
Here, print() methods internally converts the data in its argument into a String object and then print
the composition. Here, + is the concatenation of different String representation.
Please refer to chapter 3 of book Joy With Java for a more detailed explaination.
QUESTION 4:
Correct Answer:
Detailed Solution:
Please refer to chapter 3 of book Joy With Java for a more detailed explaination.
Encapsulation is one of the fundamental principles of object-oriented programming. It involves bundling
the data (variables) and the methods (functions) that operate on the data into a single unit, typically a
class. By making certain data private and providing public methods to access or modify it, encapsulation
helps hide implementation details from the outside world while exposing only the required functionality.
This improves code modularity, security, and maintainability.
QUESTION 5:
Correct Answer:
Constructors are used to initialize objects.
Detailed Solution:
A constructor is a special method in a class that is automatically called when an object of the class is
created. Its main purpose is to initialize the object's properties (variables). Unlike other methods,
constructors:
Have the same name as the class.
Do not have a return type, not even void. A class can have multiple constructors with
different parameter lists (constructor overloading) to allow flexibility in object creation.
Please refer book Joy with Java Chapter 3 for mored etailed explaination.
QUESTION 6:
Avoiding name space collision between instance variables and method parameters
Correct Answer:
Avoiding name space collision between instance variables and method parameters
Detailed Solution:
The this keyword is used to refer to the current instance of a class. It is commonly used to resolve
ambiguity when instance variables and method parameters have the same name. For example:
class Example {
int value;
Example(int value) {
this.value = value; // Resolves name collision by referring to
the instance variable
}
}
Here, this.value refers to the instance variable, while value refers to the parameter of the constructor.
This avoids confusion and ensures the proper assignment of values.
Please refer book Joy with Java Chapter 3 for mored etailed explaination.
QUESTION 7:
Correct Answer:
Detailed Solution:
The main method in Java must be declared as public static void main(String[] args) to
be recognized by the JVM as the entry point of the program. The public modifier allows the method
to be accessible from anywhere, static ensures it can be called without creating an instance of the
class, and String[] args is the parameter used for command-line arguments.
Note: Please refer book Joy with Java Chapter 3 for mored etailed explaination.
QUESTION 8:
BufferedReader
Scanner
DataInputStream
Correct Answer:
Detailed Solution:
print()
println()
printf()
format()
Correct Answer:
printf()
Detailed Solution:
The printf() method is used in Java to produce formatted output. It follows the syntax of
System.out.printf(format, arguments) where the format specifies how the output should
appear. For example:
Which Java class is primarily used to read input from the console?
Scanner
BufferedReader
Console
DataInputStream
Correct Answer:
Scanner
Detailed Solution:
The Scanner class is widely used to read input from the console in Java. It provides methods to parse
and read primitive types (e.g., nextInt(), nextDouble()) and strings (e.g., next(), nextLine()). It
is a versatile and easy-to-use class for input handling.
Note: Please refer to chapter 3 of book Joy With Java for a more detailed explaination.
QUESTION 1:
Correct Answer:
Detailed Solution:
The super keyword is used to refer to the immediate parent class. It is commonly used to invoke the
parent class constructor or access its non-private methods and variables. However, it cannot access
private members of the parent class or be used in static methods.
QUESTION 2:
class StaticScopeDemo {
static int x = 5;
a. 15
b. Compilation Error
c. 5
d. 10
Correct Answer:
b. Compilation Error
Detailed Solution:
The block within main() tries to declare a local variable x that has the same name as an already
existing variable in the same scope, which causes a compilation error. Variable names must be unique
within the same scope
QUESTION 3:
class Parent {
void display() {
System.out.println("Parent display");
}
}
a. Parent display
b. Child display
c. Compilation Error
d. Runtime Error
Correct Answer:
b. Child display
Detailed Solution:
This is an example of method overriding. The display() method in the Child class overrides the method in
the Parent class. When the method is called, Java uses dynamic method dispatch to execute
the Child class implementation.
QUESTION 4:
c. A class inheriting from an abstract class must implement all its abstract methods unless it is
itself abstract.
Correct Answer:
c. A class inheriting from an abstract class must implement all its abstract methods unless it is
itself abstract.
Detailed Solution:
Abstract classes cannot be instantiated directly. They may or may not contain abstract methods. A
subclass inheriting an abstract class must provide implementations for all abstract methods unless it is
also declared abstract.
QUESTION 5:
a. 5
b. 24
c. 120
d. Runtime Error
Correct Answer:
c. 120
Detailed Solution:
The fun method is a recursive function that calculates the factorial of a number. For fun(5), the
computation is 5 * 4 * 3 * 2 * 1 = 120.
QUESTION 6:
Which of the following is NOT true regarding the final keyword in Java?
Correct Answer:
Detailed Solution:
A class marked as final cannot be extended, meaning it cannot have subclasses. The other statements
about the final keyword are correct.
QUESTION 7:
class Test {
static int count = 0;
public Test() {
count++;
}
a. Count: 0
b. Compilation Error
c. Runtime Error
d. Count: 3
Correct Answer:
d. Count: 3
Detailed Solution:
The count variable is static, meaning it is shared among all instances of the class. Each time
a Test object is created, the constructor increments count. Since three objects are created, the
output is Count: 3.
QUESTION 8:
a. A subclass defining a method with the same name but different parameters than a
superclass method.
c. A subclass defining a method with the same name and parameters as a superclass method.
d. Using the super keyword to call the superclass version of an overridden method.
Correct Answer:
a. A subclass defining a method with the same name but different parameters than a
superclass method.
Detailed Solution:
If a method in a subclass has the same name but different parameters, it is method overloading, not
method overriding. Method overriding requires the same name and parameters.
QUESTION 9:
b. Child
c. Compilation Error
Correct Answer:
c. Compilation Error
Detailed Solution:
There will be a compilation error: Type mismatch: cannot convert from Parent to Child
QUESTION 10:
a. 5
b. 10
c. 15
d. Runtime Error
Correct Answer:
c. 15
Detailed Solution:
The fun function calculates the sum of the first n natural numbers using recursion. For fun(5), the
computation is 5 + 4 + 3 + 2 + 1 = 15.
QUESTION 1:
Which access modifier allows a method to be accessible within the same package but not from
outside the package?
a. default
b. private
c. public
d. protected
Correct Answer:
a. default
Detailed Solution:
The default access modifier (no explicit modifier specified) allows access to the method within the
same package but not from outside. It is also known as "package-private."
QUESTION 2:
What will happen if you attempt to access a private method from another class in Java?
Correct Answer:
Detailed Solution:
A private method is accessible only within the same class. Any attempt to access it from another class
results in a compilation error.
QUESTION 3:
class Person {
int a = 1;
int b = 0;
a. 1 Java 10
0 Java 0
b. 1 Java
0 Java
c. 10 Java
0 Java
d. 1 java 1
0 Java 0
Correct Answer:
b. 1 Java
0 Java
Detailed Solution:
If no super() or this() is included explicitly within the derived class constructor, the super() is implicitly
invoked by the compiler. Therefore, in this case, the Person class constructor is called first and then the
Employee class constructor is called. Up casting is allowed.
QUESTION 4:
a. java.util
b. my.package.util
c. default.package
d. system.java
Correct Answer:
a. java.util
Detailed Solution:
`java.util` is a built-in Java package containing utility classes such as `ArrayList`, `HashMap`, and
`Scanner`.
QUESTION 5:
a. define
b. package
c. import
d. namespace
Correct Answer:
b. package
Detailed Solution:
The `package` keyword is used in Java to define a package. For example, `package mypackage;` defines
a package named `mypackage`.
QUESTION 6:
a. import package.*;
b. import package.ClassName;
c. include package.ClassName;
d. use package.ClassName;
Correct Answer:
b. import package.ClassName;
Detailed Solution:
The syntax `import package.ClassName;` imports a specific class from a package. For example, `import
java.util.Scanner;` imports the `Scanner` class from the `java.util` package.
QUESTION 7:
class Base {
public void print() {
System.out.println("Base class...");
}
}
class Derived extends Base {
public void print() {
System.out.println("Derived
class...");
}
}
public class Main {
private static void main (String[] args)
{ Base b = new Base();
b.print();
Derived d = new Derived();
d.print();
}
}
How many errors does this program contain?
a. None
b. 1
c. 2
d. 3
Correct Answer:
b. 1
Detailed Solution:
Correct Answer:
d. They allow a class to achieve multiple inheritance.
Detailed Solution:
Interfaces in Java provide a mechanism to achieve multiple inheritance because a class can implement
multiple interfaces.
QUESTION 9:
What will happen if you do not specify an access modifier for a class in a package?
If no access modifier is specified for a class, it gets the default access level, making it accessible only
within the same package.
QUESTION 10:
a. default
b. protected
c. private
d. public
Correct Answer:
c. private
Detailed Solution:
The `private` modifier provides the most restrictive access, allowing access only within the class where it
is defined.
QUESTION 1:
a. I and II
b. II and III
c. I, II and III
Detailed Solution:
The finally block always executes except when the JVM exits using System.exit(). It can exist
without a catch block and may contain a return statement, though this is not recommended.
QUESTION 2:
interface A {
int x = 10;
void display();
}
class B implements A {
public void display() {
System.out.println("Value of x: " + x);
}
}
public class Main {
public static void main(String[] args) {
B obj = new B();
obj.display();
}
}
a. Value of x: 10
b. Value of x: 0
c. Compilation Error
d. Runtime Error
Correct Answer:
a. Value of x: 10
Detailed Solution:
Variables in interfaces are public, static, and final by default. Hence, the value of x is
accessible in the display method.
QUESTION 3:
class NPTEL {
public static void main(String[] args) {
try {
int a = 5;
int b = 0;
System.out.println(a / b);
} catch (ArithmeticException e) {
System.out.print("Error ");
} finally {
System.out.print("Complete");
}
}
}
a. 5 Complete
b. Error Complete
c. Runtime Error
d. Compilation Error
Correct Answer:
b. Error Complete
Detailed Solution:
An ArithmeticException is caught in the catch block, which prints “Error”. The finally
block executes afterward, printing “Complete”.
QUESTION 4:
Which of the following is TRUE regarding abstract class and an interface in Java?
a. I, II and III
b. II only
c. I and II only
d. II and III only
Correct Answer:
a. I, II and III
Detailed Solution:
Abstract classes can have constructors and concrete methods. Interfaces support multiple inheritance.
Before Java 8, interfaces could only contain abstract methods, but now they can include default and
static methods.
QUESTION 5:
a. NullPointerException
b. ArrayIndexOutOfBoundsException
c. IOException
d. ArithmeticException
Correct Answer:
c. IOException
Detailed Solution:
IOException is a checked exception, meaning it must be either caught or declared in the throws
clause of a method. The others are unchecked exceptions, which do not require explicit handling.
QUESTION 6:
a. try
b. catch
c. final
d. finally
Correct Answer:
c. final
Detailed Solution:
In Java, exceptions are handled using the try, catch, and finally blocks. The try block contains
code that might throw an exception, the catch block handles specific exceptions, and the finally
block
executes regardless of whether an exception occurs.
QUESTION 7:
c. To catch an exception
The throws keyword is used in a method signature to declare the exceptions that the method might
throw, alerting callers to handle or propagate these exceptions.
QUESTION 8:
Correct Answer:
Detailed Solution:
In Java, an interface can extend multiple interfaces. Interfaces can also contain public, static,
and final variables, but they cannot be instantiated directly.
QUESTION 9:
interface Demo {
void display();
}
a. Hello, NPTEL!
b. Compilation Error
c. Runtime Error
d. No Output
Correct Answer:
a. Hello, NPTEL!
Detailed Solution:
The Test class implements the Demo interface and provides a definition for the display method.
When display() is called, it prints “Hello, NPTEL!”.
QUESTION 10:
interface Calculator {
void calculate(int value);
}
b. Cube: 27 Square: 9
Correct Answer:
a. Square: 9 Cube: 9
Detailed Solution:
The Cube class overrides the calculate method of the Square class. In the Cube class’s calculate
method, super.calculate(value) is called, which executes the calculate method of the Square
class. First, "Square: 9" is printed by the superclass method. Then, the overridden method in Cube
prints "Cube: 9".NOC25-CS57 (JAN-2025 25S)
QUESTION 1:
a. Running thread: 0
Running thread: 1
Running thread: 2
Main method complete.
b. Running thread: 0
Main method complete.
Running thread: 1
Running thread: 2
Correct Answer:
a. Running thread: 0
Running thread: 1
Running thread: 2
Main method
complete
Detailed Solution:
In this program, the run() method is called directly instead of using start(). When run() is called
like this, it does not create a new thread; it behaves like a regular method call and runs on the main
thread. As a result, the output is sequential. To create a separate thread, you must call the start()
method.For a more detailed understanding of thread methods like run() and start(), refer to the
book Joy with Java.
QUESTION 2:
Correct Answer:
Detailed Solution:
Multithreading in Java allows multiple threads to run concurrently within the same program, sharing the
same memory space. This feature makes Java programs more efficient, especially for tasks like
multitasking or background processing. However, proper synchronization is crucial to avoid issues like
data inconsistency. For a more detailed explanation of multithreading concepts, refer to the book Joy
with Java.
QUESTION 3:
b. The program will throw an error when attempting to start the thread a second time.
d. The thread will run only once, and the second start() call will be ignored.
Correct Answer:
b. The program will throw an error when attempting to start the thread a second time.
Detailed Solution:
In Java, a thread can only be started once. If you try to call start() on the same thread object more
than once, the JVM will throw an IllegalThreadStateException. This is because a thread's lifecycle
allows it to transition to the "terminated" state after completing execution, and it cannot be restarted.
For more details about the thread lifecycle, refer to the book Joy with Java.
QUESTION 4:
b. The program will run successfully but will not create a new thread.
d. The program will throw a runtime error because Thread is not used.
Correct Answer:
b. The program will run successfully but will not create a new thread.
Detailed Solution:
In this code, the Runnable object is created, but it is executed directly using the run() method instead
of passing it to a Thread object. To create a new thread, you need to use:
Without this, the run() method behaves like a regular method call, and no new thread is created.
For more detailed guidance on creating threads using Runnable, refer to the book Joy with Java.
QUESTION 5:
b. The program will execute successfully, and the run() method will run in a new thread.
c. The program will execute the run() method directly on the main thread.
d. The program will throw a runtime error because Runnable is not properly implemented.
Correct Answer:
b. The program will execute successfully, and the run() method will run in a new thread.
Detailed Solution:
The Runnable interface is implemented by the class RunnableExample. To create a thread, the
Runnable object is passed to the Thread constructor, and calling start() ensures that the run() method
is executed in a new thread.For more details on creating threads using Runnable, refer to the book Joy
with Java.
QUESTION 6:
Which of the following states can a thread enter during its lifecycle in Java?
a. New, Runnable, Running, Blocked
Correct Answer:
Detailed Solution:
What does the thread scheduler use to decide which thread to run when multiple threads are in
the runnable state?
a. Thread priority
c. Thread name
a. Thread priority
Detailed Solution:
The thread scheduler uses thread priorities as a hint to determine the execution order of threads in
the runnable state. However, thread scheduling also depends on the operating system's scheduling
policies and may not strictly follow priority.
For more on thread scheduling, refer to the book Joy with Java.
QUESTION 8:
Consider the following program:
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
}
Correct Answer:
Detailed Solution:
Thread priority is a hint to the thread scheduler but does not guarantee execution order. The actual
behavior depends on the JVM and the underlying OS.For more on thread priorities, refer to the book Joy
with Java.
QUESTION 9:
Correct Answer:
Detailed Solution:
Thread synchronization is used to control the access of multiple threads to shared resources,
ensuring data consistency and preventing race conditions. This is typically done using synchronized
methods or blocks. For more details on thread synchronization, refer to the book Joy with Java.
QUESTION 10:
What is the primary difference between Byte Streams and Character Streams in Java?
b. Byte Streams are used for binary data, while Character Streams are used for text data.
b. Byte Streams are used for binary data, while Character Streams are used for text data.
Detailed Solution:
Byte Streams: Handle raw binary data like images or files (InputStream, OutputStream).
Character Streams: Handle text data and support encoding like Unicode (Reader, Writer).
Character Streams are better for text processing, especially when handling international characters.
For a detailed understanding of Java I/O streams, refer to the book Joy with Java.
QUESTION 1:
import java.io.*;
class ReadFile {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("NPTEL.txt");
BufferedReader br = new BufferedReader(fr);
System.out.println(br.readLine());
br.close();
}
}
a. Hello, World!
c. IOException
d. null
Correct Answer:
Detailed Solution:
BufferedReader to read the first line from the file NPTEL.txt. Since the file contains “This is
Programming in Java online course.”, it is printed.
QUESTION 2:
Which of these classes is used to write primitive data types to an output stream in Java?
a. FileWriter
b. DataOutputStream
c. PrintWriter
d. BufferedOutputStream
Correct Answer:
b. DataOutputStream
Detailed Solution:
The DataOutputStream class is used to write primitive data types (e.g., int, float, boolean)
to an output stream.
QUESTION 3:
import java.io.*;
class RandomAccessFileExample {
public static void main(String[] args) throws IOException {
RandomAccessFile file = new RandomAccessFile("test.dat", "rw");
file.writeInt(100);
file.seek(0);
System.out.println(file.readInt());
file.close();
}
}
a. 0
b. Runtime Error
c. Compilation Erro
d. 100
Correct Answer:
d. 100
Detailed Solution:
The program writes the integer 100 to the file test.dat. Using the seek(0) method, the file
pointer is reset to the beginning, and the integer is read back and printed.
QUESTION 4:
a. file.exists()
b. file.isFile()
c. file.fileExists()
d. file.isAvailable()
Correct Answer:
a. file.exists()
Detailed Solution:
The exists() method in the File class checks if a file or directory exists in the specified path.
QUESTION 5:
import java.io.*;
class SequenceInputStreamExample {
public static void main(String[] args) throws IOException {
ByteArrayInputStream input1 = new
ByteArrayInputStream("123".getBytes());
ByteArrayInputStream input2 = new
ByteArrayInputStream("ABC".getBytes());
SequenceInputStream sequence = new
SequenceInputStream(input1, input2);
int i;
while ((i = sequence.read()) != -1) {
System.out.print((char) i);
}
}
}
a. 123ABC
b. ABC123
c. Compilation Error
d. Runtime Error
Correct Answer:
a. 123ABC
Detailed Solution:
The SequenceInputStream combines input1 and input2 streams sequentially. It first reads
the content of input1 (123), followed by input2 (ABC), resulting in 123ABC.
QUESTION 6:
class Main {
a. 30
b. Compiler Error
c. Garbage value
d. 0
Correct Answer:
b. Compiler Error
Detailed Solution:
i is assigned a value twice. Final variables can be assigned values only one. Following is the compiler
error “Main.java:5: error: variable i might already have been assigned”.
QUESTION 7:
import java.io.*;
class Chararrayinput
{
public static void main(String[] args) {
a. abc
b. abcd
c. abcde
Correct Answer:
Detailed Solution:
No output is printed. CharArrayReader object input1 contains string “abcdefgh” whereas object input2
contains string “bcde”, when while((i=input1.read())==(j=input2.read())) is executed the starting
character of each object is compared since they are unequal control comes out of loop and nothing is
printed on the screen.
QUESTION 8:
a. 20
b. 100
c. 1000
d. 2
Correct Answer:
a. 20
Detailed Solution:
Here the class instance variable name(num) is same as calc() method local variable name(num). So for
referencing class instance variable from calc() method, this keyword is used. So in statement this.num =
num * 10, num represents local variable of the method whose value is 2 and this.num represents class
instance variable whose initial value is 100. Now in printNum() method, as it has no local variable whose
name is same as class instance variable, so we can directly use num to reference instance variable,
although this.num can be used.
QUESTION 9:
import java.io.*;
public class W7 {
public static void main(String[] args) {
try {
writer.write(9 + 97);
writer.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
c. j
d. 106
Correct Answer:
c. j
Detailed Solution:
The output of this program will be the character 'j' because the Unicode code point for 106
corresponds to 'j'.
QUESTION 10:
What will be the output of the following code.
import java.io.File;
class FileSizeEample {
public static void main(String[] args) {
// Specify the file path
String filePath = "file.txt";
a. 42
b. 35
c. 7
d. 0
Correct Answer:
a. 42
Detailed Solution:
The length() method on the File object, which returns the size of the file in bytes.
Number of questions: 10 Total marks: 10 × 1 = 10
QUESTION 1:
Which of the following is TRUE regarding check box and radio button?
Check box is used for single selection item whereas radio button is used for multiple
selection. Check box is used for multiple selection items whereas radio button is used for
single selection. Both are used for multiple as well as single item selection.
Correct Answer:
Check box is used for multiple selection items whereas radio button is used for single selection.
Detailed Solution:
Check box is used for multiple selection items whereas radio button is used for single selection. For
example, if a form is asking for your favorite hobbies, there might be multiple correct answers to it,
in that case check box is preferred. And if a form is asking about gender, there must be only one
true
QUESTION 2:
Which of the following is the latest graphics and media package for Java?
Applet
AWT
Swing
JavaFX
Correct Answer:
JavaFX
Detailed Solution:
JavaFX is a set of latest graphics and media packages in Java that enables developers to design, create,
test, debug, and deploy rich client applications that operate consistently across diverse platforms.
More details can be found here: https://docs.oracle.com/javafx/2/overview/jfxpub-overview.htm
QUESTION 3:
HeadlessException
AWTException
FontFormatException
IllegalStateException
Correct Answer:
IllegalStateException
Detailed Solution:
Which of the following statement is FALSE about the update() in java.awt package?
Sets the color of the graphics context to be the foreground color of this component.
Correct Answer:
Detailed Solution:
The update() function does not update the component by checking an online repository rather it,
sets the color of the graphics context to be the foreground color of this component, calls this
component's paint method to completely redraw this component and clears this component by
filling it with the
background color.
QUESTION 5:
Which of the following method is used to remove all items from scrolling list in java.awt.list?
hide()
remove()
clear()
close()
Correct Answer:
clear()
Detailed Solution:
The function clear() in java.awt.list is used for remove all items from scrolling list.
QUESTION 6:
Which layout manager arranges components in a single row or column in Commented [NP1]: no question shold be given
Java? from applet
Commented [DM2R1]: changed. Thanks.
FlowLayout
BorderLayout
GridLayout
CardLayout
Correct Answer:
FlowLayout
Detailed Solution:
The FlowLayout arranges components sequentially, either in a single row or column, based on the
available space.
QUESTION 7:
Correct Answer:
Detailed Solution:
AWT is the Java library for creating GUI components like buttons and windows.
QUESTION 8:
Label
Button
TextField
Checkbox
Correct Answer:
Button
Detailed Solution:
Correct Answer:
Detailed Solution:
There is a Frame with two Labels and two TextFields in the given GUI.
QUESTION 10:
A check box can be in an "on" (true) and in "off" (false) state simultaneously.
Correct Answer:
Clicking on a check box changes its state from "on" to "off," or from "off" to "on."
Detailed Solution:
A check box is a graphical component that can be in either an "on" (true) or "off" (false) state. Clicking
on a check box changes its state from "on" to "off," or from "off" to "on.". A check box cannot be in
both “on” and “off” state simultaneously. Further, several check boxes can be grouped together under
the control of a single object, using the CheckboxGroup class. In a check box group, at most one button
can be in the "on" state at any given time. Clicking on a check box to turn it on forces any other check
box in the same group that is on into the "off" state.
QUESTION 1:
Which Swing component is best suited for displaying a drop-down list of selectable options?
a. JButton
b. JComboBox
c. JTextField
d. JPanel
Correct Answer:
b. JComboBox
Detailed Solution:
JComboBox is a Swing component that provides a drop-down list from which users can select one
option.
QUESTION 2:
import javax.swing.*;
import java.awt.*;
c. Compilation Error.
d. Runtime Error.
Correct Answer:
Detailed Solution:
The FlowLayout layout manager arranges components in a row. Here, both buttons are added and
displayed in the frame.
QUESTION 3:
Which of the following is true about the JLabel component in Java Swing?
Correct Answer:
Detailed Solution:
JLabel can display both text and images/icons. It is commonly used for non-interactive purposes in
Swing GUIs.
QUESTION 4:
a. mouseClicked()
b. keyPressed()
c. actionPerformed()
d. componentShown()
Correct Answer:
a. mouseClicked()
Detailed Solution:
The mouseClicked() method in the MouseListener interface is used to handle mouse click
events in Java Swing.
QUESTION 5:
What should replace // INSERT CODE HERE to create a JFrame with a JButton labeled
"Click Me"?
import javax.swing.*;
a. frame.add(button);
b. frame.insert(button);
c. frame.append(button);
d. frame.push(button);
Correct Answer:
a. frame.add(button);
Detailed Solution:
The add() method is used to add components like buttons, text fields, or panels to a JFrame.
QUESTION 6:
import javax.swing.*;
import java.awt.*;
a. panel.setLayout(new GridLayout());
b. panel.addFlowLayout();
c. panel.appendLayout(new FlowLayout());
d. panel.setLayout(new FlowLayout());
Correct Answer:
d. panel.setLayout(new FlowLayout());
Detailed Solution:
The setLayout() method is used to define the layout manager for a panel. FlowLayout is the
default layout for JPanel.
QUESTION 7:
import javax.swing.*;
c. Compilation Error.
d. Runtime Error.
Correct Answer:
Detailed Solution:
The JLabel has to be added to the frame using add(). The frame is visible, but the label is not
displayed as it has not been added.
QUESTION 8:
import javax.swing.*;
public NPTEL() {
button = new JButton("Programming in Java");
add(button);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
Correct Answer:
Detailed Solution:
The code extends JFrame and uses the JButton class object to create a button with the name of
“Programming in Java”.
QUESTION 9:
What happens when the button in this Java code snippet is clicked?
import javax.swing.*;
import java.awt.event.*;
a. The program exits
d. Nothing happens
Correct Answer:
Detailed Solution:
The code creates a button with label “Click Me” and in the frame titled “NPTEL Java Course”. A
action listener is defined that opens a new message dialog with the text “Welcome to the course”
when the button is clicked.
QUESTION 10:
The container displays a number of components in a column, with extra space going between the first
two components.
Which of the following layout manager(s) most naturally suited for the described layout?
a. BoxLayout
b. FlowLayout
c. BorderLayout
d. GridLayout
Correct Answer:
a. BoxLayout
Detailed Solution:
BoxLayout lays out components in either a column or a row. You can specify extra space using an
invisible component.
NOC25-CS57 (JAN-2025 25S)
QUESTION 1:
JLabel
JButton
JTextField
JPanel
Correct Answer:
JButton
Detailed Solution:
clicked.
Correct Answer:
Detailed Solution:
A toggle button allows users to switch between two states, such as "on" or "off." It behaves like a
checkbox, but it is represented as a button.
QUESTION 3:
Correct Answer:
Detailed Solution:
SQL is used in Java applications primarily to connect to databases, retrieve data, update records, and
perform other database operations, making it essential for handling data within applications.
QUESTION 4:
isActive()
isUp()
isRunning()
isConnected()
Correct Answer:
isUp()
Detailed Solution:
In Java, the isUp() method is used to check whether a network interface is up and running. This
method is part of the NetworkInterface class from the java.net package.
QUESTION 5:
Correct Answer:
Detailed Solution:
In Java, Socket and ServerSocket are the primary components used for establishing client-server
communication. These classes belong to the java.net package and are fundamental to networking
in Java. String, Integer, JFrame, JButton, Scanner, and System are not used for basic
networking functionality.
QUESTION 6:
https://nptel.ac.in
Correct Answer:
Detailed Solution:
Resource name is nptel.ac.in. The protocol used is https and hence provides a secure connection to the
website. The link is complete in all aspects and hence can open a website (if hosted). The ac.in portion of
the website is top-level domain part and not a path.
QUESTION 7:
TCP
UDP
ARP
SMTP
Correct Answer:
SMTP
Detailed Solution:
TCP, UDP are transport layer protocols. ARP is a Network - IP layer protocol. SMTP is Application layer
protocol.
QUESTION 8:
import java.sql.*;
a. Connects to a MySQL database, retrieves data from the "employees" table, and prints it
Correct Answer:
a. Connects to a MySQL database, retrieves data from the "employees" table, and prints it
Detailed Solution:
The code snippet establishes a connection to a MySQL database, executes a SELECT query to retrieve
data from the "employees" table, and prints the results.
QUESTION 9:
a. URLConnection
b. HttpURL
c. NetURL
d. URL
Correct Answer:
d. URL
Detailed Solution:
The URL class provides methods to work with Uniform Resource Locators.
QUESTION 10:
Socket
ServerSocket
DatagramSocket
HttpURLConnection
Correct Answer:
b. ServerSocket
Detailed Solution:
Correct Answer:
Detailed Solution:
JDBC stands for Java Database Connectivity, a Java API used to connect and interact with relational
databases. It provides methods to query and update data in a database.
QUESTION 2:
import java.sql.*;
// Establish Connection
Connection connection = // INSERT CODE HERE;
Correct Answer:
Detailed Solution:
QUESTION 3:
Identify the error in the following code and select the corrected statement:
import java.sql.*;
What is the correct statement to replace the line with error (stmt.execute("SELECT * FROM
users");)?
Correct Answer:
Detailed Solution:
The executeQuery method is used to execute SQL queries that return a ResultSet.
QUESTION 4:
What will the following Java program output if the database contains a table products with a column
name and three rows: Laptop, Phone, and Tablet?
import java.sql.*;
Compilation Error
Runtime Error
Laptop
Phone
Tablet
No Output
Correct Answer:
Laptop
Phone
Tablet
Detailed Solution:
The program fetches and displays all rows from the name column in the products table using a
ResultSet.
QUESTION 5:
Complete the following code to insert a new user into a users table.
import java.sql.*;
conn.createStatement(query);
conn.prepareStatement(query);
conn.execute(query);
conn.runStatement(query);
Correct Answer:
conn.prepareStatement(query);
Detailed Solution:
The prepareStatement method prepares the SQL query for execution, allowing the use of
parameterized inputs.
QUESTION 6:
Which of the following SQL operations can be executed using the executeUpdate method in JDBC?
Only I and II
Only I
Correct Answer:
Detailed Solution:
The executeUpdate method is used for SQL operations that modify data (INSERT, UPDATE,
DELETE). It cannot be used for SELECT queries, which return a ResultSet.
QUESTION 7:
Correct Answer:
The DriverManager class loads the JDBC drivers and establishes connections to databases.
QUESTION 8:
Correct Answer:
Detailed Solution:
Which method executes a simple query and returns a single Result Set object?
executeQuery()
executeUpdate()
execute()
run()
Correct Answer:
executeQuery()
Detailed Solution:
The executeQuery() method is used to execute a simple SQL query that returns a single ResultSet object.
QUESTION 10:
Which package in Java contains the classes and interfaces for JDBC?
java.sql
java.io
java.db
java.net
Correct Answer:
java.sql
Correct Answer:
java.sql package in Java contains the classes and interfaces for JDBC.