0% found this document useful (0 votes)
24 views26 pages

Practice Questions For Java

The document is a practice book for Computer Programming using Java-II, focusing on multithreaded programming concepts. It contains multiple-choice questions (MCQs) related to Java threads, synchronization, and thread behavior. The practice book is intended for reference only and may not fully align with the actual test question paper.
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)
24 views26 pages

Practice Questions For Java

The document is a practice book for Computer Programming using Java-II, focusing on multithreaded programming concepts. It contains multiple-choice questions (MCQs) related to Java threads, synchronization, and thread behavior. The practice book is intended for reference only and may not fully align with the actual test question paper.
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
You are on page 1/ 26

L.J Institute of Engineering and Technology, Ahmedabad.

Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer

UNIT 4- Multithreaded Programming


Select the method that should be overridden to provide thread's behavior D 1 start() resume() runnable() run()
114 4 when Thread class is extended:
115 4 What are Threads? A 1 lightweight process heavyweight process Both none of above
116 4 Multithreading is also called as ____________ C 1 Recurrent Crosscurrent Concurrency Simultaneity
What is the default relation b/w Thread & Runnable? D 1 Thread is child of Runnable Runnable extends Thread Thread extends Runnable Thread implements
117 4
Runnable
Which method is used to get the object of current thread? B 1 Thread.CurrentThread() Thread.currentThread() Thread.liveThread() Thread.getThread()
118 4

119 4 Which method throws InterruptedException A 1 join() start() run() currentThread()

Two threads cannot simultaneously enter into the methods of the same B 1 static synchronized synchronize synchronization
120 4
object if the methods are
121 4 Which mathod is not a part of multi-threading? A 1 Sleep() join() wait() run()

122 4 mathods used for inter thread communication are? D 1 wait() notify() notifyAll() All of the above

Which of these are types of multitasking? C 1 Process based Thread based Process and Thread based None of the mentioned
123 4
If there occurs any exception in thread, then other threads C 1 stop executing gets impacted doesn't gets impacted daemon thread starts
124 4
executing
Which mathod is used to assign name of thread by programmer? D 1 run() start() getName() setName(String s)
125 4
Which of these method waits for the thread to terminate? A 1 join() stop() sleep() isAlive()
126 4
Which of the following method is not available in Thread class? D 1 join() run() sleep() Run()
127 4
Which function of pre defined class Thread is used to check weather C 1 Join() Alive() isAlive() isRunning()
128 4
current thread being checked is still running?
Which of these method is used to tell the calling thread to give up a A 1 wait() sleep() notifyAll() notify()
129 4 monitor and go to sleep until some other thread enters the same
monitor?
What is true about threading? D 1 run() method creates new run() method calls start() run() method can be called start() method creates new
thread method and runs the code directly without start() thread and calls code
130 4 method being called written in run() method

Thread synchronization in a process will be required when D 1 All threads sharing the All threads sharing the All threads sharing the All
131 4 same address space same global variables same files

Which of the following is a correct way to synchronize a method in Java A 1 public synchronized void public void method() { public void synchronized public void method() {
132 4 code? method() { } synchronized { } } method() { } synchronized void() { } }

Answer the Question : start() method is called to ______ ? A 1 Invoke the thread, before Execute the thread which Transit the thread from Transit from runnable to
the run() method is is in 'ready to run' state 'running' to 'ready to run' waiting state
133 4
executed state

134 4 Threads in java share the same memory space and resources. B 1 FALSE TRUE Depends on Compiler Depends on JVM
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
We can create thread in java by B 1 a & b only b & d only a & e only c & e only
a) Implementing Thread Class
b) Implementing Runnable Interface
135 4 c) Implementing Thread Interface
d) Extending Thread class
e) Extending Runnable class

136 4 The tasks or job that thread needs to perform is written inside D 1 inner class Static Block Constructor run()

Which is the correct Thread Class constructor? C 1 A & B only C & D only A & C Only A & D Only
A) Thread(Runnable r)
137 4 B) Thread(Runnable r, Thread t)
C) Thread(Runnable r, String s)
D) Thread(String s, Runnable r)
What is the name of the thread in output of this program? A 1 main java system thread
Class A
{
public static void main(String args[])
138 4 {
Thread t = Thread.currentThread();
System.out.println(t.getName());
}
}
what is output of this code? B 1 Hello Hii HelloHii None of the above
class A extends Thread {
public void run() {
System.out.println("Hello");
}
public void start() {
System.out.println("Hii");
139 4 }
}
class LJU {
public static void main(String[] args) {
A a = new A();
a.start();
}
}
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
what is the output of this code? D 1 Hello Hii HelloHii Error
class A extends Thread {
public void run() {
System.out.println("Hello");
}
public void run(int a) {
System.out.println("Hii");
140 4 }
}
class LJU {
public static void main(String[] args) {
A a = new A();
a.start(10);
}
}
class multithreaded_programing { C 1 Thread[0,main] Thread[t,5,main] Thread[main,5,main] Thread[t1,5,main]
public static void main(String args[]) {
Thread t = Thread.currentThread();
Thread t1 = t;
141 4
System.out.println(t1);
}
}

Assume the following method is properly synchronized and called from a C 1 Two seconds after thread Two seconds after lock B is After thread A is notified After the lock on B is
thread A on an object B: A is notified released or after two seconds. released and after two
142 4 wait(2000); seconds.
After calling this method, when will the thread A become a candidate to
get another turn at the CPU?
Which of these statement is incorrect? D 1 start() method is used to A thread can be formed by A thread can be formed by run() method is used to
begin execution of the a class that extends thread implementing Runnable begin execution of a
143 4 thread class interface only thread before start()
method in special cases

What will be the output of the following code? A 1 0..1..2.. 0..1..2..3.. 1..2..3.. Compilation fails
class LJ extends Thread {
public static void main(String[] args) {
LJ t = new LJ();
Thread x = new Thread(t);
144 4 x.start(); /* Line 7 */
}
public void run() {
for (int i = 0; i < 3; ++i) {
System.out.print(i + ".."); } }
}
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
Which of the following line of code is suitable to start a thread ? C 1 Thread t = new Thread(X); Thread t = new Thread(X); X run = new X(); Thread t = new Thread();
class X implements Runnable t.start(); Thread t = new x.run();
{ Thread(run); t.start();
public static void main(String args[])
{
145 4
/* Missing code? */
}
public void run() {}
}

What will be the output of the follwing code? B 1 Compile time error Run time exception Thread one. Thread two. one. two. Thread
class MyThread extends Thread
{
public static void main(String [] args)
{
MyThread t = new MyThread();
t.start();
146 4 System.out.print("one. ");
t.start();
System.out.print("two. ");
}
public void run() {
System.out.print("Thread ");
}
}
What is output of this code? B 1 Hello Hii HelloHii None of the above
class A extends Thread {
public void run() {
System.out.println("Hello");
}
public void run(int a) {
System.out.println("Hii");
147 4 }
}
class LJU {
public static void main(String[] args) {
A a = new A();
a.run(10);
}
}
What is the difference between synchronized methods and synchronized C 1 Synchronized methods can Synchronized methods are Synchronized blocks can There is no difference
blocks in Java? be used on non-static less efficient than be used to synchronize between synchronized
methods, while synchronized blocks access to specific parts of a methods and synchronized
148 4 synchronized blocks can method, while blocks
only be used on static synchronized methods lock
methods the entire method
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
What is the output? C 1 ONE TWO main No Output
class TestDemo{
public static void main(String args[])
{
Thread t = new Thread(“ONE”);
149 4 Thread t2 = new Thread(“TWO”);
Thread t3 = Thread.currentThread();
System.out.println(t3.getName());
}
}

class newthread extends Thread { C 1 TRUE FALSE Main thread interrupted None of the mentioned
Thread t;
String name;
newthread(String threadname) {
name = threadname;
t = new Thread(this, name);
t.start(); }
public void run() {}
}
class LJ {
public static void main(String args[]) {
newthread obj1 = new newthread("one");
150 4 newthread obj2 = new newthread("two");
try {
obj1.t.wait();
System.out.print(obj1.t.isAlive());
} catch (Exception e) {
System.out.print("Main thread interrupted");
}
}
}

what is output of Below Java Programs? A 1 Thread is running no Thread is running no Thread is running no None of the above
public class ThreadExtended extends Thread { Thread is running no Thread is running no
public void run() { Thread is running no
System.out.println("Thread is running no");
}
public static void main(String[] args)
151 4 {
ThreadExtended threadE = new ThreadExtended();
ThreadExtended threadEx = new ThreadExtended();
ThreadExtended threadEx1 = new ThreadExtended();
threadEx.start();
}
}
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
what is output of Below Java Programs? D 1 4 2 Thread-0 Thread-1
public class ThreadExtended extends Thread {
public void run() {
System.out.println(ThreadExtended.currentThread().getName());
}
public static void main(String[] args)
{
152 4 ThreadExtended threadE = new ThreadExtended();
ThreadExtended threadEx = new ThreadExtended();
ThreadExtended threadEx1 = new ThreadExtended();
threadEx.start();
}
}

The static method Thread.currentThread() returns a reference to the D 1 Each String in the array Each String in the array Each String in the array This code will not compile.
currently executing Thread object. What is the result of this code? lines will output, and there lines will output, with no lines will output, with a 1-
class Test { is no guarantee there will pause in between because second pause.
public static void main(String [] args) { be a pause because this method is not
printAll(args); currentThread() may not executed in a Thread.
} retrieve this thread.
public static void printAll(String[] lines) {
153 4 for(int i = 0; i < lines.length; i++)
{
System.out.println(lines[i]);
Thread.currentThread().sleep(1000);
}
}
}

What is the output of the following code? B 1 HelloHi Hi Hello compile time error output will be different
every time
class LJU extends Thread {

public void run(){


System.out.print(“Hi ”);
}
154 4 }
class Test{
public static void main(String args[]) {
LJU lj = new LJU();
lj.run();
System.out.println(“Hello”);
}
}
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
What will be the output of the following code? B 1 Compile time error 0 1 0 0 null null
class One extends Thread {
public void run(){
for(int i=0; i<2; i++)
{
System.out.print(i+" ");
}
}
}
155 4 class Test{
public static void main(String args[])
{
Test t = new Test();
One o = new One();
t.call(o);
}
public void call(One o) {
o.start();
}}

What will be the output of the following code? A 1 LJU “LJU” LJ No Output
class LJ extends Thread {
public void run() {
try {
Thread.sleep( 'a' );
} catch (Exception e) {
e.printStackTrace();
}
System.out.print("LJ"); } }
156 4 class runLJ {
synchronized public static void main(String[] args) throws Exception {
LJ t1 = new LJ( );
t1.start();
synchronized(t1) {
t1.wait();
}
System.out.println("U"); } }
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
What will be the output of the following code? D 1 Q100 70Q100 a3 100
class LJIET extends Thread {
public void runn() {
System.out.print('A' + 5);
display();
}
static void display() {
157 4 System.out.print("Q");
}}
class runLJ {
public static void main(String[] args) throws Exception {
LJIET t1 = new LJIET( );
t1.start(); t1.join();
System.out.println('a' + 3);
}}
What will be the output of the following code? A 1 mAB ABm XAB Compile time error
class thread implements Runnable {
static Thread m;
public void run(){
try {
m.join( ); }
catch ( Exception e ) {
158 4 System.out.print("X"); }
System.out.print("AB"); } }
class runLJ {
public static void main(String[] args) throws Exception {
Thread t1 = new Thread( new thread ( ) , "Y");
thread.m = Thread.currentThread();
t1.start(); t1.join(1000);
System.out.print("m"); } }
What is the output of the Java code snippet? C 1 pop pop pop pop push push Compile Error Runtime Exception
class Thread implements Runnable {
public static void main(String[] args) {
Thread t = new Thread();
t.start();
}
public void run() {
159 4 for (int i = 0; i < 2; ++i) {
System.out.print("pop "); }
}
public void run(int number) {
for (int i = 0; i < number; ++i) {
System.out.print("push "); }
}}
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
What is the output of the Java code snippet? B 1 main Thread-0 Compile Error Runtime Exception

class Test extends Thread {


public sta c void main(String[] args) throws InterruptedExcep on {
new Thread (new Test( ),"true").start( );
}
160 4
synchronized public void run( ){
Thread.currentThread( ).setName("TRUE");
System.out.print(this.getName( ));
}
}

What is the output of the Java code snippet? A 1 Sleep Join Sleep Compile Error Runtime Exception
class Wait extends Thread implements Runnable {
public static void main(String[] args) {
Wait run = new Wait();
Thread stop =new Thread(run);
run.start();
}
161 4 public void run( ){
System.out.print("Join ");
}
public void start( ){
System.out.print("Sleep ");
}
}

Write an application that creates and starts three threads. Each thread is 3
instantiated from the
same class. It executes a loop with 10 iterations. Each iteration displays
162 4 string "HELLO",
sleeps for 300 milliseconds. The application waits for all the threads to
complete & displays
the message "Good Bye..."
Write a program to create a child thread to print integer numbers 1 to 10 3
163 4
Write a program to create two threads, one thread will check whether 3
164 4 given number is prime or not and second thread will print prime numbers
between 0 to 100
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
It's IPL 2023 time. In this process of IPL-23 there is a thread called Bowler. 5
This Bowler is going to create two threads with name – “Yorker” and
“googly”.
Write a java program to perform following task with each thread.
Task 1 : if the thread name is "yorker" then it should print "SIXER"
Task 2 : if the thread name is "googly" then it should print "WICKET"
Make sure first thread bowl must be yorker. When execution of first
165 4 thread is completed then and only then second bowl googly should work.
Hint: Here Bowler is a Thread Class. and It must have execution of SIXER
AND WICKET. Both yorker and googly must be from Bowler Thread Only.
Give name IPL to the class of Main method.

Write an application that executes two threads. One thread displays 5


"Good Morning" every
166 4 1000 milliseconds & another thread displays "Good Afternoon" every
3000 milliseconds for 10 times..
Create the threads by implementing the Runnable interface.
Write a program to create two threads, one thread will print odd 4
167 4 numbers and second thread will print even numbers between 1 to 100
numbers
Write a complete multi-threaded program to meet following 5
requirements:
o Two threads of same type are to be instantiated in the method main.
o Each thread acts as a producer as well as a consumer.
o A shared buffer can store only one integer information along with the
source &
168 4 destination of the information at a time.
o The information produced is to be consumed by appropriate consumer.
o Both producers produce information for both consumers.
o Each thread produces 5 information.

Create PaymentThread class by extending Thread and Make a program to 5


169 4 count payments of 10 tickets each of 100 rs. Display total using main
thread.
Write a multithreaded program to print all odd positive numbers in 5
ascending order up to n, where n is a positive integer number given as a
command line argument. Instantiate requited number of threads, where
170 4
each thread except the last, examines next 50 numbers and the last
thread examines remaining numbers up to n
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
Write an application that read limit from user and executes two threads. 4
One thread displays total of first n even numbers & another thread
171 4 displays total of first n odd numbers. Create the threads by implementing
the Runnable interface

Write a program to create two thread one display alphabet from a to z 3


172 4 and other will display numbers from 1 to 100

write a program that demonstrates the prodecer consumer concept in 4


173 4 detail.
Explain the concept of Syncronization by taking suitable example. 4
174 4

Write a complete multi-threaded program to meet following 4


requirements:
- Read matrix [A] m x n
- Create m number of threads
175 4 - Each thread computes summation of elements of one row, i.e. ith row of
the matrix is processed by ith thread. Where 0 <= i< m.
- Print the results

Create a program for class PVR having Total_seats as instance 6


variable.Create method for seat booking.Create two threads which try to
176 4 book seat of PVR screen1 (common object). Use concept of
synchronization.
Make caller thread by extending thread class which calls synchronized 6
receiver method available in receiver class. Make two threads of Caller
and display message "Ringing" and thread name according to thread.
177 4
Thread name must be Caller1 and Caller2.

Implement a Prime Number Finder 5


Write a Java program to implement a prime number finder that checks if
a given number is prime or not in a separate thread. The program should
use the join() method to wait for all the threads to finish, and the isAlive()
method to check if a thread is still running.
To solve this problem, you can create a prime number finder thread that
implements the Runnable interface and checks if a given number is prime
178 4
or not. You can then create multiple instances of the prime number finder
thread and start them using separate threads. The main thread can use
the join() method to wait for all the threads to finish, and the isAlive()
method to check if a thread is still running.
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
Problem Statement: Implement a Bank Account 5

Write a Java program to implement a bank account that allows multiple


threads to deposit and withdraw money from the same account. The
problem requires synchronization between the threads to prevent race
conditions and ensure that the balance is accurate.
179 4 To solve this problem, you can create a BankAccount class that has a
balance variable and synchronized methods for depositing and
withdrawing money. You can then create multiple threads that use the
deposit and withdraw methods to modify the account balance.

UNIT 5- Collection-Part 1
Which of these class object can be used to form a dynamic array? B 1 Array ArrayList & Vector Both Only Vector Only ArrayList
180 5
What does get(int index) method define by List interface do ? C 1 stores an object at the delete the object at returns the object at returns the object at
181 5 specified index specified index specified index specified index and
modifies it’s value
What will be the output of the following code? C 1 Saha Rahul Compile time error Runtime error

import java.util.ArrayList;
class IPL{
public static void main(String args[])
{
ArrayList<String> gt1 = new ArrayList<String>();
182 5
gt1.addList(“Hardik”);
gt1.addList(“Saha”);
gt1.addList(“Rahul”);
gt1.remove(2);
System.out.println(gt1.get(1));
} }

What is the output of the following code? D 1 Compile time error [A, B, null] [A, B] [A, B, A, null]

import java.util.ArrayList;
import java.util.List;

public class Test {


183 5 public static void main(String[] args) {
List<String> al = new ArrayList<String>();
al.add("A");
al.add("B");
al.add("A");
al.add(null);
System.out.println(al); } }
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
What is the output of the following code? C 1 [A, B] [P, Q] [A, B, P, Q] [P, Q, A, B]
import java.util.ArrayList;
import java.util.List;

public class Test {


public static void main(String[] args) {

184 5 List<String> al1 = new ArrayList<String>();


al1.add("A");
al1.add("B");
List<String> al2 = new ArrayList<String>();
al2.add("P");
al2.add("Q");
al1.addAll(al2);
System.out.println(al1); } }
What is the output of the code ? A 1 [A, Z, B, C, V] [A, B, C, Z, V] [Z, A, B, V, C] None of these
import java.util.ArrayList;
import java.util.List;

public class Test {


public static void main(String[] args) {
185 5
List<String> al = new ArrayList<String>();
al.add("A");
al.add("B");
al.add("C");
al.add(1, "Z");
al.add(4, "V");
System.out.println(al); } }
What is the output? D 1 [A, V] [A, null, null, null, V] [A, 0, 0, 0, V] IndexOutOfBoundsExcetpti
import java.util.ArrayList; on
import java.util.List;

public class Test {


186 5 public static void main(String[] args) {
List<String> al = new ArrayList<String>();
al.add("A");
al.add(4, "V");
System.out.println(al);
} }
Which of these method of ArrayList class is used to obtain present size of A 1 size() contains() capacity() length()
187 5
an object?
188 5 Arraylist, Linkedlist and Vector are __________ A 1 classes interfaces packages methods
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
What is the output of the Java code snippet? B 1 [YES, NO] [YES, NO, 10] [10, YES, NO] [YES]
import java.util.*;
class New {
public static void main(String[] args) {
ArrayList a1 = new ArrayList(50);
a1.addAll(Arrays.asList("YES", "NO"));
189 5
ArrayList<Integer> a2 = new ArrayList<Integer>(a1);
a2.add(10);
System.out.print(a2);
}
}
190 5 In Java, the underlying data structure for the LinkedList class is? B 1 Singly linked list Doubly linked list Circular linked list None of these
191 5 LinkedList class implements? C 1 List interface Deque interface both List & Deque Vector & Stack
interface
What is the output? C 1 [100, 220, 50, 100, 50, [100, 220, 50, null] [100, 220, 50, null, 100, 50, None of these
import java.util.LinkedList; 100] 100, null]
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Integer> ll = new LinkedList<Integer>();
ll.add(100);
192 5 ll.add(220);
ll.add(50);
ll.add(null);
ll.add(100);
ll.add(50);
ll.add(100);
ll.add(null);
System.out.println(ll); } }
What is the output? C 1 [100, 220, 50, 100, 50] [999, 100, 220, 50, 888] [999, 100, 220, 50, 100, [999, 100, 220, 50, 100,
import java.util.LinkedList; 50, 888] 50, 888,null]

public class Test {


public static void main(String[] args) {
LinkedList<Integer> ll = new LinkedList<Integer>();
ll.add(100);
193 5
ll.add(220);
ll.add(50);
ll.add(100);
ll.add(50);
ll.addFirst(999);
ll.addLast(888);
System.out.println(ll); } }
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
What is the output of following code snippet? C 1 [D, A, B, F, C, E] [D, A, B, C, F, E] [D, A, F, B, C, E] [D, A, B, C, E, F]
LinkedList<String> list = new LinkedList<String>();
list.add("A");
list.add("B");
list.add("C");
194 5
list.addFirst("D");
list.addLast("E");
list.add(2, "F");
System.out.println(list);

What is the output of following code snippet? C 1 3 1 2 4

LinkedList<Integer> list1 = new LinkedList<Integer>();


list1.add(1);
list1.add(2);
195 5 LinkedList<Integer> list2 = new LinkedList<Integer>();
list2.add(3);
list2.add(4);
list1.addAll(1, list2);
System.out.println(list1.get(3));

Which of the following methods is used to get the last element of a A 1 getLast() getLastNode() getLastElement() getFirst()
196 5
LinkedList in Java?
Collection is ______________ and Collections is ____________. A 1 Interface and class class and Interface In built framework & class and class
197 5
interface
What does the frequency() method of the Collections class do? A 1 Returns the number of Returns the number of Returns the number of None of the above
198 5 occurrences of an element occurrences of an element occurrences of an element
in a List in a Set in a Map
What is the output of the following code snippet? C 1 5 1 8 3
List<Integer> list = new ArrayList<Integer>();
list.add(5);
list.add(3);
199 5 list.add(8);
list.add(1);
Collections.sort(list);
System.out.println(Collections.max(list));
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
What will be the output of the following code? C 1 55 5 0707 50101505
import java.util.*;
class xyz
{
public static void main(String[] args)
{
ArrayList a = new ArrayList(Arrays.asList(5 , 0 , 10 , 7 , 15 , 0 , 5 , 7));
200 5 Iterator i = a.iterator();
while(i.hasNext())
{
if( ( int ) i.next() % 5 == 0)
System.out.print( i.next());
}
}}

Which of the following is a valid way to reverse the order of the elements C 1 list.reverse() reversed(list) Collections.reverse(list) collections.reverse(list)
201 5
of a List using the Collections class?
Which of the following is a valid way to find the smallest element in a List A 1 Collections.min(list) list.min() Collections.minimum(list) list.minimum()
202 5
using the Collections class?
Which of the following is a valid way to find the frequency of an element C 1 Collections.count(list, list.count(element) Collections.frequency(list, list.frequency(element)
203 5
in a List using the Collections class? element) element)
Which of these methods is used to add elements in vector at specific A 1 add() set() AddElement() addElement()
204 5
location?
What is the correct syntax to declare a vector in Java? A 1 Vector vec = new Vector(); Vector vec[]; Vector vec = {1, 2, 3}; None of the above.
205 5
Which method is used to add an element to the end of a vector? A 1 add() insert() push() append()
206 5
207 5 What is the default capacity of a vector in Java? B 1 50 10 100 20
What is the correct syntax to create a vector of Strings in Java? A 1 Vector vec = new vector<String> vec = new vector vec = new Vector(); None of the above.
208 5
Vector<String>(); Vector();
Which of the following methods is used to insert an element at a specific B 1 add() set() addAll() setAll()
209 5
index in a vector?
Which is not correct way to get the last element of a vector in Java? A 1 vec.get(0) vec.get(vec.size() - 1) vec.lastElement() vec.elementAt(vec.size() -
210 5
1)
What is the output of the following code snippet? B 1 1 2 3 4

Vector<Integer> vec = new Vector<Integer>();


211 5 vec.add(1);
vec.add(2);
vec.add(3);
System.out.println(vec.get(1));
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
What is the output of the following code ? D 1 [3, 2, 6] [3, 2, 6, 6] [3, 2, 6, 8] [3, 2, 8, 6]

import java.util.*;
class vector
{
public static void main(String args[])
{
212 5 Vector obj = new Vector();
obj.addElement(new Integer(3));
obj.addElement(new Integer(2));
obj.addElement(new Integer(6));
obj.insertElementAt(new Integer(8), 2);
System.out.println(obj);
} }

What is the output of the following code snippet? A 1 1 2 3 -1


Vector<Integer> vec = new Vector<Integer>();
vec.add(1);
213 5 vec.add(2);
vec.add(3);
vec.add(2);
System.out.println(vec.indexOf(2));
What is the output of the following code snippet? C 1 Java Python C++ null
Vector<String> vec = new Vector<String>();
vec.add("Java");
214 5
vec.add("Python");
vec.add("C++");
System.out.println(vec.get(2));
What is the output of the following code snippet? C 1 1 2 3 null
Vector<Integer> vec = new Vector<Integer>();
vec.add(1);
215 5 vec.add(2);
vec.add(3);
vec.remove(1);
System.out.println(vec.get(1));
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
What is the output of the following code snippet? B 1 10 20 14 13
Vector<Integer> vec = new Vector<Integer>();
vec.add(1);
vec.add(2);
vec.add(3);
vec.add(1);
vec.add(2);
216 5 vec.add(1);
vec.add(2);
vec.add(1);
vec.add(2);
vec.add(1);
vec.add(2);
vec.add(1);
vec.add(2); System.out.println(vec.capacity());
What will be the output of the following code? C 1 240 3920 280 null40
import java.util.*;
class xyz {
public static void main(String[] args) {
Vector s = new Vector ();
for(int i =0 ; i < 39 ; i++)
{
217 5 s.add(i);
}
s.add(2);
s.add(null);
System.out.print(s.get(39));
System.out.println(s.capacity());
}
}
What is the output of the Java code snippet? D 1 17[2, 0, 2, null, Easy] 17[2, 0, LJ, 2, null, Easy] Compile Error Runtime Exception
import java.util.*;
class Test {
public static void main(String[] args) {
Vector v = new Vector<>(Arrays.asList(2, "LJ", 'h', 2, null));
v.add("Easy");
218 5
v.add(1, 0);
v.remove('h');
System.out.print(v.capacity() + v.size());
System.out.print(v);
}
}
219 5 Stack class is designed for ? A 1 FILO Order FIFO ORDER LILO ORDER None of the above
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
What will be the output of the following code? D 1 Kotlin Java Kotlin Java null Compile time error Exception at run time
import java.util.Stack;

public class Test {


public static void main(String[] args) {

220 5 Stack<String> st = new Stack<String>();


st.push("Java");
st.push("Kotlin");
System.out.println( st.pop() + " " + st.pop() + " " + st.pop() );
}
}

What is the output of the following? C 1 [50] [100, 50, 200, 220, 50] [100, 50, 220, 50] [220, 50]
import java.util.Stack;
public class Test {
public static void main(String[] args) {
Stack<Integer> st = new Stack<Integer>();
st.add(100);
st.push(50);
221 5 st.add(200);
st.pop();
st.add(220);
st.push(50);
System.out.println(st);
} }

What is the output of the following code? A 1 true false false true true true false false
import java.util.Stack;

public class Test {


public static void main(String[] args) {
222 5 Stack<String> st = new Stack<String>();
System.out.print(st.isEmpty() + " ");
st.push("Java");
st.push("Kotlin");
System.out.println(st.isEmpty());
} }
What is the output? B 1 10 3 -1 0 -1 30
import java.util.Stack;
public class Test {
public static void main(String[] args) {
Stack<String> st = new Stack<String>();
223 5 st.push("Java");
st.push("Kotlin");
st.push("Python");
System.out.println(st.search("Java")
+ " " + st.search("SQL"));
} }
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
import java.util.*; A 1 [3, 5] [3, 5, 2] [3, 5, 2, null] [3, 2, 5]
class stack
{
public static void main(String args[])
{
Stack obj = new Stack();
224 5
obj.push(new Integer(3));
obj.push(new Integer(2));
obj.pop();
obj.push(new Integer(5));
System.out.println(obj);
} }
What is the output of the following code? A 1 02 01 compile time error run time error
import java.util.Stack;
class TestDemo2{
public static void main(String[] args) {
Stack s1 = new Stack();
System.out.print(s1.size()+" ");
s1.push("Hello");
225 5 s1.push(20.23);
s1.push("JJS");
s1.peek();
s1.peek();
s1.peek();
s1.pop();
System.out.println(s1.size());
} }
What will be the output of the following code? D 1 10 31 13 -1 -1
import java.util.*;

class xyz {
public static void main(String[] args) {
Stack<String> st = new Stack<String>();
226 5 st.push("Java");
st.push("Kotlin");
st.push("Python");
System.out.println(st.search("java") + " " + st.search("SQL"));
}
}

Write a program in which create two ArrayList. Add odd numbers 2


between 1 to 10 in one arraylist and even numbers between 1 to 10 in
227 5 another arraylist. Now merge these two ArrayList and sort them in
descending order. At last print this sorted ArrayList.

Write a Java program to create a new array list, add some colors (string) 3
228 5 and print out the collection
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
Write a Java program that creates an ArrayList<Student> to store a name 3
and marks of 3 students. Then sort the ArrayList by student marks in
descending order. Then print arraylist using iterator. Add these details of
3 Students in arraylist in given sequence:
Devarsh (18.5 marks), Viraj (20.5 marks) and Nidhi (17.5 marks)
229 5
Desired Output:
Name=Viraj, Marks=20.5
Name=Devarsh, Marks=18.5
Name=Nidhi, Marks=17.5

Write a Java program to remove duplicates from an ArrayList as per given 3


input and output. Take main class 'Exam'. Create ArrayList: [1, 2, 3, 4, 4, 5,
6, 7, 8, 9, 6, 9, 1, 1, 10] in main method then you need to implement
another method named 'removeDuplicate' that takes an ArrayList as an
argument , removes all duplicates and returns an ArrayList without
230 5
duplicates. At end print that Arraylist from main method. (No need to use
Scannner)

Output of your code should be:- [2, 3, 5, 7, 8, 10]

Remove Duplicates from an ArrayList 4


Write a Java program to remove duplicates from an ArrayList. You need
231 5 to implement a function that takes an ArrayList as input and returns an
ArrayList with duplicates removed.
Merge two sorted ArrayLists 4
Write a Java program to merge two sorted ArrayLists into a single sorted
232 5 ArrayList. You need to implement a function that takes two sorted
ArrayLists as input and returns a single sorted ArrayList containing all the
elements.
Write a Java program to copy one array list into another. & sort the 5
233 5 second arraylist & search an element in a array list
Problem Statement: Employee Management System 5
Implement an employee management system in Java using ArrayList and
a class. The system should have the following functionalities:

Add an employee to the system


Remove an employee from the system
Update an employee's details
234 5 Display all employees in the system
To implement this system, you can create an Employee class with
attributes such as name, age, salary, etc. Then, you can create an
ArrayList to store all the employees. You can then implement functions to
add, remove, update and display employees.
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
Write a Java program that creates an ArrayList to store a list of students 6
and their grades. The program should provide the following functionality:
Add a student: The program should prompt the user for a student name
and their grade, and add the student to the ArrayList.
Remove a student: The program should prompt the user for a student
name and remove the corresponding entry from the ArrayList.
Search for a student: The program should prompt the user for a student
name and output their corresponding grade. If the student name is not
found in the ArrayList, the program should output an error message.
Sort students by name: The program should sort the ArrayList by student
name in ascending order.
Sort students by grade: The program should sort the ArrayList by student
grade in descending order.
To accomplish these tasks, you can use the following Collections class
methods:
235 5 addAll(collection, elements): Adds all elements from one collection to
another. sort(list): Sorts the elements in a list in natural order.
sort(list, comparator): Sorts the elements in a list using a custom
comparator. reverse(list): Reverses the order of the elements in a list.
You can also use the following ArrayList methods:
add(element): Adds an element to the end of the ArrayList.
remove(element): Removes the first occurrence of an element from the
ArrayList. get(index): Returns the element at the specified index in the
ArrayList. size(): Returns the number of elements in the ArrayList.

Problem Statement: Library Management System 7


You are required to design a library management system in Java using
ArrayList. The system should have the following classes:
Book - This class should contain the following attributes: bookId,
bookName, author, and quantity. It should also have a method to display
book details.
User - This class should contain the following attributes: userId,
236 5 userName, and booksIssued. It should also have methods to display user
details and to issue/return a book.
Library - This class should contain an ArrayList to store all the books and
an ArrayList to store all the users. It should have methods to add/remove
books and users, to display all books/users, to issue/return a book, and to
display all books issued by a particular user.

Write a Java program to insert the specified element at the specified 3


237 5 position in the linked list.
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
Write a Java program to get the first and last occurrence of the specified 3
238 5 elements in a linked list.
Write a Java program to clone an linked list to another linked list. 3
239 5

Write a Java program to append the specified element to the end of a 4


240 5 linked list & Write a Java program to iterate through all elements in a
linked list.
Problem Statement: Implement a Phone Book 7
Write a Java program to implement a phone book using an ArrayList and a
LinkedList. The phone book should allow users to add, delete, and search
for contacts by name or phone number.
241 5 To solve this problem, you can create a Contact class that stores the name
and phone number of each contact. You can then use an ArrayList to store
the contacts and a LinkedList to store the indices of the contacts sorted by
name.

I have an Induction machine manufacturing company. My Manager wants 5


to analyze some data of the induction machines of our manufacturing
unit.
What I have: List of machine's price. Note: each price is in Double.
Write a java program that contains list of various machine's price. & do
the following tasks.
242 5
Task 1 - Create a list of 5 machine's price.
[10000.0,55000.0,80000.0,25000.0,55000.0]
Task 2 - Find the maximum price from the list.
Task 3 - sort the list.

Write a program that contains Stack of 3 items. First insert 3 items in 4


243 5 stack. Then do pop operation 2 times. and print the stack.

Problem Statement: Balanced Parentheses 5


Given a string containing only parentheses, determine if it is balanced. A
string is considered balanced if every opening parenthesis has a
corresponding closing parenthesis, and they are properly nested.
You need to implement a function that takes a string as input and returns
true if the string is balanced and false otherwise.
244 5 HINT: To solve this problem, you can use a stack to keep track of the
opening parentheses and pop them off the stack when a closing
parenthesis is encountered. If at any point the stack is empty when a
closing parenthesis is encountered or if the top of the stack doesn't match
the current closing parenthesis, then the string is not balanced.
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
Write a Java program to sort a stack of Student objects by their GPA. You 5
need to implement a function that takes a stack of Student objects as
input and returns a new stack with the Students sorted in descending
order of their GPA.
245 5
To solve this problem, you can create a Student class with attributes such
as name, id, and GPA. You can then create a stack of Student objects and
implement a function to sort the stack by their GPA.

TOPIC NAME:- 9 marks (PROGRAMS)


Create a Java program for a Quiz game consisting of 5 Multiple Choice
Questions (MCQs) with 3 participants. Each participant will be
represented by the "Participant" class, which will have attributes such as
"name," "age," and "contactNumber".

To ensure the correctness of the contact number, implement a validation


check. If a participant enters a contact number that is not 10 digits long or
does not start with '9', display a message stating "Wrong number" and
prompt the participant to enter the correct contact number. This
validation check should continue until the participant enters a valid 10-
digit contact number starting with '9'.

Create objects of the "Participant" class and store them in an ArrayList.


This ArrayList will hold all the participant objects participating in the quiz.

Use a Stack data structure to store the correct answers to all 5 MCQs.
Each answer should be represented as a character in the stack. This stack
will serve as the reference for evaluating the participants' answers. The
correct answer sequence is as follows: A, B , A , D , C.

Create a thread for each participant using Java's threading mechanism.


Each thread will represent an individual participant . The participant with
the lowest age should be given the chance to answer all 5 questions first
using scanner class. At a time only one participant can give answer of
Questions.

During the quiz, the participant's answers should be stored in an


ArrayList. This ArrayList will hold the participant's submitted answers.

246 4,5 After all participants have submitted their answers, calculate and display 9
each participant's score. The score should be calculated by comparing
each participant's submitted answers (ArrayList) with the correct answers
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer
each participant's submitted answers (ArrayList) with the correct answers
(Stack). Award 1 point for each correct answer and calculate the total
score for each participant out of 5.

Finally, declare the winner based on the participant with the highest
score. In case of tie, younger participant will be declared as winner.

Below is the list of 5 Questions which is asked in Quiz.


Q.1. National bird of INDIA..(A) Peacock (B) Sparrow (C) Duck (D) Owl
Q.2 Independence year of INDIA..(A) 1955 (B) 1947 (C) 1999 (D) 1929
Q.3 Gandhi Jayanti is on......(A) 2nd Oct (B) 5th Oct (C) 9th Oct (D) 7th Oct
Q.4 Count of states in INDIA..(A) 17 (B) 21 (C) 25 (D) 28
Q.5 how many continents are there in the world..(A) 5 (B) 6 (C) 7 (D) 8
Answers: A, B , A , D , C

Filename: ConsProd.java
You are tasked with implementing a multi-threaded program in Java that
simulates the Consumer Producer problem. In this problem, you have a
shared buffer between a consumer and a producer. The producer
generates data and puts it into the buffer, while the consumer retrieves
data from the buffer.

Shared Buffer: Implement a SharedBuffer class. This class represents the


shared resource between the producer and consumer threads. It should
support operations for putting data into the buffer (one at a time by
producer) and retrieving data from the buffer (one at a time by
consumer). It has a value(int) field and isReady(boolean) field indicating
whether the value is ready to be consumed or not. The produce() method
sets the value and notifies the consumer, while the consume() method
consumes the value and notifies the producer.
L.J Institute of Engineering and Technology, Ahmedabad.
Computer Programming using Java-II PRACTICE BOOK (SEM-II-EVEN_2025-CE RELATED BRANCHES)

Note : This PRACTICE BOOK is only for reference purpose. LJU Test question paper may not be completely set from this PRACTICE BOOK.

Unit MCQ
Sr No Question_Text Marks Option A Option B Option C Option D
Number Answer

Producer: Create a Producer thread class that generates data items and
puts them into the buffer. It repeatedly produces (total 5) values and
sleeps for 1 second between each production. The producer should wait if
the buffer is full.

Consumer: Create a Consumer thread class that retrieves data items from
the buffer. It repeatedly consumes the produced value (total 5) and sleeps
for 1 second between each consumption.The consumer should wait if the
buffer is empty.

Main Class (ConsProd): This is the entry point of the program. Create an
247 4,5 9
object of the SharedBuffer class and two threads - one for the producer
and one for the consumer. Then start both threads to achieve goal.
Sample output: (assume above mentioned delay between each
production and each consumption)

Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4
Produced: 5
Consumed: 5

Properly do use of synchronization in methods of the SharedBuffer class


to ensure thread safety, and wait() and notify() methods for coordinating
between the producer and consumer threads.

You might also like