0% found this document useful (0 votes)
12 views20 pages

AJP Unit 1 QB Bank

The document covers advanced Java programming concepts, focusing on Java I/O, multithreading, and reflection. It includes multiple-choice questions and short notes on various topics such as input-output streaming, byte and character streams, and the life cycle of threads. Additionally, it discusses Java streams, their types, and practical applications in file handling and network communication.

Uploaded by

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

AJP Unit 1 QB Bank

The document covers advanced Java programming concepts, focusing on Java I/O, multithreading, and reflection. It includes multiple-choice questions and short notes on various topics such as input-output streaming, byte and character streams, and the life cycle of threads. Additionally, it discusses Java streams, their types, and practical applications in file handling and network communication.

Uploaded by

srnarayanan_slm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

ADVANCED JAVA PROGRAMMING

Unit I
Part I (One Marks)

1. Java I/O is used to process the?

A. input
B. output
C. Both A and B
D. None of the above

2. Can we perform file handling in Java by Java I/O API?

A. TRUE
B. FALSE
C. Can be true or false
D. Can not say

3. In java, how many streams are created for us automatically?

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

4. Which method is used to write a byte to the current output stream?

A. public void write(int)throws IOException


B. public void write(byte[])throws IOException
C. public void flush()throws IOException
D. public void close()throws IOException

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.

9. Which method is used to invoke a method on an object using Java Reflection?


A) invoke()
B) callMethod()
C) execute()
D) run()

10. How method is to be invoked on Unknown object?


A) obj.getClass().getDeclaredMethod()
B)obj.getClass().getDeclaredField()
C) obj.getClass().getMethod()
D) obj.getClass().getObject()

11. What is multithreaded programming?


A) It’s a process in which two different processes run simultaneously
B) It’s a process in which two or more parts of same process run simultaneously
C) It’s a process in which many different process are able to access same information
D) It’s a process in which a single process can access information from many sources
12. Thread priority in Java is?
A) Integer
B) Float
C) double
D) long

13. What is true about threads?


A) Threads consumes CPU in best possible manner
B) Threads enables multi processing.
C) Multi threading reduces idle time of CPU
D) All

14. A thread can acquire a lock by using which reserved keyword?

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

15. Which language is used in the swing framework?

A. JavaScript
B. Java
C. React
D. Python

16. How many types of events are there?

A. 5
B. 3
C. 2
D. 4

17. An ____ is a change in the state of an item?

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

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

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.

2. Explain ByteStream with it classes and description


This is used to process data byte by byte (8 bits). Though it has many classes, the
FileInputStream and the FileOutputStream are the most popular ones. The FileInputStream is
used to read from the source and FileOutputStream is used to write to the destination. Here
is the list of various ByteStream Classes:

Stream class Description

BufferedInputStream It is used for Buffered Input Stream.

DataInputStream It contains method for reading java standard datatypes.

FileInputStream This is used to reads from a file

InputStream This is an abstract class that describes stream input.

BufferedOutputStream This is used for Buffered Output Stream.

DataOutputStream This contains method for writing java standard data types.

FileOutputStream This is used to write to a file.

3. What is CharacterStream and its classes ?

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

BufferedReader It is used to handle buffered input stream.

FileReader This is an input stream that reads from file.

InputStreamReader This input stream is used to translate byte to character.

OutputStreamReader This output stream is used to translate character to byte.

Reader This is an abstract class that define character stream input.

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.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

List<Integer> evenNumbers = numbers.stream()


.filter(n -> n % 2 == 0)
.collect(Collectors.toList());

// Result: [2, 4, 6, 8, 10]

5. What is Stream pipelining in Java give syntax ?

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.

Advantages of Byte Code in Java

 Portability: One of the biggest advantages of Java’s use of bytecode is that it


allows code to run on any platform that has a Java Virtual Machine (JVM)
installed.
 Performance optimization: The JVM can optimize the bytecode for the specific
machine it’s running on, resulting in improved performance compared to the
same code compiled directly to machine code.

7. What is Reflection and use of it ?


Reflection is a feature in the Java programming language. It allows an executing Java
program to examine or "introspect" upon itself, and manipulate internal properties of the
program. For example, it's possible for a Java class to obtain the names of all its members and
display them

Reflection can be used to get the information about :


1. Class : To know the name of the class to which that particular object belongs we can use
the getClass() method.

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.

8. Explain Understanding Dynamic Class Loading: With syntax

Dynamic Reflection in Java: A Deep Dive

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

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.

public class MainClass {

public static void main(String[] args){

ClassLoader classLoader = MainClass.class.getClassLoader();

try {
Class aClass = classLoader.loadClass("com.jenkov.MyClass");
System.out.println("aClass.getName() = " + aClass.getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

Why Use Reflection?

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

9. Write short notes on Java Threads.

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

10. Describe the Life Cycle Of Thread in java.

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

public class GFG {


public static void main(String args[])
{
// Thread object created
// and initiated with data
Thread t = new Thread("Hello Geeks!");

// Thread gets started


t.start();

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

Java I/O 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.

Practical Applications of Java I/O


Java I/O is employed in various real-world scenarios, including:

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) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

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

2. Describe Stream filter() in Java

Stream filter(Predicate predicate) returns a stream consisting of the elements of this


stream that match the given predicate. This is an intermediate operation. These operations
are always lazy i.e, executing an intermediate operation such as filter() does not actually
perform any filtering, but instead creates a new stream that, when traversed, contains the
elements of the initial stream that match the given predicate.

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 {

// Main driver method


public static void main(String[] args)
{
// Creating a stream of strings
Stream<String> stream = Stream.of(
"Geeks", "fOr", "GEEKSQUIZ", "GeeksforGeeks");
// Getting a stream consisting of the
// elements having UpperCase Character
// at custom index say be it '1'
// using Stream filter(Predicate predicate)
stream
.filter(
str -> Character.isUpperCase(str.charAt(1)))
.forEach(System.out::println);
}
}
OutPut : fOr GEEKSQUIZ

3. Discuss the use cases where reflection is particularly beneficial in Java programming.
Highlight both advantages and potential drawbacks.

Reflection can be used to get the information about :

 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: A Deep Dive

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.

Why Use Reflection?

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

3. Complexity & Maintainability


o Code using reflection is harder to read, debug, and maintain compared to regular
Java code.

4. Lack of Compile-Time Safety


o Since reflection bypasses compile-time checks, errors (such as incorrect method
names or field accesses) manifest only at runtime.

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.

5. Illustrate the concept of threading in java and it’s lifecycle.

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:

1. Process-Based Multitasking
2. Thread-Based Multitasking

1. Process-Based Multitasking (Multiprocessing)


In this type of Multitasking, processes are heavyweight and each process was allocated by a
separate memory area. And as the process is heavyweight the cost of communication
between processes is high and it takes a long time for switching between processes as it
involves actions such as loading, saving in registers, updating maps, lists, etc.
2. Thread-Based Multitasking
As we discussed above Threads are provided with lightweight nature and share the same
address space, and the cost of communication between threads is also low.

Life Cycle Of Thread


A thread in Java at any point of time exists in any one of the following states. A thread lies
only in one of the shown states at any instant:
1. New State
2. Runnable State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State

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.

6. Terminated State: A thread terminates because of either of the following reasons:

 Because it exits normally. This happens when the code of the thread has been entirely
executed by the program.

6. Write notes on java swing and its features in detail.


Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

 Swing is a Set Of API ( API- Set Of Classes and Interfaces )


 Swing is Provided to Design Graphical User Interfaces
 Swing is an Extension library to the AWT (Abstract Window Toolkit)
 Includes New and improved Components that have been enhancing the looks and
Functionality of GUIs’
 Swing is more portable and more flexible than AWT, The Swing is built on top of the AWT
 Swing is Entirely written in Java
 Java Swing Components are Platform-independent And The Swing Components are
lightweight

Features Of Swing Class


 Lightweight Components: Swing components have their own view supported by Java’s
look and feel classes.
 Pluggable Look and Feel: The Swing library provides an API that gives real flexibility in
determining the look and feel of the GUI of an application

 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 {

// Main driver method


public static void main(String[] args)
{
JFrame frame
= new JFrame(); // creating instance of JFrame

JButton button = new JButton(


" GFG WebSite Click"); // creating instance of
// JButton
button.setBounds(
150, 200, 220,
50); // x axis, y axis, width, height

frame.add(button); // adding button in JFrame

frame.setSize(500, 600); // 400 width and 500 height


frame.setLayout(null); // using no layout managers
frame.setVisible(true); // making the frame visible
}
}
Output:

You might also like