0% found this document useful (0 votes)
20 views131 pages

Programming in Java NPTEL 2025 (Previous Year Assignments)

The document contains multiple-choice questions (MCQs) related to Java programming, covering topics such as Java's execution model, object-oriented principles, and specific coding scenarios. Each question includes the correct answer and a detailed solution explaining the reasoning behind it. The content is structured as assignments from NPTEL Online Certification Courses by the Indian Institute of Technology Kharagpur.

Uploaded by

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

Programming in Java NPTEL 2025 (Previous Year Assignments)

The document contains multiple-choice questions (MCQs) related to Java programming, covering topics such as Java's execution model, object-oriented principles, and specific coding scenarios. Each question includes the correct answer and a detailed solution explaining the reasoning behind it. The content is structured as assignments from NPTEL Online Certification Courses by the Indian Institute of Technology Kharagpur.

Uploaded by

parthrai1905
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NPTEL Online Certification Courses

Indian Institute of Technology Kharagpur


NOC25-CS110 (July-2025 25A)

PROGRAMMING IN JAVA
Assignment 01
TYPE OF QUESTION: MCQ
Number of questions: 10 Total marks: 10 × 1 = 10

QUESTION 1:

Which of the following is true?

a. Java uses only interpreter.

b. Java uses only compiler.

c. Java uses both interpreter and compiler.

d. None of the above.

Correct Answer:

c. Java uses both interpreter and compiler.

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

A Java file with extension ‘.class’ contains

a. Java source code

b. HTML tags

c. Java Byte code

d. A program file written in Java programming language

Correct Answer:

c. Java Byte code

Detailed Solution:

A .class file is a compiled version of the .java file in byte code (it is a kind of object code with JVM (Java
Virtual Machine) as the target machine.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

Which of the following is not an object-oriented programming paradigm?

a. Encapsulation

b. Inheritance

c. Polymorphism

d. Dynamic memory allocation

Correct Answer:

d. Dynamic memory allocation

Detailed Solution:

Dynamic memory allocation is a memory allocation strategy and not a programming paradigm.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

What will be the output of the following Java code?

class increment {

public static void main(String args[]) {


int g = 3;
System.out.print(++g * 8);
}
}

a. 32

b. 33

c. 24

d. 25

Correct Answer:

a. 32

Detailed Solution:

Operator ++ has more preference than *, thus g becomes 4 and when multiplied by 8 gives 32.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

What is the correct sequence of steps to execute a Java program?

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.
Which of the following options represents this sequence?

a. Run → Edit → Compile

b. Edit → Run → Compile

c. Compile → Edit → Run

d. Edit → Compile → Run

Correct Answer:

d. Edit → Compile → Run

Detailed Solution:

The Java development process involves writing code (Edit), converting it to bytecode (Compile), and then
executing it on the JVM (Run).
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

Consider the following code.

class NPTEL {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

What is the output of the above code?

a. Hello, World!

b. HelloWorld!

c. Compilation Error

d. Runtime Error

Correct Answer:

a. Hello, World!

Detailed Solution:

Java program to print Hello, World!


NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

What is the primary focus of Java programming?

a. Low-level optimizations

b. Hardware-specific operations

c. Platform independence

d. Assembly language programming

Correct Answer:

c. Platform independence

Detailed Solution:

Java's primary feature is its ability to run on any platform without modification, thanks to the concept of
Write Once, Run Anywhere (WORA).
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

Which of the following programming principles is a key aspect of Java?

a. Code obfuscation

b. Platform dependence

c. Object-oriented programming

d. Global variables

Correct Answer:

c. Object-oriented programming

Detailed Solution:

Java is designed based on the principles of object-oriented programming, promoting concepts like
encapsulation, inheritance, and polymorphism.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

What is the primary purpose of the Java Virtual Machine (JVM) in the Java programming language?

a. Code optimization

b. Platform independence

c. Memory management

d. Hardware-specific operations

Correct Answer:

b. Platform independence

Detailed Solution:

The Java Virtual Machine (JVM) enables platform independence by interpreting Java bytecode, allowing
Java programs to run on any device with a compatible JVM.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

Consider the following program.

public class Question {


public static void main(String[] args) {
int x = 5;
x *= (2 + 8);
System.out.println(x);
}
}

What is the output of the above code?

a. 50

b. 10

c. Compiler error

d. 5

Correct Answer:

a. 50

Detailed Solution:

Here, x *= 2 + 8 is equivalent to x * (2+ 8) => x * 10. Therefore, x = 50.


NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur
NOC25-CS110 (July-2025 25A)

PROGRAMMING IN JAVA
Assignment 02
TYPE OF QUESTION: MCQ
Number of questions: 10 Total marks: 10 × 1 = 10

QUESTION 1:

Which of the following is the correct way to declare a class in Java?

public class MyClass {}

class MyClass[] {}

public MyClass class {}

MyClass public class {}

Correct Answer:

public class MyClass {}

Detailed Solution:

The correct way to declare a class in Java is by using the class keyword followed by the class name and
curly braces. Refer to Lecture 7 for more details.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

Consider the code given below.

public class VarPrint {


int x = 30;
static int y = 20;

public static void main(String[] args) {


VarPrint t1 = new VarPrint();
t1.x = 88;
t1.y = 99;
int z1 = t1.x + t1.y;
VarPrint t2 = new VarPrint();
System.out.println(t1.y + " " + t2.y + " " + z1);
}
}
What will be the output of the above Java program?

30 99 178

30 88 129

30 99 187

99 99 187

Correct Answer:

99 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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

Consider the code given below.

public class ArgumenTest {


public static void main(String[] args) {
Test t = new Test();
t.start();
}

static class Test {


void start() {
int a = 4;
int b = 5;
System.out.print("" + 8 + 3 + "");
System.out.print(a + b);
System.out.print(" " + a + b + "");
System.out.print(foo() + a + b + " ");
System.out.println(a + b + foo());
System.out.print(a + b);

String foo() {
return "foo";
}
}
}

What will be the output of the code given above?

9 7 7 foo34 34foo

839 45foo45 9foo

72 34 34 foo34 34foo

839 45foo45 9foo9

Correct Answer:

839 45foo45 9foo9

Detailed Solution:
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

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

that

self

current

this

Correct Answer:

this

Detailed Solution:

In Java, the this keyword is used to refer to the current object within an instance method or a
constructor. Refer to Lecture 8 for more details.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

Which of the following is true about constructors in a class?

Constructors do not have a return type.

Constructors aren’t used to initialize objects.

A class can have only one constructor.

Constructors cannot be overloaded.

Correct Answer:

Constructors do not have a return type.

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

Consider the following code snippet

class NPTEL_W2 {
int x;

NPTEL_W2(int x) {
this.x = x;
}

void printX() {
System.out.println(this.x);
}

public static void main(String[] args) {


NPTEL_W2 obj = new NPTEL_W2(100);
obj.printX();
}
}

What will be the output of the code given above?

10

100

Runtime error

Correct Answer:

100

Detailed Solution:

The constructor NPTEL_W2 (int x) initializes the instance variable x with the value passed as an
argument. The method printX() prints the value of x, which is 10. Refer to Lecture 7 for more
details.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

Consider the code snippet give below.


(\n in output is to be assumed to be the new line character)

public class Main {


public static void main(String[] args) {
System.out.print("Hello ");
System.out.println("World");
System.out.println("Number: %d", 10);
}
}

What will be the output of the code given above?

Hello World\nNumber: 10

Hello WorldNumber: 10

Hello \nWorld\nNumber: 10

Hello World\nNumber: 10\n

Correct Answer:

Hello World\nNumber: 10\n

Detailed Solution:

The print method prints text without a newline, println prints text with a newline, and printf
prints formatted text. The output is Hello World on the first line and Number: 10 on the second
line. Refer to Lecture 10 for more details.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

Which class is used in Java to take runtime data input from the user?

BufferReader

UserInputStreamReader

Scanner

DataInputStreamReader

Correct Answer:

Scanner

Detailed Solution:

The Scanner class is used to take runtime data input from the user. It provides methods to read various
types of input such as strings, integers, and floating-point numbers. Refer to Lecture 9 for more details.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

How do you read a line of text from the console using the Scanner class in Java?

scanner.readLine()

scanner.nextLine()

scanner.getLine()

scanner.fetchLine()

Correct Answer:

scanner.nextLine()

Detailed Solution:

The nextLine() method of the Scanner class reads a line of text from the console. Refer to Lecture 10 for
more details.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

What is the correct signature of the main method in Java?

public void main(String args[])

public static void main(String[] args)

void main(String[] args)

public static void main(String args[])

Correct Answer:

public static void main(String[] args)

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 to the book Joy with Java Chapter 3 for more detailed explanation.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur
NOC25-CS110 (July-2025 25A)

PROGRAMMING IN JAVA
Assignment 03
TYPE OF QUESTION: MCQ
Number of questions: 10 Total marks: 10 × 1 = 10

QUESTION 1:

In Java, what is the role of the public static void main(String[] args) method?

a. Initialization method

b. Execution entry point

c. Constructor

d. Destructor

Correct Answer:

b. Execution entry point

Detailed Solution:

The public static void main(String[] args) method is the entry point for the execution
of a Java program.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

Consider the following code.

class First {
static void staticMethod() {
System.out.println("Static Method");
}
}

class MainClass {
public static void main(String[] args) {
First first = null;
First.staticMethod();
}
}
What is the output of the above code?

a. Static Method

b. Throws a NullPointerException

c. Compile-time error

d. Run time error

Correct Answer:

a. Static Method

Detailed Solution:

The provided Java code will compile and execute successfully without any exceptions. When calling a
static method, it doesn't require an instance of the class. Therefore, you can call the static
method staticMethod() from class First using the null reference first.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

Consider the following code.

class access {
public int x;
private int y;

void cal(int a, int b) {


x = a + 1;
y = b;
}
void print() {
System.out.println(" " + y);
}
}
public class access_specifier {
public static void main(String args[]) {
access obj = new access();
obj.cal(2, 3);
System.out.print(obj.x);
obj.print();
}
}
What is the output of the above code?

a. 2 3

b. 3 3

c. Runtime Error

d. Compilation Error

Correct Answer:

b. 3 3

Detailed Solution:

The first 3 is printed by System.out.println(obj.x); because x was set to 3 (2 + 1) in the cal method.
The second 3 is printed by obj.print(); because y was set to 3 in the cal method.
Although y is a private variable, it is still accessible within the methods of the same class. Therefore, the
print method can access and print its value.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

Members which are not intended to be inherited are declared as

a. Public members

b. Protected members

c. Private members

d. Private or Protected members

Correct Answer:

c. Private members

Detailed Solution:

Private access specifier is the most secure access mode. It doesn’t allow members to be inherited. Even
Private inheritance can only inherit protected and public members.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

Which type of inheritance leads to diamond problem?

a. Single level

b. Multi-level

c. Multiple

d. Hierarchical

Correct Answer:

c. Multiple

Detailed Solution:

When 2 or more classes inherit the same class using multiple inheritance and then one more class
inherits those two base classes, we get a diamond like structure. Here, ambiguity arises when same
function gets derived into 2 base classes and finally to 3rd level class because same name functions are
being inherited.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

Consider the following code.

class superDemoClass {
final void func() {
int a = 20;
System.out.println("value of a = " + a);
}
}

class subDemoClass extends superDemoClass {


void func() {
int b = 60;
System.out.println("value of b = " + b);
}
}

class demo {
public static void main(String[] args) {
subDemoClass subc = new subDemoClass();
subc.func();
}
}
What is the output of the above code?

a. error: func() in subDemoClass cannot override func() in superDemoClass

b. value of b = 60

c. value of a = 20

d. None of the above

Correct Answer:

a. error: func() in subDemoClass cannot override func() in superDemoClass

Detailed Solution:

Here in this program, the subclass is trying to override the final method of the superclass, i.e. it is trying
to change the behavior of the final method. The behavior of the final method cannot be changed in the
subclass. In other words, the final method cannot be overridden in any subclass because the final
method is a complete method. Therefore, error: func() in subDemoClass cannot override func() in
superDemoClass
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

Consider the following code.

class StaticScopeDemo {
static int x = 5;

public static void main(String[] args) {


int x = 10;
{
int x = 15; // Compilation Error
System.out.println(x);
}
}
}
What is the output of the above code?

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
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

Consider the following code.

public class NptelExample {


public static int fun(int n) {
if (n == 0) {
return 1;
}
return n * fun(n - 1);
}

public static void main(String[] args) {


System.out.println(fun(5));
}
}
What is the output of the above code?

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

If a variable of primitive datatype in Java is declared as final, then

a. It cannot get inherited

b. Its value cannot be changed

c. It cannot be accessed in the subclass

d. All of the above

Correct Answer:

b. Its value cannot be changed

Detailed Solution:

A final variable of a primitive data type cannot change its value once it has been initialize.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

Consider the following code.

class static_out {
static int x;
static int y;

void add(int a, int b) {


x = a + b;
y = x + b;
}
}

public class static_use {


public static void main(String args[]) {
static_out obj1 = new static_out();
static_out obj2 = new static_out();
int a = 2;
obj1.add(a, a + 1);
obj2.add(5, a);
System.out.println(obj1.x + " " + obj2.y);
}
}
What is the output of the above code?

a. 7 7.4

b. 6 6.4

c. 7 9

d. 9 7

Correct Answer:

c. 7 9

Detailed Solution:
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

x and y are static variables, so they are shared across all instances of the class static_out.
When obj1.add(a, a + 1) is called, x and y are updated to 5 and 8, respectively.
When obj2.add(5, a) is called, x and y are updated to 7 and 9, respectively.
The final values of x and y after all method calls are 7 and 9, respectively, which are printed by
System.out.println(obj1.x + " " + obj2.y);.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur
NOC25-CS110 (July-2025 25A)

PROGRAMMING IN JAVA
Assignment 4
TYPE OF QUESTION: MCQ
Number of questions: 10 Total marks: 10 × 1 = 10

QUESTION 1:

Which of these access specifiers must be used for main() method?

a. private

b. public

c. protected

d. default

Correct Answer:

b. public

Detailed Solution:

main() method must be specified public as it called by Java run time system, outside of the
program. If no access specifier is used then by default member is public within its own package &
cannot be accessed by Java run time system.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

Consider the program given below.

public class Main{


public static void main(String args[]){
System.out.println(cos(2*PI));
}
}

What will be the output if the program is executed?

a. It will give compile-time error

b. It will give run-time error

c. 1.0

d. 3.14

Correct Answer:

b. It will give compile-time error

Detailed Solution:

The program gives a compile time error as the Math class is missing.
The static import statement needs to be used to import the static members (e.g., PI) of java.lang.Math.

import static java.lang.Math.*;

This will allow the program to use PI directly.


NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

Consider the following code:

class Person {
int a = 1;
int b = 0;
public Person() {
System.out.println(a * b + " Java " );
}
}

class Employee extends Person {


int a = 0;
int b = 1;
public Employee() {
System.out.println(a + b + " Java " );
}
}

public class Question {


public static void main(String args[]) {
Person p = new Employee();
}
}

What will be the output of the code given above?

a. 1 Java 10
0 Java 0

b. 1 Java
0 Java

c. 10 Java
0 Java

d. 0 Java
1 Java

Correct Answer:

d. 0 Java
1 Java

Detailed Solution:
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

In Java, can a subclass in a different package access a superclass’s protected method?

a. Yes, without any restrictions.

b. Yes, but only if they are in the same package.

c. No, protected methods are not accessible by subclasses.

d. Yes, but only through inheritance (i.e., using super or this, not via an object)

Correct Answer:

d. Yes, but only through inheritance (i.e., using super or this, not via an object)

Detailed Solution:

- A subclass in a different package can access protected members only through inheritance (directly via
super or this).

- It cannot access the superclass’s protected method via an instance of the superclass.

- Protected also allows access to classes in the same package without subclassing, but that’s not the
case here.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

A package is a collection of:

a. Only classes

b. Only interfaces

c. editing tools

d. classes,methods and interfaces

Correct Answer:

d. Classes,methods and interfaces

Detailed Solution:

In Java (and many other object-oriented languages), a package is a namespace that organizes a set of
related classes, interfaces, and methods.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

Consider the following 2 programs:

// Main1.java ------------------
public class Main1{
public static void main(String args[]){
int number = 10;
System.out.println(number++ + ++number);
}
}

// Main2.java ------------------
public class Main2{
public static void main(String args[]){
int number = 10;
System.out.println(++number + number++);
}
}

Choose the best option among the following for the code snippet given above

a. Both pre-increment and post-increment operators becomes pre-increment during print.

b. Both pre-increment and post-increment operators becomes post-increment during print.

c. Both Main1 and Main2 classes give the same output.

d. Pre-increment and post-increment operators don’t work during print.

Correct Answer:

c. Both Main1 and Main2 classes give the same output.

Detailed Solution:

The output of both the program are 22. Therefore, option c is correct and we can eliminate option d that
the operators don’t work. Further, the operators are doing exactly what they are supposed to do i.e. pre-
increment first increases the values and post-increment increases the value during the next operation.
The print statement is the next operation; hence it received the post incremented value as well making
option a and b invalid.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

Consider the following program:

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:

This code has one error:


1. Incorrect visibility of `main` method:
The `main` method is defined as `private static void main(String[] args)`. The
`main` method must be `public static void main(String[] args)` to be recognized as
the entry point of the program by the Java Virtual Machine (JVM).
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

Consider the code given below.

// Teacher.java ------------------
package nptel1;
public class Teacher {
protected void showMarks() {
System.out.println("100 Marks");
}
}

// Student.java ------------------
package nptel2;
import nptel1.*;
public class Student extends Teacher {
void show() {
showMarks();
}
public static void main(String[] args) {
Student st1 = new Student();
st1.show();
}
}

What is the output of the above Java Code Snippet with protected access modifier?

a. 100 marks

b. No output

c. Compiler error

d. None of the above

Correct Answer:

a. 100 marks

Detailed Solution:

Through inheritance, one can access a protected variable or method of a class even from outside the
package. Here, we accessed Teacher class of nptel1 from Student class of nptel2.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

Choose the correct syntax of a Java Package below.

a. package PACKAGE_NAME;

b. package PACKAGE_NAME.*;

c. pkg PACKAGE_NAME;

d. pkg PACKAGE_NAME.*;

Correct Answer:

a. package PACKAGE_NAME;

Detailed Solution:

A package declaration statement should end with a package name but not with *.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

What is the process by which we can control what parts of a program can access the members of a
class?

a. Polymorphism

b. Augmentation

c. Encapsulation

d. Recursion

Correct Answer:

c. Encapsulation

Detailed Solution:

Encapsulation in Java is the process by which data (variables) and the code that acts upon them
(methods) are integrated as a single unit. By encapsulating a class's variables, other classes cannot
access them, and only the methods of the class can access them.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur
NOC25-CS110 (July-2025 25A)

PROGRAMMING IN JAVA
Assignment 05
TYPE OF QUESTION: MCQ
Number of questions: 10 Total marks: 10 × 1 = 10

QUESTION 1:

Which of the following statement(s) is/are true about finally in Java?

I. The finally block is executed regardless of whether an exception is thrown or not.


II. A finally block can exist without a catch block.
III. The finally block will not execute if System.exit() is called in the try block.
IV. A finally block can have a return statement, but it is not recommended to use.

a. I and II

b. II and III

c. I, II and III

d. I, II, III and IV

Correct Answer:

d. I, II, III and IV

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

Consider the following code.

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();
}
}
What will be the output of the above code?

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

Consider the following code.

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");
}
}
}
What will be the output of the above code?

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”.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

Which of the following is TRUE regarding abstract class and an interface in Java?

I. Abstract classes can contain constructors, but interfaces cannot.


II. Interfaces support multiple inheritance, but abstract classes do not.
III. Abstract classes can have both abstract and concrete methods, whereas interfaces only had
abstract methods before Java 8.

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

Which of the following is a checked exception in Java?

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

Consider the following code.

interface Demo {
void display();
}

class Test implements Demo {


public void display() {
System.out.println("Hello, NPTEL!");
}
}

public class Main {


public static void main(String[] args) {
Test obj = new Test();
obj.display();
}
}
What will be the output of the above code?

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!”.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

Consider the following code.

interface Calculator {
void calculate(int value);
}

class Square implements Calculator {


int result;
public void calculate(int value) {
result = value * value;
System.out.print("Square: " + result + " ");
}
}

class Cube extends Square {


public void calculate(int value) {
result = value * value * value;
super.calculate(value);
System.out.print("Cube: " + result + " ");
}
}

public class Main {


public static void main(String[] args) {
Calculator obj = new Cube();
obj.calculate(3);
}
}
What will be the output of the above code?

a. Square: 9 Cube: 9

b. Cube: 27 Square: 9

c. Square: 9 Square: 27 Cube: 27

d. Square: 9 Cube: 27 Square: 27

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
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

class. First, "Square: 9" is printed by the superclass method. Then, the overridden method in Cube prints
"Cube: 9".
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

Which keyword is NOT used by Java during exception handling?

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

A method that potentially generates a checked exception must include this keyword in its method
signature:

a. throw

b. extend

c. throws

d. extends

Correct Answer:

c. throws

Detailed Solution:

Any Java class that generates a checked exception and does not handle it internally must use the throws
keyword to alert other methods of its instability.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

Consider the following code.

class Test extends Exception {}

class Main {

public static void main(String args[]) {


try {
throw new Test();
} catch (Test t) {
System.out.println("Got the Test Exception");
} finally {
System.out.println("Inside finally block ");
}
}
}

What will be the output of the above code?

a. Got the Test Exception


Inside finally block

b. Got the Test Exception

c. Inside finally block

d. Compiler Error

Correct Answer:

a. Got the Test Exception


Inside finally block

Detailed Solution:

In Java, the finally is always executed after the try-catch block. This block can be used to do the common
cleanup work.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur
NOC25-CS110 (JAN-2025 25A)

PROGRAMMING IN JAVA
Assignment 06
TYPE OF QUESTION: MCQ
Number of questions: 10 Total marks: 10 × 1 = 10

QUESTION 1:

Which of the following method returns a reference to the currently executing thread object?

a. public static boolean interrupted();

b. public static Thread currentThread();

c. public final boolean isAlive();

d. public final void suspend();

Correct Answer:

b. public static Thread currentThread();

Detailed Solution:

Only public static Thread currentThread() method returns a reference to the currently
executing thread object among the options.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

Which of the following best describes the concept of multithreading in Java?

a. Multiple threads execute concurrently, sharing the same memory space.

b. Only one thread executes at a time, ensuring sequential execution.

c. Threads in Java cannot communicate with each other.

d. Threads require separate memory allocation for each thread to run.

Correct Answer:

a. Multiple threads execute concurrently, sharing the same memory space.

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

Consider the code given below:

class ExampleThread extends Thread {


public void run() {
System.out.println("Thread is running.");
}
}

public class Main {


public static void main(String[] args) {
ExampleThread thread = new ExampleThread();
thread.start();
//thread.start();
}
}
What will happen when the above code is executed?

a. The program will execute successfully, printing "Thread is running." twice.

b. The program will throw an error when attempting to start the thread a second time.

c. The program will terminate without any output.

d. The program will execute successfully, printing "Thread is running."

Correct Answer:

d. The program will execute successfully, printing "Thread is running."

Detailed Solution:

 The second thread.start(); is commented out, so it's not executed.


 Only one thread is started, and the run() method prints:

Thread is running.
For more details about the thread lifecycle,please refer to the relavant chapter in the book Joy with
Java.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

Which method is used to start a thread in Java?

a. run()

b. start()

c. execute()

d. begin()

Correct Answer:

b. start()

Detailed Solution:

The start() method begins a new thread and calls the run() method in a separate call stack.

For more details, refer to the book "Joy with Java" — it's great for beginners!
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

Cosnider the code given below:

class RunnableExample implements Runnable {


public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println("Thread running: " + i);
}
}
}

public class Main {


public static void main(String[] args) {
RunnableExample task = new RunnableExample();
Thread thread = new Thread(task);
thread.start();
}
}
What will happen when the above code is executed?

a. The program will throw a compile-time error because Runnable is not a thread.

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

Which of the following states can a thread enter during its lifecycle in Java?

a. New, Runnable, Running, Blocked

b. New, Runnable, Waiting, Blocked

c. New, Runnable, Running, Sleeping, Dead

d. New, Runnable, Waiting, Blocked, Terminated

Correct Answer:

d. New, Runnable, Waiting, Blocked, Terminated

Detailed Solution:

The states of a thread in Java are:


 New: Thread is created but not started.
 Runnable: Thread is ready to run but waiting for CPU time.
 Waiting/Blocked: Thread is paused or waiting for some resource.
 Terminated: Thread has completed execution.

Additional note:
In Java thread lifecycle, Waiting and Blocked are two distinct states:
 Blocked means the thread is waiting to enter a synchronized block/method because another
thread holds the lock.
 Waiting means the thread is waiting indefinitely for another thread to notify it (e.g., via
wait()/notify()).
 This distinction helps in understanding thread coordination better. For more details, check Joy
with Java
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

What does the thread scheduler use to decide which thread to run when multiple threads are in the
runnable state?

a. Thread priority

b. Thread's execution time

c. Thread name

d. Thread creation order

Correct Answer:

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

Consider the code given below:

class PriorityExample extends Thread {


public void run() {
System.out.println(Thread.currentThread().getName() +
" with priority " +
Thread.currentThread().getPriority());
}
}

public class Main {


public static void main(String[] args) {
PriorityExample t1 = new PriorityExample();
PriorityExample t2 = new PriorityExample();

t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);

t1.start();
t2.start();
}
}
Which of the following is true about the output?

a. The thread with the higher priority is guaranteed to execute first.

b. The thread with the lower priority will never execute.

c. The order of execution depends on the JVM and OS scheduling policies.

d. The program will throw an error due to invalid priority values.

Correct Answer:

c. The order of execution depends on the JVM and OS scheduling policies.

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

What is the primary purpose of thread synchronization in Java?

a. To allow multiple threads to execute a method at the same time

b. To ensure thread execution follows a specific order

c. To prevent rare conditions and ensure data in-consistency

d. To prevent race conditions and ensure data consistency

Correct Answer:

d. To prevent race conditions and ensure data consistency

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

What is the primary difference between Byte Streams and Character Streams in Java?

a. Byte Streams handle characters, while Character Streams handle bytes.

b. Byte Streams are used for binary data, while Character Streams are used for decimal data.

c. Character Streams are faster than Byte Streams in all cases.

d. Byte Streams are used for binary data, while Character Streams are used for text data

Correct Answer:

d. 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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur
NOC25-CS110 (July-2025 25A)

PROGRAMMING IN JAVA
Assignment - 07
TYPE OF QUESTION: MCQ
Number of questions: 10 Total marks: 10 × 1 = 10

QUESTION 1:

Consider the following code.

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();
}
}
Assume NPTEL.txt contains:

This is Programming in Java online course.

What will be the output if the program is executed?

a. Hello, World!

b. This is Programming in Java online course.

c. IOException

d. null

Correct Answer:

b. This is Programming in Java online course.

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

Consider the following code.

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();
}
}
What will be the output of the above code?

a. 0

b. Runtime Error

c. Compilation Error

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

Consider the following partially written code.

File file = new File("file.txt");


if (__________________) // Fill in the blanks
{
System.out.println("File exists.");
} else
{
System.out.println("File does not exist.");
}

Complete the code snippet with the appropriate code. Select your answer from the following choices.

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

Consider the following code.

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);
}
}
}
What will be the output of the above code?

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

Consider the following code.

class Main {

public static void main(String args[]) {


final int i;
i = 20;
i = 30;
System.out.println(i);
}
}
What will be the output of the above code?

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”.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

Which of these exception is thrown in cases when the file specified for writing is not found?

a. IOException

b. FileException

c. FileNotFoundException

d. FileInputException

Correct Answer:

c. FileNotFoundException

Detailed Solution:

In cases when the file specified is not found, then FileNotFoundException is thrown by java run-time
system, earlier versions of java used to throw IOException but after Java 2.0 they throw
FileNotFoundException.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

Consider the following code.

public class Calculator {


int num = 100;

public void calc(int num) {


this.num = num * 10;
}

public void printNum() {


System.out.println(num);
}

public static void main(String[] args) {


Calculator obj = new Calculator();
obj.calc(2);
obj.printNum();
}
}

What will be the output of the above code?

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

Consider the following code.

import java.io.*;

public class W7 {
public static void main(String[] args) {
try {

PrintWriter writer = new PrintWriter(System.out);

writer.write(9 + 97);

writer.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

What will be the output of the above code?

a. It will give compile-time error

b. It will give run-time error

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'.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

Consider the following code.

file.txt contain "This is Programming in Java online course." (without quotes)

import java.io.File;

class FileSizeEample {
public static void main(String[] args) {
// Specify the file path
String filePath = "file.txt";

// Create a File object


File file = new File(filePath);

// Get the size of the file


long fileSize = file.length();

// Print the size of the file


System.out.println(fileSize);
}
}

What will be the output of the above code?

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

Consider the following code.

import java.io.*;

class Chararrayinput {

public static void main(String[] args) {


String obj = "abcdefgh";
int length = obj.length();
char c[] = new char[length];
obj.getChars(0, length, c, 0);
CharArrayReader input1 = new CharArrayReader(c);
CharArrayReader input2 = new CharArrayReader(c, 1, 4);
int i, j;
try {
while ((i = input1.read()) == (j = input2.read())) {
System.out.print((char) i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
What will be the output of the above code?

a. abc

b. abcd

c. abcde

d. None of the mentioned

Correct Answer:

d. None of the mentioned

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
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

character of each object is compared since they are unequal control comes out of loop and nothing is
printed on the screen.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur
NOC25-CS110 (July-2025 )

PROGRAMMING IN JAVA
Assignment 08
TYPE OF QUESTION: MCQ
Number of questions: 10 Total marks: 10 × 1 = 10

QUESTION 1:

Which layout manager organizes components in a grid, with each cell of the grid containing a
component?

Flow Layout

Card Layout

Border Layout

Grid Layout

Correct Answer:

Grid Layout

Detailed Solution:

Grid Layout organizes components in a grid, and each cell of the grid contains a component.
Components are added in a left-to-right, top-to-bottom order.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

Which AWT component is used to display a simple text label?

Button

Label

TextField

Checkbox

Correct Answer:

Label

Detailed Solution:

The Label class in AWT is used to display a simple, non-editable text string on the screen.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

Which method is used to set the title of a Frame in Java?

setTitle()

setName()

setText()

setLabel()

Correct Answer:

setTitle()

Detailed Solution:

The setTitle() method is used to set the title text that appears on the title bar of a Frame.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

Which AWT component is used to take input from the user in a single line?

Label

TextField

Button

Checkbox

Correct Answer:

TextField

Detailed Solution:

The TextField class creates a single-line box where the user can type text input.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

Consider the code given below:

import java.awt.*;
import java.awt.event.*;

public class ButtonExample extends Frame {


public static void main(String[] args) {
ButtonExample frame = new ButtonExample();
Button b = new Button("Programming in Java - 2025");
b.setBounds(30, 50, 180, 30);
frame.add(b);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}

What will be the output of the code given above?

Compilation error

An empty frame with no button

A frame with a button "Programming in Java - 2025" at coordinates (30, 50)

A frame with a button, but not at the specified coordinates

Correct Answer:

A frame with a button "Programming in Java - 2025" at coordinates (30, 50)

Detailed Solution:

- The program creates a frame and adds a button with the label "Programming in Java - 2025".
- Since setLayout(null) is used, absolute positioning is applied, so the button will appear exactly at
coordinates (30, 50) with a width of 180 and a height of 30.
- The frame title will appear blank because setTitle() was never called, but this does not affect the
button’s placement or visibility.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

Which layout manager arranges components in a left-to-right, top-to-bottom flow, adding them to the
next available position?

Grid Layout

Flow Layout

Border Layout

Card Layout

Correct Answer:

Flow Layout

Detailed Solution:

Flow Layout arranges components in a left-to-right flow, top-to-bottom, adding them to the next
available position in the container.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

What is the significance of AWT components being heavyweight?

They have higher memory requirements

They are slower in performance

They are dependent on the underlying operating system

They are easier to customize

Correct Answer:

They are dependent on the underlying operating system

Detailed Solution:

AWT components being heavyweight means they rely on the native components of the underlying
operating system, which can affect their appearance and behavior.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

Which AWT concept allows you to handle events such as button clicks or mouse movements?

Event Handling

Function Overloading

Mouse Manager

GUI Processing

Correct Answer:

Event Handling

Detailed Solution:

Event Handling in AWT enables the response to user actions, such as button clicks or mouse movements,
in a graphical user interface.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

What does AWT stand for in Java?

Apple Windowing Toolkit

Abstract Window Tool

Absolute Windowing Toolkit

Abstract Window Toolkit

Correct Answer:

Abstract Window Toolkit

Detailed Solution:

The Abstract Window Toolkit (AWT) is Java's original platform-dependent windowing, graphics, and user-
interface widget toolkit, preceding Swing.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

Consider the code given below:

import java.awt.*;

public class LayoutExample extends Frame {


public static void main(String[] args) {
LayoutExample frame = new LayoutExample();
Button b1 = new Button("Button 1");
Button b2 = new Button("Button 2");
Button b3 = new Button("Button 3");
frame.add(b1);
frame.add(b2);
frame.add(b3);
// create a flow layout
frame.setLayout(new FlowLayout());
frame.setLayout(new GridLayout(2, 2));
frame.setSize(300, 200);
frame.setVisible(true);
}
}

What is the layout manager used in the Java code given below?

Grid Layout

Border Layout

Flow Layout

Card Layout

Correct Answer:

Grid Layout

Detailed Solution:

The code sets the layout manager of the frame to a 2x2 grid layout using frame.setLayout(new
GridLayout(2, 2)). The FlowLayout gets overridden by the GridLayout, you can try to comment
out the GridLayout line to see the difference.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur
NOC25-CS110 (July-2025 25A)

PROGRAMMING IN JAVA
Assignment 09
TYPE OF QUESTION: MCQ
Number of questions: 10 Total marks: 10 × 1 = 10

QUESTION 1:

Which method is used to remove a component from a container in AWT?

a. remove()

b. deleteComponent()

c. removeComponent()

d. destroy()

Correct Answer:

a. remove()

Detailed Solution:

The remove() method is used to remove a component from a container in AWT. It takes a Component
object as an argument and removes it from the container.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

Consider the following code.

import javax.swing.*;

public class Nptel {


public static void main(String[] args) {
JFrame frame = new JFrame("My Frame");
frame.add(new JButton("OK"));
frame.add(new JButton("Cancel"));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
}

What will be the output of the above code?

a. Both “OK” and “Cancel” button is added, but only “Cancel” button is visble.

b. Only “OK” button is added and visible, “Cancel” button is not added.

c. Only “Cancel” button will be added and visible, “OK” button is not added.

d. Code throws an ERROR.

Correct Answer:

a. Both “OK” and “Cancel” button is added, but only “Cancel” button is visble.

Detailed Solution:

By default, the layout of the content pane in a JFrame is BorderLayout. Button OK is placed in the center
of content pane, then button Cancel is placed in the same place. So you only can see button Cancel.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

Consider the following code.

import javax.swing.*;
import java.awt.*;

public class SwingExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Example");
frame.setLayout(new FlowLayout());
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
What will be the output of the above code?

a. A frame with two buttons labeled “Button 1” and “Button 2”.

b. A frame with only one button labeled “Button 2”.

c. Compilation Error.

d. Runtime Error.

Correct Answer:

a. A frame with two buttons labeled “Button 1” and “Button 2”.

Detailed Solution:

The FlowLayout layout manager arranges components in a row. Here, both buttons are added and
displayed in the frame.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

Consider the following code.

import javax.swing.*;

public class FrameExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Demo Frame");
JButton button = new JButton("Click Me");
// INSERT CODE HERE
frame.setSize(300, 200);
frame.setVisible(true);
}
}
What should replace // INSERT CODE HERE to create a JFrame with a JButton labeled
"Click Me"?

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

Identify and correct the error in the following program:

import javax.swing.*;
import java.awt.*;

public class PanelExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Panel Example");
JPanel panel = new JPanel();
JButton button = new JButton("Submit");
panel.setFlowLayout(); // ERROR
panel.add(button);
frame.add(panel);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
What should the erroneous line (panel.setFlowLayout();) be replaced with?

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

Consider the following code.

import javax.swing.*;

public class LabelExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Label Demo");
JLabel label = new JLabel("Welcome to Swing");
frame.setSize(250, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
What will be the output of the above code?

a. A frame with the label "Welcome to Swing".

b. A frame with no visible label.

c. Compilation Error.

d. Runtime Error.

Correct Answer:

b. A frame with no visible label.

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

Consider the following code.

import javax.swing.*;

public class NPTEL extends JFrame {


JButton button;

public NPTEL() {
button = new JButton("Programming in Java");
add(button);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[] args) {


new NPTEL();
}
}

What will be the output of the above code?

a. Creates a JFrame with a JButton labeled "Programming in Java"

b. Compiles with errors

c. Displays a message dialog

d. Creates a JPanel with a JButton labeled "Programming in Java"

Correct Answer:

a. Creates a JFrame with a JButton labeled "Programming in Java"

Detailed Solution:
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

The code extends JFrame and uses the JButton class object to create a button with the name of
“Programming in Java”.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

Consider the following code.

import javax.swing.*;
import java.awt.event.*;
public class NPTEL {
public static void main(String[] args) {
JFrame frame = new JFrame("NPTEL Java Course");
JButton button = new JButton("Click Me");
button.setBounds(50, 100, 100, 40);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Welcome to the course");
}
});
frame.add(button);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}

What happens when the button in this Java code snippet is clicked?

a. The program exits

b. A message dialog with the text "Welcome to the course" is displayed

c. The button label changes to "Welcome to the course"

d. Nothing happens

Correct Answer:

b. A message dialog with the text "Welcome to the course" is displayed

Detailed Solution:
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

The container displays a number of components in a row, but adjusts according to the window size.

Which of the following layout manager(s) most naturally suited for the layout given below?

a. FlowLayout

b. BorderLayout

c. GridLayout

d. BoxLayout

Correct Answer:

a. FlowLayout

Detailed Solution:

FlowLayout arranges components left-to-right, wrapping to the next row as needed.


NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

In Java, what is the primary purpose of a layout manager?

a. To manage memory allocation

b. To arrange GUI components within a container

c. To handle exception handling

d. To control database connections

Correct Answer:

b. To arrange GUI components within a container

Detailed Solution:

A layout manager in Java is responsible for arranging and positioning GUI components within a container.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur
NOC25-CS110 (July-2025 25A)

PROGRAMMING IN JAVA
Assignment 10
TYPE OF QUESTION: MCQ
Number of questions: 10 Total marks: 10 × 1 = 10

QUESTION 1:

Which class provides methods to work with URLs?

a. URLConnection

b. HttpURL

c. URL

d. URLs

Correct Answer:

c. URL

Detailed Solution:

The URL class provides methods to work with Uniform Resource Locators.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

Consider the code given below:

import javax.swing.*;

public class NPTEL extends JFrame {


JButton button;

public NPTEL() {
button = new JButton("Programming in Java");
add(button);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[] args) {


new NPTEL();
}
}

What will be the output of the code given above?

a. Creates a JFrame with a JButton labeled "Programming in Java"

b. Compiles with errors

c. Displays a message dialog

d. Creates a JPanel with a JButton labeled "Programming in Java"

Correct Answer:

a. Creates a JFrame with a JButton labeled "Programming in Java"

Detailed Solution:
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

The code extends JFrame and uses the JButton class object to create a button with the name of
“Programming in Java”.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

Consider the code given below.

import javax.swing.*;
import java.awt.event.*;
public class NPTEL {
public static void main(String[] args) {
JFrame frame = new JFrame("NPTEL Java Course");
JButton button = new JButton("Click Me");
button.setBounds(50, 100, 100, 40);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Welcome to the course");
}
});
frame.add(button);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}

What will be the output of the code given above?

a. The program exits

b. A message dialog with the text "Welcome to the course" is displayed

c. The button label changes to "Welcome to the course"

d. Nothing happens

Correct Answer:

b. A message dialog with the text "Welcome to the course" is displayed

Detailed Solution:
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

What does JDBC stand for?

a. Java Data Base Connectivity

b. Java Development Base Connection

c. Java Distributed Binary Code

d. Java Data Binding Channel

Correct Answer:

a. Java Data Base Connectivity

Detailed Solution:

JDBC is an API that allows Java programs to interact with databases using SQL queries. It’s the standard
way to connect to databases like MySQL, Oracle, etc.
Refer JDBC setup and SQL execution in Joy with Java.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

Consider the code given below:

import javax.swing.*;
public class NPTEL {
public static void main(String[] args) {
JFrame frame = new JFrame("NPTEL Java Course");
String[] colors = {"Red", "Green", "Blue"};
JComboBox<String> comboBox = new JComboBox<>(colors);
comboBox.setBounds(50, 50, 90, 20);
frame.add(comboBox);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}

What will be the output of the code given above?

a. A frame with a list of colors displayed as buttons

b. A frame with a combo box containing options "Red", "Green", and "Blue"

c. A frame with radio buttons for selecting colors

d. A frame with checkboxes for selecting colors

Correct Answer:

b. A frame with a combo box containing options "Red", "Green", and "Blue"

Detailed Solution:

The code snippet creates a JComboBox with the options "Red", "Green", and "Blue", and adds it to a
JFrame.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

Cosider the code given below.

import java.net.*;

public class NPTEL {


public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("nptel.ac.in");
System.out.println("Host Name: " + address.getHostName());
System.out.println("IP Address: "+ address.getHostAddress());
} catch (Exception e) {
System.out.println(e);
}
}
}

What does this above Java code snippet do?

a. Just prints the IP address of the local machine

b. Prints the IP address and host name of the local machine

c. Prints the IP address and host name of "nptel.ac.in"

d. Just prints the IP address of "nptel.ac.in"

Correct Answer:

c. Prints the IP address and host name of "nptel.ac.in"

Detailed Solution:

The code snippet retrieves and prints the IP address and host name of the specified domain
"nptel.ac.in".
Output:

Host Name: nptel.ac.in


IP Address: 216.239.34.21
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

Consider the following code.

import java.sql.*;

public class NPTEL {


public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydatabase",
"username", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
while (rs.next()) {
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

What does the above code snippet do?

a. Connects to a MySQL database, retrieves data from the "employees" table, and prints it

b. Inserts data into the "employees" table of a MySQL database

c. Deletes data from the "employees" table of a MySQL database

d. Updates data in the "employees" table of a MySQL database

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

Consider the code given below:

import java.sql.*;
public class NPTEL {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydatabase",
"username", "password");
String query="INSERT INTO employees (name,age)VALUES(?, ?)";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, "John");
pstmt.setInt(2, 30);
int rowsAffected = pstmt.executeUpdate();
System.out.println(rowsAffected + " row(s) inserted.");
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

What will be the code given above do?

a. Retrieves data from the "employees" table

b. Inserts a new employee record into the "employees" table

c. Updates employee records in the "employees" table

d. Deletes employee records from the "employees" table

Correct Answer:

b. Inserts a new employee record into the "employees" table

Detailed Solution:

The code snippet inserts a new employee record with name "John" and age 30 into the "employees"
table of a MySQL database using a PreparedStatement.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

Which of the following option is TRUE regarding the below statement?

Connection con = DriverManager.getConnection


("jdbc:mysql://localhost:3306/nptel","nptel","java");

a. 3307 is the MySQL port

b. Database name is ‘JAVA’

c. The database server is hosted on IP 192.168.0.1

d. Password for ‘nptel’ user is ‘java’

Correct Answer:

d. Password for ‘nptel’ user is ‘java’

Detailed Solution:

User is nptel and password is java


NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

Which package in Java contains the classes and interfaces for JDBC?

a. java.sql

b. java.io

c. java.db

d. java.net

Correct Answer:

a. java.sql

Correct Answer:
java.sql package in Java contains the classes and interfaces for JDBC..
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur
NOC25-CS57 (JAN-2025 25S)

PROGRAMMING IN JAVA
Assignment 11
TYPE OF QUESTION: MCQ
Number of questions: 10 Total marks: 10 × 1 = 10

QUESTION 1:

What is the full form of JDBC?

Java Database Connectivity

Java Data Code

Java Data Communication

Java Development Connectivity

Correct Answer:

Java Database Connectivity

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

Fill in the missing code to establish a connection to a MySQL database.

import java.sql.*;

public class JDBCExample {


public static void main(String[] args) {
try {
// Load JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish Connection
Connection connection = // INSERT CODE HERE;

System.out.println("Connected to the database.");


connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
What should replace // INSERT CODE HERE ?

DriverManager.connect("mysql:localhost:mydb", "user", "password");

DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");

Connection.get("jdbc:mysql://localhost:3306/mydb", "user", "password");

Driver.connect("jdbc:mysql://localhost:mydb", "user", "password");

Correct Answer:

DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");

Detailed Solution:

The DriverManager.getConnection method establishes a connection to the specified database URL


with the provided username and password.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

Identify the error in the following code and select the corrected statement:

import java.sql.*;

public class ResultSetExample {


public static void main(String[] args) throws SQLException {
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",
"user", "password");
Statement stmt = connection.createStatement();
ResultSet rs = stmt.execute("SELECT * FROM users"); // Error
while (rs.next()) {
System.out.println(rs.getString("username"));
}
connection.close();
}
}
What is the correct statement to replace the line with error (stmt.execute("SELECT * FROM
users");)?

ResultSet rs = stmt.executeQuery("SELECT * FROM users");

ResultSet rs = stmt.runQuery("SELECT * FROM users");

ResultSet rs = stmt.execute("users SELECT * FROM");

ResultSet rs = stmt.fetch("SELECT * FROM users");

Correct Answer:

ResultSet rs = stmt.executeQuery("SELECT * FROM users");

Detailed Solution:

The executeQuery method is used to execute SQL queries that return a ResultSet.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

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.*;

public class DisplayProducts {


public static void main(String[] args) {
try {
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/store", "root",
"pass");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT name FROM products");
while (rs.next()) {
System.out.println(rs.getString("name"));
}
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

Complete the following code to insert a new user into a users table.

import java.sql.*;

public class InsertUser {


public static void main(String[] args) {
try {
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root",
"password");
String query = "INSERT INTO users (username, email) VALUES
(?, ?)";
PreparedStatement pstmt = // INSERT CODE HERE;
pstmt.setString(1, "john_doe");
pstmt.setString(2, "[email protected]");
pstmt.executeUpdate();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

What should replace // INSERT CODE HERE ?

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

Which of the following SQL operations can be executed using the executeUpdate method in JDBC?

I. INSERT INTO users (id, name) VALUES (1, 'Alice');


II. UPDATE users SET name='Bob' WHERE id=1;
III. DELETE FROM users WHERE id=1;
IV. SELECT * FROM users;

I, II, and III

Only I and II

Only I

I, II, III and IV

Correct Answer:

I, II, and III

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

What is the purpose of the DriverManager class in JDBC?

To manage database connections.

To execute SQL queries.

To fetch data from a database.

To represent a database record.

Correct Answer:

To manage database connections.

Detailed Solution:

The DriverManager class loads the JDBC drivers and establishes connections to databases.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

How do you establish a connection to a database using JDBC?

By creating an instance of the Connection interface

By using the DriverManager.getConnection() method

By implementing the Connection interface

By extending the Connection class

Correct Answer:

By using the DriverManager.getConnection() method

Detailed Solution:

To establish a connection to a database using JDBC, you use the DriverManager.getConnection() method.
This method takes a JDBC URL, username, and password as parameters and returns a Connection object,
which represents a connection to the database. The JDBC URL specifies the database type, location, and
other connection details.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur
NOC24-CS105 (July-2024 24A)

PROGRAMMING IN JAVA
Assignment 12
TYPE OF QUESTION: MCQ
Number of questions: 10 Total marks: 10 × 1 = 10

QUESTION 1:

Execution of the following SQL command

SELECT * FROM myTable;

Using JDBC program will return a ResultSet object. This object is:

a. Same as the myTable.

b. All records in verbatim from the table but those records with null values.

c. All records in verbatim from the table.

d. All records in verbatim from the table but those records are not with null values.

Correct Answer:

c. All records in verbatim from the table.

Detailed Solution:

When executing an SQL SELECT query using JDBC, the result is returned as a ResultSet object. This
ResultSet object contains all the records (rows) returned by the SELECT query from the specified table
(myTable in this case), without any filtering based on null values.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

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. FlowLayout

b. BorderLayout

c. GridLayout

d. BoxLayout

Correct Answer:

d. BoxLayout

Detailed Solution:

BoxLayout lays out components in either a column or a row. You can specify extra space using an
invisible component.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

Consider the following program:

public class Question {


public static void main(String[] args) {

String str = "NPTEL - Programming in JAVA - JULY 2024";

System.out.println(str.length());
}
}

What will be the output of the code given above?

a. 38

b. 39

c. 40

d. 41

Correct Answer:

b. 39

Detailed Solution:

The provided Java program calculates and prints the length of the string str, which contains the text
"NPTEL - Programming in JAVA - JULY 2024".
The output of this program will be: 39
This is because the string "NPTEL - Programming in JAVA - JULY 2024" consists of 39 characters, including
spaces and hyphens.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

Comnsider the code given below:

public class Test {


public static void aMethod() throws Exception {
try {
throw new Exception();
} finally {
System.out.print("finally ");
}
}
public static void main(String args[]) {
try {
aMethod();
} catch (Exception e) {
System.out.print("exception ");
}
System.out.print("finished ");
}
}

What will be the output of the code given above?

a. finally

b. exception finished

c. finally exception finished

d. Compilation fails

Correct Answer:

c. finally exception finished

Detailed Solution:

The program is syntactically correct and here for two try blocks, there is one catch block.
Here's the step-by-step explanation:
i. The main method calls aMethod(), which throws an Exception.
ii. Inside aMethod(), an Exception is thrown in the try block.
iii. The finally block is always executed, regardless of whether an exception is thrown or not. In
this case, it prints "finally ".
iv. Since aMethod() throws an Exception, control moves to the catch block in main.
v. The catch block prints "exception ".
vi. After the try-catch block in main, "finished " is printed.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

vii. Therefore, the complete output is "finally exception finished".


NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

Which of the following option is TRUE regarding the below statement?

Connection con = DriverManager.getConnection


("jdbc:mysql://localhost:3306/nptel","nptel","java");

a. 3307 is the MySQL port

b. Database name is ‘JAVA’

c. The database server is hosted on IP 192.168.0.1

d. Password for ‘nptel’ user is ‘java’

Correct Answer:

d. Password for ‘nptel’ user is ‘java’

Detailed Solution:

User is nptel and password is java


NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

Consider the code given below:

import javax.swing.*;
import java.awt.event.*;
public class NPTEL {
public static void main(String[] args) {
JFrame frame = new JFrame("NPTEL Java Course");
JButton button = new JButton("Click Me");
button.setBounds(50, 100, 100, 40);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Welcome to the course");
}
});
frame.add(button);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}

What happens when the button in this Java code snippet is clicked? Select your answer from the
following choices.

a. The program exits

b. A message dialog with the text "Welcome to the course" is displayed

c. The button label changes to "Welcome to the course"

d. Nothing happens

Correct Answer:

b. A message dialog with the text "Welcome to the course" is displayed

Detailed Solution:
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

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.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

Which class in Java is used to create a server socket?

a. Socket

b. ServerSocket

c. DatagramSocket

d. HttpURLConnection

Correct Answer:

b. ServerSocket

Detailed Solution:

ServerSocket is used to listen for incoming connections on a specific port, enabling communication
with clients in server-client applications.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

Which of the following is the most accurate description of the GUI shown?

a. There is a Frame with two Labels and two TextFields.

b. There is a Frame with two Labels and two non-editable TextFields.

c. There is a Frame with two Labels and two Buttons.

d. There is a Window with two Labels and two TextFields.

Correct Answer:

a. There is a Frame with two Labels and two TextFields

Detailed Solution:

There is a Frame with two Labels and two TextFields in the given GUI.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

Consider the code given below:

public class NPTEL {


public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
System.out.print((str1 == str2) + " ");
System.out.print(str1 == str3);
}
}

What will be the output of the code given above?

a. true false

b. false true

c. true true

d. false false

Correct Answer:

a. true false

Detailed Solution:

str1 and str2 are string literals and will be interned to the same memory location, so str1 ==
str2 will be true. However, str3 is created using the new keyword, so it will be stored in a different
memory location, leading str1 == str3 to be false.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

Which of the following is TRUE regarding check box and radio button?

a. Check box is used for single selection item whereas radio button is used for multiple selection.

b. Check box is used for multiple selection items whereas radio button is used for single selection.

c. Both are used for multiple as well as single item selection.

d. Checkbox is always preferred than radio buttons.

Correct Answer:

b. 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
option among the multiple choices, in that case radio buttons are used.

You might also like