Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Java Nptel Solution

The document contains multiple-choice questions (MCQs) from assignments on Java programming provided by the Indian Institute of Technology Kharagpur. Each question includes options, the correct answer, and a detailed solution explaining the concept. The assignments cover various Java programming topics such as platform independence, object-oriented principles, constructors, and method overriding.

Uploaded by

t33763210
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java Nptel Solution

The document contains multiple-choice questions (MCQs) from assignments on Java programming provided by the Indian Institute of Technology Kharagpur. Each question includes options, the correct answer, and a detailed solution explaining the concept. The assignments cover various Java programming topics such as platform independence, object-oriented principles, constructors, and method overriding.

Uploaded by

t33763210
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 120

NPTEL Online Certification Courses

Indian Institute of Technology Kharagpur

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

QUESTION 1:

What is the primary focus of Java programming?

a. Low-level op�miza�ons

b. Hardware-specific opera�ons

c. Pla�orm independence

d. Assembly language programming

Correct Answer:

c. Pla�orm independence

Detailed Solu�on:

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

QUESTION 2:

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

a. Code obfusca�on

b. Pla�orm dependence

c. Object-oriented programming

d. Global variables

Correct Answer:

c. Object-oriented programming

Detailed Solu�on:

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

QUESTION 3:

What is the last step in the Java programming process?

a. Java Program Execu�on

b. Java Program Edi�ng

c. Java Program Compila�on

d. C/C++ versus Java

Correct Answer:

a. Java Program Execu�on

Detailed Solu�on:

The final step in the Java programming process is the execu�on of the compiled Java program on the
Java Virtual Machine (JVM).
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

Which of the following is NOT a Java programming tool?

a. Eclipse

b. NetBeans

c. IntelliJ IDEA

d. GCC

Correct Answer:

d. GCC

Detailed Solu�on:

GCC (GNU Compiler Collec�on) is not a Java-specific tool. It is commonly used for compiling C, C++, and
other languages.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

What does the term "Write Once, Run Anywhere" (WORA) imply in Java?

a. Code reusability

b. Pla�orm independence

c. Cross-compila�on

d. Dynamic typing

Correct Answer:

b. Pla�orm independence

Detailed Solu�on:

"Write Once, Run Anywhere" (WORA) is a key concept in Java, indica�ng that code writen in Java can
run on any pla�orm without modifica�on.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

In Java, what is used to store multiple values of the same type?

a. Structures

b. Pointers

c. Arrays

d. Lists

Correct Answer:

c. Arrays

Detailed Solu�on:

Arrays in Java are used to store mul�ple values of the same type in a single variable.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

Which of the following is a valid identifier in Java?

a. 123iden�fier

b. _iden�fier

c. #iden�fier

d. iden�fier-123

Correct Answer:

b. _iden�fier

Detailed Solu�on:

Iden�fiers in Java can start with a leter, underscore (_), or dollar sign ($).
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

What is the purpose of Java Language Subset?

a. To limit the capabili�es of Java

b. To make Java code compa�ble with other languages

c. To define a smaller set of Java features for specific purposes

d. To enhance the performance of Java programs

Correct Answer:

c. To define a smaller set of Java features for specific purposes

Detailed Solu�on:

Java Language Subset is a set of features tailored for specific purposes, limi�ng the use of certain Java
features.
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 op�miza�on

b. Pla�orm independence

c. Memory management

d. Hardware-specific opera�ons

Correct Answer:

b. Pla�orm independence

Detailed Solu�on:

The Java Virtual Machine (JVM) enables pla�orm independence by interpre�ng Java bytecode, allowing
Java programs to run on any device with a compa�ble JVM.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

What is emphasized during the Java Program Editing phase?

a. Wri�ng pla�orm-specific code

b. Debugging the program

c. Compiling the program

d. Wri�ng and modifying the source code

Correct Answer:

d. Wri�ng and modifying the source code

Detailed Solu�on:

Java Program Edi�ng involves wri�ng and modifying the source code to implement the desired
func�onality before compila�on.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

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

QUESTION 1:

In Java programming an object can take many forms. This feature called ______.

a. Abstrac�on
b. Polymorphism
c. Encapsula�on
d. Inheritance

Correct Answer:

b. Polymorphism

Detailed Solu�on:

Polymorphism means "many forms", and it occurs when we have many classes that are related to each
other by inheritance. Object variables (instance variables) represent the behavior of polymorphic
variables in Java. It is because object variables of a class can refer to objects of its class as well as objects
of its subclasses.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

Which of the following is a valid declaration of an object of class, say NPTEL?

a. NPTEL obj = new NPTEL ();


b. NPTEL obj = new NPTEL;
c. obj = new NPTEL ();
d. new NPTEL obj;

Correct Answer:

a. NPTEL obj = new NPTEL ();

Detailed Solu�on:

The correct syntax for declaring an object is:


<class_name> <object_name> = new <class_name>().
So the correct declara�on of an object named obj is: NPTEL obj = new NPTEL();
Others are invalid declara�ons.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

A default constructor:

a. has no arguments
b. has no return type
c. has one argument but no return type
d. has two arguments

Correct Answer:

a. has no arguments

Detailed Solu�on:

A default constructor is a constructor created by the compiler if we do not define any constructor(s) for a
class. A constructor is called "Default Constructor" when it doesn't have any parameter. The Syntax of
default constructor: <class_name>(){} . The default constructor is used to provide the default values to
the object like 0, null, etc., depending on the type.
Example:

class NPTEL {

//creating a default constructor


NPTEL() {
System.out.println("Programming in Java");
}

//main method
public static void main(String args[]) {
//calling a default constructor
NPTEL obj = new NPTEL();
}
}

Output: “Programming in Java”


NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

A top-level class may have which one of the following access modifiers?

a. package
b. private
c. protected
d. public

Correct Answer:

d. public

Detailed Solu�on:

At the top level only public, or package-private (no explicit modifier) access modifier is allowed in
Java. For top level class only two access modifiers are allowed: public and default. If a class is
declared as public it is visible everywhere. If a class is declared default it is visible only in same
package.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

Integer in Java is a\an _______.

a. Adapter class
b. Inner class
c. Not a class
d. Wrapper class

Correct Answer:

d. Wrapper class

Detailed Solu�on:

Byte, Short, Integer, Long, Character, Boolean, Double, Float are called wrapper class in Java.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

What is true about the new operator?

a. returns a pointer to a variable


b. creates a variable called new
c. obtains memory for a new variable
d. tells how much memory is available

Correct Answer:

c. obtains memory for a new variable

Detailed Solu�on:

The new operator is used in Java to create new objects. It can also be used to create an array object. The
new operator instan�ates a class by alloca�ng memory for a new object and returning a reference to
that memory. The new operator also invokes the object constructor. It is used for dynamic memory
alloca�on which puts variables on heap memory.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

Which one is not supported by OOP?

a. Abstrac�on
b. Polymorphism
c. Encapsula�on
d. Global variables

Correct Answer:

d. Global variables

Detailed Solu�on:

Java does not support global variables. A global variable is one declared at the start of the code and is
accessible to all parts of the program. Since Java is object-oriented, everything is part of a class. The
intent is to protect data from being changed. A sta�c variable can be declared, which can be available to
all instances of a class.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

Which of the following modifiers can be used to disallow a method from being overridden?

a. final
b. transient
c. vola�le
d. sta�c

Correct Answer:

a. final

Detailed Solu�on:

The final keyword is a non-access modifier used for classes, atributes and methods, which makes
them non-changeable (impossible to inherit or override). The final keyword is useful when you want a
variable to always store the same value, like PI (3.14159...).
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

Consider the following code segment

1 class Question{
2 public static void main(String args){
3 System.out.print(“Welcome to NPTEL”);
4 }
5 }

Identify the line number(s) where there is/are error(s) in the above code.

a. 1
b. 2
c. 3
d. 4 and 5

Correct Answer:

b. 2

Detailed Solu�on:

The String argument in the main method is an array hence the args should be changed to args[].
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

Which of the following is TRUE about print() and println() methods?

a. print() prints in a single line only and mul�ple lines cannot be printed in any way.
b. println()prints and then appends a line break.
c. println() prints in a single line only and mul�ple lines cannot be printed.
d. print() prints and then appends a line break.

Correct Answer:

b. println()prints and then appends a line break.

Detailed Solu�on:

Method print() can be used to print in a single line only but mul�ple lines can be printed using escape
sequence ‘\n’. Similarly, println() prints in a single line only and mul�ple lines can be printed using escape
sequence ‘\n’. Method print() prints but does not appends a line break. So, op�on (b) println() prints and
then appends a line break is the only correct op�on.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

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

QUESTION 1:

Which of the following statement is true regarding the order of execution of constructors in an
inheritance hierarchy?

a. Base class constructor will be called followed by the derived class constructor.
b. Derived class constructor will be called followed by the base class constructor.
c. Only Base class constructor will be called.
d. Only derived class constructor will be called.

Correct Answer:

a. Base class constructor will be called followed by the derived class constructor.

Detailed Solu�on:

On object crea�on of derived class, first base class constructor and then the derived class constructor
will be called.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

The super() method is used to:

a. Call constructor of friend class


b. Is a declared method
c. Call constructor of the parent class
d. Call constructor

Correct Answer:

c. Call constructor of the parent class

Detailed Solu�on:

In Java programming language, the super() is a reference variable that is used to refer parent class
constructors. The super can be used to call parent class's variables and methods. The super() can be used
to call parent class' constructors only.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

What will be the output of the following Java program?

class A {

int i;

void display() {
System.out.println(i);
}
}

class B extends A {

int j;

void display() {
System.out.println(j);
}
}

class inheritance_demo {

public static void main(String args[]) {


B obj = new B();
obj.i = 1;
obj.j = 2;
obj.display();
}
}

a. 0
b. 1
c. 2
d. Compila�on Error

Correct Answer:

c. 2

Detailed Solu�on:

Class A & class B both contain display() method, class B inherits class A, when display() method is called
by object of class B, display() method of class B is executed rather than that of Class A.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

In Java, is it possible to override a static method?

a. Yes, we can override a sta�c method just like we do with instance methods.
b. No, sta�c methods cannot be overridden because they belong to the class, not the object.
c. It depends on whether the sta�c method is declared as final or not.
d. It depends on the access modifier of the sta�c method.

Correct Answer:

b. No, sta�c methods cannot be overridden because they belong to the class, not the object.

Detailed Solu�on:

In Java, a sta�c method is bound to the class and not to the instance. Hence, it is not part of the state of
the object and doesn't par�cipate in polymorphism and dynamic dispatch, which are necessary for
method overriding.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

What is the output of the following Java program?

public class Vehicle {


public void move() {
System.out.println("The vehicle moves");
}
}

public class Car extends Vehicle {


public void move() {
System.out.println("The car moves");
}
}

public class Main {


public static void main(String[] args) {
Vehicle vehicle = new Car();
vehicle.move();
}
}

a. "The vehicle moves"


b. "The car moves"
c. The code does not compile
d. None of the above

Correct Answer:

b. "The car moves"

Detailed Solu�on:

In Java, a subclass can override methods from its superclass. In this example, the Car class is overriding
the move method of the Vehicle class. Since the object is instan�ated as a Car, the overridden move
method in the Car class is called, producing the output "The car moves"
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

What is the output of the below Java program with inheritance?

class Sweet {

void price() {
System.out.print("Sweet=$10 ");
}
}

class Sugar extends Sweet {

void price() {
super.price();
System.out.print("Sugar=$20");
}
}

public class JavaInheritance1 {

public static void main(String[] args) {


Sugar su = new Sugar();
su.price();
}
}

a. Sweet=$10 Sugar=$20
b. Sweet=$10 Sugar=$10
c. Sweet=$20 Sugar=$20
d. Compiler error

Correct Answer:

a. Sweet=$10 Sugar=$20

Detailed Solu�on:

No�ce the use of the keyword "super". Using this keyword, you can call superclass's methods and
variables.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

What is the purpose of method hiding in Java inheritance?

a. To prevent a subclass from inheri�ng methods


b. To override superclass methods with new implementa�ons
c. To expose private methods of the superclass
d. To define methods with the same name in both the superclass and subclass

Correct Answer:

d. To define methods with the same name in both the superclass and subclass

Detailed Solu�on:

Method hiding occurs when a subclass defines a sta�c method with the same name as a sta�c method in
the superclass.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

What is the output of the following Java program?

class Parent {

String name = "parent";

String message() {
return "from parent";
}
}

class Child extends Parent {

String name = "child";

String message() {
return "from child";
}
}

public class Main {

public static void main(String[] args) {


Parent p = new Child();
System.out.println(p.name + " " + p.message());
}
}

a. "parent from parent"


b. "child from child"
c. "parent from child"
d. "child from parent"

Correct Answer:

c. "parent from child"

Detailed Solu�on:

In Java, while methods are overridden (dynamic binding), variables are not overridden (sta�c binding).
Therefore, p.name refers to the Parent class variable, and p.message() refers to the Child class method.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

Can a class be marked as both “final” and “abstract” in Java?

a. Yes, but only if it has no methods.


b. Yes, a class can be marked as both “final” and “abstract.”
c. No, a class cannot be both “final” and “abstract.”
d. Yes, but only if it is marked as “protected.”

Correct Answer:

c. No, a class cannot be both “final” and “abstract.”

Detailed Solu�on:

A class marked as “final” cannot be extended (subclassed), while an abstract class is meant to be
extended. Therefore, they are contradictory modifiers.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

In Java, is it possible to override a static method?

a. Yes, we can override a sta�c method just like we do with instance methods.
b. No, sta�c methods cannot be overridden because they belong to the class, not the object.
c. It depends on whether the sta�c method is declared as final or not.
d. It depends on the access modifier of the sta�c method.

Correct Answer:

b. No, sta�c methods cannot be overridden because they belong to the class, not the object.

Detailed Solu�on:

In Java, a sta�c method is bound to the class and not to the instance. Hence, it is not part of the state of
the object and doesn't par�cipate in polymorphism and dynamic dispatch, which are necessary for
method overriding.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

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

QUESTION 1:

Which is the keyword used to specify the default access modifier in java?

a. default
b. DEFAULT
c. package
d. “There is no keyword”

Correct Answer:

d. “There is no keyword”

Detailed Solu�on:

If you do not specify any access modifier before a variable or method, it is considered to be declared
under the default access modifier.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

What is the output of the Java program with access modifiers?

package nptel1;

public class ProgrammingInJava {

public String week = "FOUR";


}
// ---------------
package nptel2;

import nptel1;

public class Course {

public static void main(String[] args) {


ProgrammingInJava java = new ProgrammingInJava();
System.out.println(java.week);
}
}

a. FOUR
b. Run�me Error
c. null
d. Compiler Error

Correct Answer:

d. Compiler Error

Detailed Solu�on:

In order to use instance variables, one should import either a specific Class or all Classes of a Java
Package. So, without using import nptel1.*; or import nptel1.ProgrammingInJava;
there will be a compiler error: ProgrammingInJava cannot be resolved to a type.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

What is the output of the below Java Code Snippet with access modifiers?

package nptel1;

public class ProgrammingInJava {

int weeks = 12; // course duration


}

// ------------------
package nptel1;

public class Course {

public static void main(String[] args) {


ProgrammingInJava obj = new ProgrammingInJava();
System.out.println("Weeks = " + obj.weeks);
}
}

a. Weeks = 0
b. Weeks = 12
c. No Error, blank output
d. Compiler error

Correct Answer:

b. Weeks = 12

Detailed Solu�on:

The default variables or methods of class can be called inside any class of the same Package.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

Which of the following is the correct representation of access modifiers in order of increasing
visibility?

a. private < default < protected < public


b. private < protected < default < public
c. public < protected < default < private
d. protected < default < private < public

Correct Answer:

a. private < default < protected < public

Detailed Solu�on:

Here’s the order of the access modifiers from the least restric�ve to the most restric�ve:
public > protected > default > private
Thus, the correct representa�on of access modifiers in order of increasing visibility:
private < default < protected < public
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

Which of the following package stores all the standard java classes?

a. java.u�l
b. java.lang
c. java.java
d. java.packages

Correct Answer:

b. java.lang

Detailed Solu�on:

In Java, two packages java.lang package and a no-name package (also called default package) are
imported by default in all the classes of Java. Default Package doesn't have a name but it is present by
default and thus, it is named the default package. Java Virtual Machine imports these packages by
default in Java internally. And that is the reason we are able to access all the classes of these packages.
We are not required to explicitly import java.lang package or any of its classes like we import other
packages and their classes such as java.math or java.util.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

Which of the following is/are true about packages in Java?

1. Every class is part of some package.


2. All classes in a file are part of the same package.
3. If no package is specified, the classes in the file go into a special unnamed package.
4. If no package is specified, a new package is created with folder name of class and the class is
put in this package.

a. Only 1, 2 and 3
b. Only 1, 2 and 4
c. Only 4
d. Only 1 and 3

Correct Answer:

a. Only 1, 2 and 3

Detailed Solu�on:

In Java, a package can be considered as equivalent to C++ language's namespace. Thus, every class is
part of some package. All classes in a file are part of the same package. If no package is specified, the
classes in the file go into a special unnamed package.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

What is the output of following Java program?

import static java.lang.System.*;

class ProgrammingInJava {

public static void main(String args[]) {


out.println("Welcome!");
}
}

a. Compiler Error
b. Run�me Error
c. Welcome!
d. None of the above

Correct Answer:

c. Welcome!

Detailed Solu�on:

Sta�c import is a feature introduced in Java programming language (versions 5 and above) that allows
members (fields and methods) defined in a class as public static to be used in Java code without
specifying the class in which the field is defined. The only �me we need to pay aten�on to packages is
when we have a name conflict . For example both, java.util and java.sql packages have a class
named Date. So if we import java.util.*; and import java.sql.*; then the compiler
will not be able to figure out which Date class do we want.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

Which of these access specifiers can be used for an interface?

a. Public
b. Protected
c. private
d. All of the men�oned

Correct Answer:

a. Public

Detailed Solu�on:

Access specifier of an interface is either public or no specifier. When no access specifier is used then
default access specifier is used due to which interface is available only to other members of the package
in which it is declared, when declared public it can be used by any code.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

Which of the following is the correct way of implementing an interface NPTEL by class Java?

a. class Java extends NPTEL {}


b. class Java implements NPTEL {}
c. class Java imports NPTEL {}
d. none of the men�oned

Correct Answer:

b. class Java implements NPTEL {}

Detailed Solu�on:

interface is inherited by a class using implements.


NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

What will be the output of the following Java program?

interface calculate {
void cal(int item);
}

class display implements calculate {


int x;

public void cal(int item) {


x = item * item;
}
}

class interfaces {
public static void main(String args[])
{
display arr = new display();
arr.x = 0;
arr.cal(2);
System.out.print(arr.x);
}
}

a. 0
b. 2
c. 4
d. Compiler Error

Correct Answer:

c. 4

Detailed Solu�on:

There is no error in the program and the cal() func�on is called successfully, computes the square of
item and stores in x. Which is successfully printed.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

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

QUESTION 1:

Which of the following is an incorrect statement about interfaces?

a. Interfaces specifies what class must do but not how it does.


b. Interfaces are specified public if they are to be accessed by any code in the program.
c. All variables in interface are implicitly final and sta�c.
d. All variables are sta�c and methods are public if interface is defined public.

Correct Answer:

d. All variables are sta�c and methods are public if interface is defined public.

Detailed Solu�on:

All methods and variables are implicitly public if interface is declared public.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

How do you access a static method of an interface?

a. Using the interface name


b. Using the method name directly
c. Through an object of the interface
d. Through an implementa�on class

Correct Answer:

a. Using the interface name

Detailed Solu�on:

Sta�c methods in an interface are accessed using the interface name, similar to sta�c methods in classes.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

What is the output of the below Java program with an Interface?

interface Car {
int basePrice = 1000;
}

public class InterfaceTest2 implements Car {


void changePrice() {
basePrice = 2000;
System.out.print(basePrice);
}

public static void main(String[] args) {


new InterfaceTest2().changePrice();
}
}

a. 1000
b. 2000
c. Compiler error
d. None of the above

Correct Answer:

c. Compiler error

Detailed Solu�on:

Java Interface treats its variables like constants. So, the classes implemen�ng Interfaces, can not reassign
values to the variables.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

What happens when we access the same variable defined in two interfaces implemented by the same
class?

a. Compila�on failure
b. Run�me Excep�on
c. The JVM is not able to iden�fy the correct variable
d. The interfaceName. variableName needs to be defined

Correct Answer:

d. The interfaceName.variableName needs to be defined

Detailed Solu�on:

Explana�on: The JVM needs to dis�nctly know which value of variable it needs to use. To avoid confusion
to the JVM interfaceName.variableName is mandatory.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

Predict the output of following Java program

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 ");
}
}
}

a. Got the Test Excep�on


Inside finally block
b. Got the Test Excep�on
c. Inside finally block
d. Compiler Error

Correct Answer:

a. Got the Test Excep�on


Inside finally block

Detailed Solu�on:

In Java, the finally is always executed a�er the try-catch block. This block can be used to do the common
cleanup work.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

What happens if an exception is not caught in the catch block?

a. The finally block handles it


b. The excep�on is ignored
c. The excep�on is thrown to the caller method
d. The program terminates immediately

Correct Answer:

c. The excep�on is thrown to the caller method

Detailed Solu�on:

If an excep�on is not caught in the catch block, it is propagated back to the caller method.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

What will be the output of the following Java program?

class exception_handling {

public static void main(String args[]) {


try {
System.out.print("Hello" + " " + 1 / 0);
} catch (ArithmeticException e) {
System.out.print("World");
}
}
}

a. Hello
b. World
c. HelloWorld
d. Hello World

Correct Answer:

b. World

Detailed Solu�on:

System.out.print() func�on first converts the whole parameters into a string and then prints, before
“Hello” goes to output stream 1 / 0 error is encountered which is cached by catch block prin�ng just
“World”.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

What is the output of the below Java code with Exceptions?

public class ExceptionTest2 {

public static void main(String[] args) {


try {
int ary[] = { 10, 20, 30 };
int tempt = ary[4];
} catch (ArrayIndexOutOfBoundsException e1) {
System.out.println(e1.getMessage());
} catch (Exception e2) {
System.out.println("Some exception");
}
}
}

a. Index 4 out of bounds for length 3


b. Index 4 out of bounds for length 3
Some excep�on
c. Some excep�on
d. No excep�on occurs

Correct Answer:

a. Index 4 out of bounds for length 3

Detailed Solu�on:

IndexOutOfBoundsExcep�on is raised by TRY block. Observe the order of catching the excep�ons. Always
catch a Subclass excep�on before a Superclass excep�on.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

What is the output of the Java code with FINALLY block and RETURN statement?

public class ExceptionTest6 {

static void show() {


try {
System.out.println("inside TRY");
return;
} finally {
System.out.println("inside FINALLY");
}
}

public static void main(String[] args) {


show();
}
}

a. inside TRY
b. inside TRY
inside FINALLY
c. inside FINALLY
d. Compiler error

Correct Answer:

b. inside TRY
inside FINALLY

Detailed Solu�on:

Even if a RETURN statement is present at the last line of TRY block, the control is not returned to the
calling method. The JVM searches for the suitable FINALLY block and executes it before returning. So, the
FINALLY block has higher priority than a RETURN statement.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

What is the purpose of the finally block in Java exception handling?

a. To handle an excep�on
b. To catch an excep�on
c. To clean up resources a�er a try block
d. None of the above

Correct Answer:

c. To clean up resources a�er a try block

Detailed Solu�on:

The purpose of the finally block in Java excep�on handling is to clean up resources a�er a try block. The
finally block is executed whether or not an excep�on is thrown in the try block. It is typically used to
release resources such as open files, database connec�ons, or network sockets that were acquired in the
try block. The finally block ensures that these resources are released even if an excep�on is thrown,
which helps prevent resource leaks and other issues. The finally block is op�onal, but it is good prac�ce
to use it when dealing with resources that need to be released.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

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

QUESTION 1:

What is the output of the following program?

public class Nptel{

public static void main(String[] args) {


try {
int a = 5 / 0;
} catch (Exception e) {
catch (ArithmeticException a) {

}
}
System.out.println("Programming In Java");
}
}

a. “Programming In Java”

b. Run �me error

c. Compile �me error

d. Arithme�cExcep�on

Correct Answer:

c. Compile �me error

Detailed Solu�on:

This first handler catches excep�ons of type Exception; therefore, it catches any excep�on,
including ArithmeticException. The second handler could never be reached. This code will not
compile.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:
What is the output of the following program?

public class Nptel extends Thread {

public void run() {


for (int i = 1; i < 5; i++) {
System.out.print(i++ + " ");
}
}

public static void main(String args[]) {


Nptel t1 = new Nptel();
t1.run();
}
}

a. 1 3

b. 1 2 3 4

c. Run�me error

d. 1 2

Correct Answer:

a. 1 3

Detailed Solu�on:

Inside the for loop, the increment opera�on i++ is used, which is a post-increment opera�on. This
means that the increment happens a�er the value of i is used. But since this increment opera�on is
inside the print statement, it will increment i by 1 right a�er prin�ng it, effec�vely skipping every other
number. So, the output of this code will be: “1 3”
This is because the i++ opera�on inside the System.out.print statement causes i to increment
by an addi�onal 1 each �me through the loop, resul�ng in only the odd numbers between 1 and 3 being
printed.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

For the program given below, what will be the output after its execution?

public class Nptel extends Thread {

public static void main(String[] args) {


Thread thread = Thread.currentThread();
System.out.println(thread.activeCount());
}
}

a. 0

b. true

c. 1

d. false

Correct Answer:

c. 1

Detailed Solu�on:

java.lang.Thread.activeCount() returns an es�mate of the number of ac�ve threads in the


current thread’s thread group and its subgroups which is 1 in this case since it’s the only thread running
the program.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

Which of the following is a correct constructor for a thread object?

a. Thread(Runnable a, String str);

b. Thread(Runnable a, int priority);

c. Thread(Runnable a, ThreadGroup t);

d. Thread(int priority);

Correct Answer:

a. Thread(Runnable a, String str);

Detailed Solu�on:

Thread(Runnable a, String str) creates a new Thread object. The others are not valid
constructors to create a Thread object.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

What is the output of the following program?

class Nptel extends Thread {

public void run() {


System.out.println("Running");
}
}

public class ThreadTest {

public static void main(String args[]) throws InterruptedException {


Runnable r = new Nptel();
Thread myThread = new Thread(r);
myThread.start();
}
}

a. Compiler Error

b. “Running”

c. Run�me Excep�on

d. No output, but no error

Correct Answer:

b. “Running”

Detailed Solu�on:

The class Thread implements the Runnable interface, so the assignment is valid. Also, you can create
a new thread object by passing a Runnable reference to a Thread constructor, is also valid. Hence,
the program will compile without errors and print “Running” in the console.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

How many threads does the following program run on?

public class ThreadExtended extends Thread {

public void run() {


System.out.println("\nThread is running now\n");
}

public static void main(String[] args) {


ThreadExtended threadE = new ThreadExtended();

threadE.start();
}
}

a. 0

b. 1

c. 2

d. 3

Correct Answer:

c. 2

Detailed Solu�on:

There are 2 threads. Main program is also run as a thread. And, program has created one child thread.
Hence, total 2 threads are there in the program.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

In the following java program, what is the NAME of the thread?

class Nptel extends Thread{

public static void main(String args[]) {


Thread t = Thread.currentThread();
System.out.println(t);
}
}

a. thread

b. main

c. system

d. None of the above

Correct Answer:

b. main

Detailed Solu�on:

The name of the Tread t is main as it’s the only tread that is running. It is set to currentThread()
which is main.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

Which of the following line(s) of code is suitable to START a thread at #1?

class Nptel extends Thread {

public static void main(String args[]) {


/* Missing code */
_______________________ // #1
}

public void run() {}


}

a. Thread t = new Thread(Nptel);

b. Thread t = new Thread(Nptel);


t.start();

c. Nptel run = new Nptel();


Thread t = new Thread(run);
t.start();

d. Thread t = new Thread();


Nptel.run();

Correct Answer:

c. Nptel run = new Nptel();


Thread t = new Thread(run);
t.start();

Detailed Solu�on:

An instance of the Nptel class is created. This class should implement the Runnable interface, which
means it must have a run method. This run method contains the code that will be executed in the new
thread. (Nptel run = new Nptel();)
A new Thread object is created, passing the Nptel instance (run) to the Thread constructor.
This tells the Thread that it should execute the run method of the Nptel instance in the new thread.
(Thread t = new Thread(run);)
The start method of the Thread instance is called. This method starts the new thread and calls the
run method of the Nptel instance in that new thread. (t.start();) So, the run method of the
Nptel instance will be executed in a new thread, separate from the main thread of the applica�on.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

What is the name of the priority of this Thread in this program?

class Nptel extends Thread{

public static void main(String args[]) {


Thread t = Thread.currentThread();
System.out.println(t.getPriority());
}
}

a. 1

b. 4

c. 0

d. 5

Correct Answer:

d. 5

Detailed Solu�on:

The default priority given to a thread is 5.


NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

What does I/O stand for in Java?

a. Input/Output

b. Inheritance/Overriding

c. Integer/Object

d. Itera�on/Observa�on

Correct Answer:

a. Input/Output

Detailed Solu�on:

I/O stands for Input/Output in Java. It refers to the process of reading data from input sources and
wri�ng data to output des�na�ons.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

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

QUESTION 1:

Which stream does Java application uses to read data from a source, it may be a file, an array,
peripheral device or socket?

a. InputStream

b. OutputStream

c. Input/OutputStream

d. None of the above

Correct Answer:

a. InputStream

Detailed Solu�on:

InputSteam is used to read data from any source in Java.


NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

What is the primary purpose of input streams in Java?

a. To write data to a file.

b. To read data from a file.

c. To append data to a file.

d. To create directories.

Correct Answer:

b. To read data from a file.

Detailed Solu�on:

Input streams are used to read data from a file or another source.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

Which class in Java is used to create a new directory?

a. FileReader

b. FileWriter

c. File

d. Directory

Correct Answer:

c. File

Detailed Solu�on:

The File class is used to create directories and manipulate files.


NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

Which class in Java is used to read data line by line from a file?

a. BufferedReader

b. FileInputStream

c. FileWriter

d. OutputStream

Correct Answer:

a. BufferedReader

Detailed Solu�on:

BufferedReader is commonly used to read data line by line from a file.


NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

What does the following code do?

FileInputStream fis = new FileInputStream("test.dat");

a. It creates a new file named test.dat if it does not exist and opens the file so you can write to
it, if write permission is available.

b. It thows an error if the file named test.dat does not exist and opens the file, if it exists, so you
can read from it and write into it, if write permission is available.

c. It creates a new file named test.dat regardless of whether it exists or not and opens the file so
you can write to it, if write permission is available.

d. It creates a new file named test.dat regardless of whether it exists or not and opens the file so
you can read from it and write to it, if write permission is available.

Correct Answer:

b. It thows an error if the file named test.dat does not exist and opens the file, if it exists, so you
can read from it and write into it, if write permission is available.

Detailed Solu�on:

The provided Java code is crea�ng a FileInputStream object. FileInputStream is a class in


Java that is used for reading data from files. It's part of the Java I/O (Input/Output) package. The string
"test.dat" is the path to the file. If only a filename is provided (like in this case), Java will look for the file
in the current directory of the program. If the file is located in a different directory, you would need to
provide the full path to the file.
Once the FileInputStream is created, you can use its methods to read data from the file. For
example, the read method can be used to read a single byte of data from the file, and the
read(byte[] b) method can be used to read up to b.length bytes of data from the file into an
array of bytes.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

What is the output of this program? (Assume 'inputoutput.java' file exists in the current directory)

import java.io.*;

class filesinputoutput {
public static void main(String args[]) throws FileNotFoundException,
IOException {
InputStream obj = new FileInputStream("inputoutput.java");
System.out.print(obj.available());
obj.close();
}
}

a. true

b. false

c. prints number of bytes in file

d. prints number of characters in the file

Correct Answer:

c. prints number of bytes in file

Detailed Solu�on:

obj.available() returns the number of bytes.


NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

What will be the output of the following Java program?

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();
}
}
}

a. abc

b. abcd

c. abcde

d. none of the men�oned

Correct Answer:

d. none of the men�oned

Detailed Solu�on:

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 star�ng
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

QUESTION 8:

What is the output of the following Java program?

class Main {

public static void main(String args[]) {


final int i;
i = 20;
i = 30;
System.out.println(i);
}
}

a. 30

b. Compiler Error

c. Garbage value

d. 0

Correct Answer:

b. Compiler Error

Detailed Solu�on:

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 9:

In order to restrict a variable of a class from inheriting to subclass, how variable should be declared?

a. Protected

b. Private

c. Public

d. Sta�c

Correct Answer:

b. Private

Detailed Solu�on:

By declaring variable private, the variable will not be available in inherited to subclass.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

A ________ is a type of object that organizes components in a container.

a. Event adapter

b. Event Handler

c. Layout manager

d. Grid Manager

Correct Answer:

c. Layout manager

Detailed Solu�on:

A layout manager is a type of object that organizes components in a container.


NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

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

QUESTION 1:

What does AWT stand for in Java?

a. Applet Windowing Toolkit

b. Abstract Window Toolkit

c. Absolute Windowing Toolkit

d. None of the above

Correct Answer:

b. Abstract Window Toolkit

Detailed Solu�on:

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

QUESTION 2:

When we invoke repaint() for a java.awt.Component object, the AWT invokes which of the
following method ?

a. draw( )

b. show( )

c. update( )

d. none of the men�oned

Correct Answer:

c. update( )

Detailed Solu�on:

The repaint() method calls automa�cally update() method and in turn update() method calls
paint() method.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

Which is/are used to create a Frame?

1. By creating the object of Frame class (association)

2. By extending Frame class (inheritance)

a. Only 1

b. Only 2

c. Both

d. None

Correct Answer:

c. Both

Detailed Solu�on:

A Frame object can be created using the Frame class itself as well as extending the Frame class.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

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

a. Event Handling

b. Component Interac�on

c. Process Management

d. GUI Processing

Correct Answer:

a. Event Handling

Detailed Solu�on:

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

QUESTION 5:

Which of the following methods can be used to change the size of a java.awt.Component object?

1. dimension()

2. setSize()

3. area()

4. size()

5. resetSize()

a. 1, 2, 3 & 5

b. 4 & 5

c. 1, 2 & 5

d. only 2

Correct Answer:

d. only 2

Detailed Solu�on:

The method setSize() can only be used to change the size of a component.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

Which of the following is TRUE regarding checkbox and radio button?

a. Checkbox is used for single selec�on item whereas radio buton is used for mul�ple selec�on.

b. Checkbox is used for mul�ple selec�on items whereas radio buton is used for single selec�on.

c. Both are used for mul�ple as well as single item selec�on.

d. Checkbox is the same as radio butons.

Correct Answer:

b. Checkbox is used for mul�ple selec�on items whereas radio buton is used for single selec�on.

Detailed Solu�on:

Checkbox is used for mul�ple selec�on items whereas radio buton is used for single selec�on. For
example, if a form is asking for your favorite hobbies, there might be mul�ple correct answers to it, in
that case checkbox is preferred. And if a form is asking about gender, there must be only one true op�on
among the mul�ple choices, in that case radio butons are used.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

How is AWT different from Swing in Java?

a. AWT is for web applica�ons, Swing is for desktop applica�ons

b. AWT uses lightweight components, Swing uses heavyweight components

c. AWT is newer than Swing

d. AWT and Swing are synonyms, used interchangeably

Correct Answer:

b. AWT uses lightweight components, Swing uses heavyweight components

Detailed Solu�on:

AWT components are pla�orm-dependent and use na�ve components, whereas Swing components are
implemented in Java and are pla�orm-independent.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

What is the primary purpose of AWT components in GUI programming?

a. To perform mathema�cal calcula�ons

b. To interact with databases

c. To create graphical user interfaces

d. To handle network communica�ons

Correct Answer:

c. To create graphical user interfaces

Detailed Solu�on:

AWT components provide the building blocks for crea�ng graphical user interfaces (GUIs) in Java
applica�ons.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

What will be the output of the Java 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("NPTEL – Programming in Java");
b.setBounds(30, 50, 80, 30);
frame.add(b);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}

a. A frame with a buton "NPTEL – Programming in Java" at coordinates (30, 50)

b. Compila�on error

c. An empty frame with no buton

d. A frame with a buton, but not at the specified coordinates

Correct Answer:

a. A frame with a buton "NPTEL – Programming in Java" at coordinates (30, 50)

Detailed Solu�on:

The code creates a frame and adds a buton with the label "NPTEL – Programming in Java" at coordinates
(30, 50).
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

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

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

public class GridLayoutExample extends Frame {


public static void main(String[] args) {
GridLayoutExample frame = new GridLayoutExample();
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);
frame.setLayout(new GridLayout(2, 2));
frame.setSize(300, 200);
frame.setVisible(true);
}
}

a. Border Layout

b. Flow Layout

c. Grid Layout

d. Card Layout

Correct Answer:

c. Grid Layout

Detailed Solu�on:

The code sets the layout manager of the 1frame to a 2x2 grid layout using frame.setLayout(new
GridLayout(2, 2)).
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

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

QUESTION 1:

L
What is the parent class of all AWT components?

E
a. java.awt.Panel

T
b. java.awt.Component

P
c. java.awt.Container

N
d. java.awt.Frame

Correct Answer:

b. java.awt.Component

Detailed Solu�on:

java.awt.Component is the parent class of all AWT components. It provides methods for se�ng and
ge�ng the proper�es of a component, such as its size and posi�on.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

Which event is generated when a user clicks a button in AWT?

a. MouseEvent

b. Ac�onListener

c. KeyEvent

d. WindowEvent

L
Correct Answer:

E
b. Ac�onListener

Detailed Solu�on:

N PT
The Ac�onListener event is generated when a user clicks a buton in AWT. It is used to handle buton
clicks and perform the necessary ac�ons.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

Which of the following architecture does the Swing framework use?

a. MVC

b. MVP

c. Layered architecture

d. Master-Slave architecture

L
Correct Answer:

E
a. MVC

Detailed Solu�on:

N PT
Swing framework uses MVC architecture.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

A ____ is the basic class for all SWING UI components?

a. Container

b. JComponent

c. Component

d. Jbox

L
Correct Answer:

E
b. JComponent

Detailed Solu�on:

N PT
A JComponent is a basic class for all SWING UI components.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

Which event is generated when a window is resized in AWT?

a. WindowEvent

b. ComponentEvent

c. ResizeEvent

d. ContainerEvent

L
Correct Answer:

E
b. ComponentEvent

Detailed Solu�on:

N PT
The ComponentEvent is generated when a window is resized in AWT. It is used to handle changes in the
size or posi�on of components.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

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

a. remove()

b. deleteComponent()

c. removeComponent()

d. destroy()

L
Correct Answer:

E
a. remove()

Detailed Solu�on:

N PT
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 7:

What is true about 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);

L
frame.setVisible(true);
}

E
}

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

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

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

d. Code throws an ERROR.

Correct Answer:

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

Detailed Solu�on:

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

QUESTION 8:

Which of the following function is used to generate the application's top-level window?

a. JPanel

b. JFrame

c. JCombo

d. JBox

L
Correct Answer:

E
b. JFrame

Detailed Solu�on:

N PT
JFrame is used to generate the applica�on's top-level window.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

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

L
d. To control database connections

E
Correct Answer:

T
b. To arrange GUI components within a container

N P
Detailed Solu�on:

A layout manager in Java is responsible for arranging and posi�oning GUI components within a container.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

Which layout manager divides the container into five regions: North, South, East, West, and Center?

a. Border Layout

b. Grid Layout

c. Flow Layout

d. Card Layout

L
Correct Answer:

E
a. Border Layout

Detailed Solu�on:

N PT
Border Layout divides the container into five regions, and components can be added to each region:
North, South, East, West, and Center.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

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. URLConnec�on

b. HtpURL

c. NetURLg

d. URL

Correct Answer:

d. URL

Detailed Solu�on:

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

QUESTION 2:

What does the following code do?

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();
}
}

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

b. Compiles with errors

c. Displays a message dialog

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

Correct Answer:

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

Detailed Solu�on:

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

QUESTION 3:

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

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);
}
}

a. The program exits

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

c. The buton 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 Solu�on:

The code creates a buton with label “Click Me” and in the frame �tled “NPTEL Java Course”. A ac�on
listener is defined that opens a new message dialog with the text “Welcome to the course” when the
buton is clicked.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

What GUI component is used to input the password in this Java code snippet?

import javax.swing.*;
public class NPTELLoginGUI extends JFrame {
JTextField username;
JPasswordField password;
JButton loginButton;
public LoginGUI() {
username = new JTextField();
password = new JPasswordField();
loginButton = new JButton("Student Login");
add(username);
add(password);
add(loginButton);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new LoginGUI();
}
}

a. JTextField

b. JButon

c. JtextArea

d. JPasswordField

Correct Answer:

d. JPasswordField

Detailed Solu�on:

The GUI component which is used to input the password field is JPasswordField.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

What does this Java code snippet create?

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);
}
}

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

b. A frame with a combo box containing op�ons "Red", "Green", and "Blue"

c. A frame with radio butons for selec�ng colors

d. A frame with checkboxes for selec�ng colors

Correct Answer:

b. A frame with a combo box containing op�ons "Red", "Green", and "Blue"

Detailed Solu�on:

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

QUESTION 6:

What does this Java code snippet do?

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);
}
}
}

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 Solu�on:

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:

What does this Java code snippet do?

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);
}
}
}

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 Solu�on:

The code snippet establishes a connec�on 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:

What does this Java code snippet do?

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);
}
}
}

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 Solu�on:

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:

What additional code is needed at #1 to complete this Java program to send a message?

import java.net.*;
public class NPTEL {
public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket();
InetAddress address = InetAddress.getByName(
"localhost");
String message = "Hello, UDP Server!";
DatagramPacket packet = new DatagramPacket(
message.getBytes(),
message.length(),
address,
9876);
// #1 (MISSING CODE)
socket.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

a. socket.recieve(packet);

b. Socket.Send(packet);

c. Socket.send(packet);

d. socket.send(packet);

Correct Answer:

d. socket.send(packet);

Detailed Solu�on:

Java is case sensi�ve. A socket.send() func�on needs to be called to send the packet to the server.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

What is missing in this Java program?

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);
}
}
}

a. Retrieving the number of employees

b. Dele�ng employee records

c. Upda�ng employee records

d. Impor�ng necessary JDBC libraries

Correct Answer:

d. Impor�ng necessary JDBC libraries

Detailed Solu�on:

The program lacks the import statements for the necessary JDBC libraries like java.sql.* .
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

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

QUESTION 1:

What is the correct order to close database resources?

a. Connec�on then Statement then ResultSet

b. ResultSet then Statement then Connec�on

c. Statement then Connec�on then ResultSet

d. Statement then ResultSet then Connec�on

Correct Answer:

b. ResultSet then Statement then Connec�on

Detailed Solu�on:

When manually closing database resources, they should be closed in the reverse order from which they
were opened. This means that the ResultSet object is closed before the Statement object and the
Statement object is closed before the Connec�on object.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

How many types of JDBC drivers there?

a. 3

b. 4

c. 8

d. 10

Correct Answer:

b. 4

Detailed Solu�on:

There are 4 types of JDBC drivers: Type-1 driver or JDBC-ODBC bridge driver, Type-2 driver or Na�ve-API
driver, Type-3 driver or Network Protocol driver, Type-4 driver or Thin driver.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

What is the correct sequence to create a database connection?

i. Import JDBC packages.


ii. Open a connection to the database.
iii. Load and register the JDBC driver.
iv. Execute the statement object and return a query resultset.
v. Create a statement object to perform a query.
vi. Close the resultset and statement objects.
vii. Process the resultset.
viii. Close the connection.

a. i, ii, iii, v, iv, vii, viii, vi

b. i, iii, ii, v, iv, vii, vi, viii

c. ii, i, iii, iv, viii, vii, v, vi

d. i, iii, ii, iv, v, vi, vii, viii

Correct Answer:

b. i, iii, ii, v, iv, vii, vi, viii

Detailed Solu�on:

To create a database connec�on in Java, we must follow the sequence given below:
1. Import JDBC packages.
2. Load and register the JDBC driver.
3. Open a connec�on to the database.
4. Create a statement object to perform a query.
5. Execute the statement object and return a query resultset.
6. Process the resultset.
7. Close the resultset and statement objects.
8. Close the connec�on.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

Which of the following is correct about connection pooling?

a. Applica�on server like WebLogic, WebSphere, jBoss and Tomcat provides the facili�es to
configure connec�on pooling.

b. components like Apache Commons DBCP Component can be used to configure connec�on
pooling.

c. Both of the above.

d. None of the above.

Correct Answer:

c. Both of the above

Detailed Solu�on:

If you use an applica�on server like WebLogic, WebSphere, jBoss, Tomcat. , then your applica�on server
provides the facili�es to configure for connec�on pooling. If you are not using an applica�on server then
components like Apache Commons DBCP Component can be used.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

Which of the following is used to test the operation?

a. JDBC API

b. JDBC Driver manager

c. JDBC Test suite

d. JDBC-ODBC Bridge Drivers

Correct Answer:

c. JDBC Test suite

Detailed Solu�on:

JDBC Test suite: It is used to test the opera�on(such as inser�on, dele�on, upda�on) being performed by
JDBC Drivers.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

The JDBC architecture consists of _____________ to access a database.

a. three-�er processing models

b. two-�er processing models

c. two-�er and three-�er processing models

d. None of the above

Correct Answer:

c. two-�er and three-�er processing models

Detailed Solu�on:

The JDBC architecture consists of two-�er and three-�er processing models to access a database.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

Which of these obtains a Connection?

a. Connec�on.getConnec�on(url)

b. Driver.getConnec�on(url)

c. DriverManager.getConnec�on(url)

d. new Connec�on(url)

Correct Answer:

c. DriverManager.getConnec�on(url)

Detailed Solu�on:

Op�on C is the correct answer because DriverManager is the class used in JDBC to get a Connec�on.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

Which class provides methods to create a client-side socket in Java?

a. ServerSocket

b. NetSocket

c. Socket

d. ClientSocket

Correct Answer:

c. Socket

Detailed Solu�on:

The Socket class in the java.net package is used to create client-side sockets.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

What does JDBC stand for?

a. Java DataBase Connec�vity

b. Java DataBase Connec�on

c. Java DataBase Control

d. Java DataBase Connector

Correct Answer:

a. Java Database Connec�vity

Detailed Solu�on:

JDBC stands for Java DataBase Connec�vity.


NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 10:

Which method can be used to query for a single object using JdbcTemplate?

a. queryForObject()

b. queryForList()

c. query()

d. singleQuery()

Correct Answer:

a. queryForObject()

Detailed Solu�on:

The queryForObject() method of JdbcTemplate is used to query for a single object.


NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

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

QUESTION 1:

Which of the following statements are correct and would NOT cause a compilation error?

i. float[] = new float(3);


ii. float f1[] = new float[];
iii. float[] f2 = new float[3];
iv. float f3[] = new float[3];
v. float f4[]= { 1.0f, 2.0f, 2.0f };
vi. float f5[] = new float[] { 1.0f, 2.0f, 3.0f};

a. iii, iv, v, vi

b. i, ii, iii, iv

c. ii, iii, v, vi

d. i, ii, iv, vi

Correct Answer:

a. iii, iv, v, vi

Detailed Solu�on:

Op�on iii, iv, v and vi are syntac�cally correct for declara�on of an array.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 2:

What is the result, if the following program is executed?

public class NPTEL {


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 ");
}
}

a. “finally”

b. “excep�on finished”

c. “finally excep�on finished”

d. Compila�on fails

Correct Answer:

c. “finally excep�on finished”

Detailed Solu�on:

The program is syntac�cally correct and here for two try blocks, there is one catch block.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 3:

What is the output of the following program?

public class NPTEL {


public static void main(String[] args) {
String str = "Programming with java - nptel.";
System.out.println(str.charAt(13+4) + str.substring(13+5, 13+8));
}
}

a. java

b. ava

c. java - nptel

d. with

Correct Answer:

a. java

Detailed Solu�on:

str.charAt(17) returns ‘j’ and str.substring(18,21) returns ‘ava’ and they are printed
together.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 4:

If you run this program the how many threads will be executed altogether?

class NPTEL extends Thread {


public void run() {
System.out.println("I am from Run…");
}
}

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

a. One thread only.

b. Two threads only.

c. Three threads only.

d. No thread will run in this case.

Correct Answer:

b. Two threads only.

Detailed Solu�on:

Here, two thread objects will be in execu�on: One is the thread due to the execu�on of the main()
method and other is the run() of the object t.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 5:

Which of the following method is used to set a frame, say f with size 300 × 200 pixels?

JFrame f = newJFrame();

a. f.setSize(300, 200);

b. f.setSize(200, 300);

c. f.paint(300, 200);

d. f.setVisible(300, 200);

Correct Answer:

a. f.setSize(300, 200);

Detailed Solu�on:

The setSize(300,200) method is used to do the job. Other are either syntac�cally not valid or not
appropriate.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 6:

Which of the following control expressions are valid for an if statement?

i. Any integer expression.


ii. Any Boolean expression.
iii. A String object.
iv. Any expression with mixed arithmetic.

a. only ii

b. ii, iii

c. ii,iv

d. i, ii

Correct Answer:

a. only ii

Detailed Solu�on:

Any expression with Boolean or integer variables are valid. The condi�on will evaluate to zero (false) or
no-zero (true) values. Other op�ons are not valid.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 7:

Which of the following options correctly initializes the elements of the numbers array with values 1, 2,
3, 4, and 5?

public class NPTEL {


public static void main(String[] args) {
int[] numbers = new int[5];
// #1 : Missing code block
System.out.println("First element: " + numbers[0]);
}
}

a. numbers = {1, 2, 3, 4, 5};

b. for (int i = 1; i < numbers.length; i++) {


numbers[i] = i;
}

c. numbers[] = {1, 2, 3, 4, 5};

d. numbers = new int[]{1, 2, 3, 4, 5};

Correct Answer:

d. numbers = new int[]{1, 2, 3, 4, 5};

Detailed Solu�on:

numbers = new int[]{1, 2, 3, 4, 5}; is the correct answer because it ini�alizes the
numbers array with values 1, 2, 3, 4, and 5 using array ini�alizer syntax.
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 8:

Which of the following options correctly extracts and prints the word "World" from the str string?

public class StringExample {


public static void main(String[] args) {
String str = "Hello, World!";
//#1 Missing code block
}
}

a. System.out.println(str.substring(7, 12));

b. System.out.println(str.subString(7, 12));

c. System.out.println(str.extract(7, 12));

d. System.out.println(str.substr(7, 13));

Correct Answer:

a. System.out.println(str.substring(7, 12));

Detailed Solu�on:

System.out.println(str.substring(7, 12)); is the correct answer because the


substring() method extracts a substring from the str string star�ng from index 7 (inclusive) to
index 12 (exclusive), which results in the substring "World".
NPTEL Online Certification Courses
Indian Institute of Technology Kharagpur

QUESTION 9:

What will be the output of this program?

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);
}
}

a. true false

b. false true

c. true true

d. false false

Correct Answer:

a. true false

Detailed Solu�on:

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

QUESTION 10:

What will be the output of this program?

public class NPTEL {


public static void main(String[] args) {
try {
int num = 10 / 0;
System.out.println(num);
} catch (ArithmeticException e) {
System.out.println("Arithmetic exception occurred");
} finally {
System.out.println("Finally block executed");
}
}
}

a. Compila�on ERROR

b. “Finally block executed”

c. “Arithme�c excep�on occurred


Finally block executed”

d. Run�me ERROR

Correct Answer:

c. “Arithme�c excep�on occurred


Finally block executed”

Detailed Solu�on:

The division by zero will throw an ArithmeticException, which will be caught in the catch block.
Then, the finally block will be executed.

You might also like