AJP Unit 1 QB Bank
AJP Unit 1 QB Bank
Unit I
Part I (One Marks)
A. input
B. output
C. Both A and B
D. None of the above
A. TRUE
B. FALSE
C. Can be true or false
D. Can not say
A. 2
B. 3
C. 4
D. 5
Explanation: In Java, 3 streams are created for us automatically. All these streams are attached
with the console.
1. System.out
2. System.in
3. System.err
5. The …………………… package contains a large number of stream classes that provide capabilities for
processing all types of data.
A) java.awt
B) java.io
C) java.util
D) java.net
6. Which of the following method(s) not included in InputStream class.
A) available( )
B) reset( )
C) flush( )
D) close( )
7. The class DataInputStream extends …………………….. and implements the interface DataInput.
A) FileInputStream
B) SequenceInputStream
C) FilterInputStream
D) InputStream
8. Which method is used to get the value of a field using Java Reflection?
A) getValue()
B) getField()
C) readValue()
D) retrieveField()
Explanation: The getValue() method is used to get the value of a field using Java Reflection. This
method is declared in the Field class and can be used to get the value of any field, regardless of
its access level.
A) volatile
B) synchronized
C) locked
D) none
15. Which of the following architecture does the Swing framework use?
A. MVC
B. MVP
C. Layered architecture
D. Master-Slave architecture
A. JavaScript
B. Java
C. React
D. Python
A. 5
B. 3
C. 2
D. 4
A. Spinner
B. Event
C. Occurrence
D. Activity
18. A ____ is the abstract foundation class for SWING's non-menu user interface controls?
A. Container
B. Jcomponent
C. Component
D. JAVA
A. Container
B. Jcomponent
C. Component
D. Python
Part II
1. Write short notes on Input-output Streaming in Java
Java brings various Streams with its I/O package that helps the user to perform all the input-
output operations. These streams support all the types of objects, data-types, characters, files
etc to fully execute the I/O operations.
Before exploring various input and output streams lets look at 3 standard or default
streams that Java has to provide which are also most common in use:
1. System.in: This is the standard input stream that is used to read characters from the
keyboard or any other standard input device.
2. System.out: This is the standard output stream that is used to produce the result of a
program on an output device like the computer screen.
Here is a list of the various print functions that we use to output statements:
print(): This method in Java is used to display a text on the console. This text is passed
as the parameter to this method in the form of String. This method prints the text on
the console and the cursor remains at the end of the text at the console. The next
printing takes place from just here.
DataOutputStream This contains method for writing java standard data types.
In Java, characters are stored using Unicode conventions (Refer this for details). Character
stream automatically allows us to read/write data character by character. Though it has many
classes, the FileReader and the FileWriter are the most popular ones. FileReader and
FileWriter are character streams used to read from the source and write to the destination
respectively. Here is the list of various CharacterStream Classes:
Stream class Description
4. Explain the purpose of the filter operation in Java Streams. Provide an example code
snippet.
Answer: The filter operation in Java Streams is used to selectively include elements in
the stream based on a specified condition. It takes a Predicate as an argument, and only
elements that satisfy the given condition are included in the resulting stream.
Stream pipelining is the concept of chaining operations together. This is done by splitting the
operations that can happen on a stream into two categories. They are "intermediate
operations" and "terminal operations". Each intermediate operation returns an instance of
Stream itself when it runs, an arbitrary number of intermediate operations can, therefore, be
set up to process data forming a processing pipeline. There must then be a terminal operation
which returns a final value and terminates the pipeline.
6. Define Byte code and its advantages.
Byte code is an intermediate code that is created by the compiler after compiling the user-
written code and we can run that intermediate code anywhere with the help of a Java Virtual
machine. Java byte code is a low-level representation of Java code, consisting of a series of
instructions for the JVM to execute.
2. Constructors : To know the public constructors of the class to which that particular
object belongs we can use the getConstructors() method.
3. Methods : To know the public methods of the class to which that particular object
belongs we can use the getMethods() method.
Dynamic reflection in Java is a powerful mechanism that allows you to inspect and manipulate
classes, interfaces, fields, and methods at runtime. It's a bit like examining a running program's
inner workings and making changes on the fly.
Dynamic class reloading is a bit more challenging. Java's builtin Class loaders always checks if a
class is already loaded before loading it. Reloading the class is therefore not possible using Java's
builtin class loaders. To reload a class you will have to implement your own
ClassLoader subclass.
try {
Class aClass = classLoader.loadClass("com.jenkov.MyClass");
System.out.println("aClass.getName() = " + aClass.getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Introspection: Gaining insights into the structure of classes and their members.
Dynamic Instantiation: Creating objects of classes whose names are only known at
runtime.
Method Invocation: Calling methods on objects dynamically, even if their signatures are
not known beforehand.
Field Access: Accessing and modifying fields of objects, regardless of their visibility.
Generic Programming: Writing code that can operate on objects of various types
without explicit type information.
Testing and Debugging: Inspecting objects and their state during testing or debugging.
Threads allows a program to operate more efficiently by doing multiple things at the same time.
Threads can be used to perform complicated tasks in the background without interrupting the
main program.
Typically, we can define threads as a subprocess with lightweight with the smallest unit of
processes and also has separate paths of execution. These threads use shared memory but
they act independently hence if there is an exception in threads that do not affect the
working of other threads despite them sharing the same memory.
The Concept Of Multitasking
To help users Operating System accommodates users the privilege of multitasking, where
users can perform multiple actions simultaneously on the machine. This Multitasking can be
enabled in two ways:
Process-Based Multitasking
Thread-Based Multitasking
There are different states Thread transfers into during its lifetime, let us know about those
states in the following lines: in its lifetime, a thread undergoes the following states, namely:
1. New State - in this state, code has not yet been run and the execution process is not yet
initiated.
2. Active State - when it invokes the start() method, his Active state contains two sub-states
namely: Runnable State, Running State
3. Waiting/Blocked State - If a Thread is inactive but on a temporary time, then either it is a
waiting or blocked state
4. Timed Waiting State - each thread has a time period for which sleep() method is invoked
and after the time expires the Threads starts executing its task.
5. Terminated State - A thread will be in Terminated State
Example
import java.io.*;
import java.util.*;
// getting data of
// Thread through String
String s = t.getName();
System.out.println(s);
}
}
Output
Hello Geeks!
Part III
1. Discuss Types of java streams function with example.
Depending on the type of operations, streams can be divided into two primary
classes:
1. Java provides a rich set of classes for performing I/O operations. Some of the key classes
include:
2. InputStream and OutputStream: These abstract classes form the foundation for byte-
oriented I/O operations. They provide methods for reading and writing bytes from/to
various sources and destinations.
3. Reader and Writer: These abstract classes are used for character-based I/O operations.
They provide methods for reading and writing characters from/to character-based
streams.
4. FileInputStream and FileOutputStream: These classes allow reading from and writing to
files in a byte-oriented manner.
5. FileReader and FileWriter: These classes enable reading from and writing to files using
character-oriented operations.
6. BufferedInputStream and BufferedOutputStream: These classes provide buffering
capabilities, which can significantly improve I/O performance by reducing the number of
system calls.
7. BufferedReader and BufferedWriter: These classes offer buffered reading and writing of
character data, enhancing I/O efficiency when working with character-based streams.
1. File Handling: Java I/O is extensively used for reading from and writing to files.
Developers can manipulate files, create directories, and perform file-related operations
using Java's file I/O classes.
2. Network Communication: Java's socket classes (Socket and ServerSocket) facilitate
network communication by enabling data exchange between client and server
applications over TCP/IP.
3. Serialization: Java's serialization mechanism allows objects to be converted into a
stream of bytes for storage or transmission. It is particularly useful for storing object
state or transferring objects between applications.
4. Data Processing: Java I/O is integral to data processing tasks such as parsing text files,
processing CSV data, and interacting with databases through JDBC (Java Database
Connectivity).
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
1. Input Stream: These streams are used to read data that must be taken as an input from
a source array or file or any peripheral device. For eg., FileInputStream,
BufferedInputStream, ByteArrayInputStream etc.
2. Output Stream: These streams are used to write data as outputs into an array or file or any
output peripheral device. For eg., FileOutputStream, BufferedOutputStream,
ByteArrayOutputStream etc.
3. System.err: standard error stream
Let's see the code to print output and an error message to the console.
Syntax
System.out.println("simple message");
System.err.println("error message");
Syntax:
Stream<T> filter(Predicate<? super T> predicate)
Where Stream is an interface and T is the type of the input to the predicate.
Implementation:
1. Filtering out the elements divisible by some specific number ranging between 0 to 10.
2. Filtering out the elements with an upperCase letter at any specific index.
3. Filtering out the elements ending with custom alphabetical letters.
Example 1: filter() method with the operation of filtering out the elements with an upperCase
letter at index 1.
import java.util.stream.Stream;
// Class
class GFG {
3. Discuss the use cases where reflection is particularly beneficial in Java programming.
Highlight both advantages and potential drawbacks.
Class : To know the name of the class to which that particular object belongs we can use
the getClass() method.
Constructors : To know the public constructors of the class to which that particular
object belongs we can use the getConstructors() method.
Methods : To know the public methods of the class to which that particular object
belongs we can use the getMethods() method.
Dynamic reflection in Java is a powerful mechanism that allows you to inspect and manipulate
classes, interfaces, fields, and methods at runtime. It's a bit like examining a running program's
inner workings and making changes on the fly.
Introspection: Gaining insights into the structure of classes and their members.
Dynamic Instantiation: Creating objects of classes whose names are only known at
runtime.
Method Invocation: Calling methods on objects dynamically, even if their signatures are
not known beforehand.
Field Access: Accessing and modifying fields of objects, regardless of their visibility.
Generic Programming: Writing code that can operate on objects of various types
without explicit type information.
Testing and Debugging: Inspecting objects and their state during testing or debugging.
Advantages of Reflection
1. Flexibility – Enables dynamic behavior, which is crucial for frameworks, libraries, and
runtime configurations.
2. Runtime Inspection – Useful for analyzing class structures, method signatures, and
fields.
3. Extensibility – Supports plugin architectures where new components can be loaded
without modifying the core application.
4. Improved Testing – Allows accessing private members, aiding in comprehensive testing.
Drawbacks of Reflection
1. Performance Overhead
o Reflection operations are slower than direct method calls due to runtime type
resolution and security checks.
2. Security Risks
o It can break encapsulation, potentially leading to security vulnerabilities if
improperly used.
4. Explain the difference between compile-time type information and runtime type information
in Java. How does reflection bridge the gap between them?
Compile-time type information is checked by the compiler and ensures type safety before
the program runs.
Runtime type information allows the program to inspect and manipulate types during
execution.
Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime,
without knowing the names of the classes, methods etc. at compile time. It is also possible to
instantiate new objects, invoke methods and get/set field values using reflection.
Compile Time Run time
In Compile time, the call is resolved by the In Run time, the call is not resolved by the
compiler. compiler.
It is also known as Static binding, Early It is also known as Dynamic binding, Late
binding and overloading as well. binding and overriding as well.
It is achieved by virtual functions and
It is achieved by method overloading
pointers.
It provides fast execution because the It provides slow execution as compare to
method that needs to be executed is known early binding because the method that needs
early at the compile time. to be executed is known at the runtime.
Compile time is less flexible as all things Run time is more flexible as all things execute
execute at compile time. at run time.
Inheritance is not involved. Inheritance is involved.
The required classes for reflection are provided under java.lang.reflect package which
is essential in order to understand reflection. So we are illustrating the package with visual
aids to have a better understanding as follows:
Reflection gives us information about the class to which an object belongs and also the
methods of that class that can be executed by using the object.
Through reflection, we can invoke methods at runtime irrespective of the access specifier
used with them.
Reflection can be used to get information about class, constructors, and methods as depicted
below in tabular format as shown:
The getClass() method is used to get the name of the class to which an object
Class belongs.
The getConstructors() method is used to get the public constructors of the
Constructors class to which an object belongs.
The getMethods() method is used to get the public methods of the class to
Methods which an object belongs.
Threads allows a program to operate more efficiently by doing multiple things at the same
time.
Threads can be used to perform complicated tasks in the background without interrupting the
main program.
Typically, we can define threads as a subprocess with lightweight with the smallest unit of
processes and also has separate paths of execution. These threads use shared memory but
they act independently hence if there is an exception in threads that do not affect the
working of other threads despite them sharing the same memory.
1. Process-Based Multitasking
2. Thread-Based Multitasking
1. New Thread: When a new thread is created, it is in the new state. The thread has not yet
started to run when the thread is in this state.
2. Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a
thread might actually be running or it might be ready to run at any instant of time.
A multi-threaded program allocates a fixed amount of time to each individual thread. Each
and every thread runs for a short while and then pauses and relinquishes the CPU to
another thread so that other threads can get a chance to run.
3. Blocked: The thread will be in blocked state when it is trying to acquire a lock but currently
the lock is acquired by the other thread. The thread will move from the blocked state to
runnable state when it acquires the lock.
4. Waiting state: The thread will be in waiting state when it calls wait() method or join()
method. It will move to the runnable state when other thread will notify or that thread will
be terminated.
5. Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-
out parameter. A thread lies in this state until the timeout is completed or until a
notification is received. For example, when a thread calls sleep or a conditional wait, it is
moved to a timed waiting state.
Because it exits normally. This happens when the code of the thread has been entirely
executed by the program.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Highly customizable – Swing controls can be customized in a very easy way as visual
appearance is independent of internal representation.
Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane,
slider, colorpicker, and table controls.
Example 1: Develop a program using label (swing) to display message “GFG WEB Site Click”
import java.io.*;
import javax.swing.*;
// Main class
class GFG {