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

Advanced Java I/O Streaming Guide

The document provides an overview of Advanced Java Programming, focusing on Java I/O streaming, byte code interpretation, interfaces, threading, and Swing. It explains the types of streams, filtering and pipelining streams, and the lifecycle of threads, emphasizing the efficiency of multithreading. Additionally, it highlights the advantages of Swing over AWT for developing graphical user interfaces in Java applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views23 pages

Advanced Java I/O Streaming Guide

The document provides an overview of Advanced Java Programming, focusing on Java I/O streaming, byte code interpretation, interfaces, threading, and Swing. It explains the types of streams, filtering and pipelining streams, and the lifecycle of threads, emphasizing the efficiency of multithreading. Additionally, it highlights the advantages of Swing over AWT for developing graphical user interfaces in Java applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CS2210501- ADVANCED JAVA PROGRAMMING


UNIT-I - INTRODUCTION

Java I/O streaming – filter and pipe streams – Byte Code interpretation - interfaces - Threading –
Swing.

JAVA I/O STREAMING

Java provides 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.

The image below demonstrates the flow of data from a source to a destination.

Standard or Default Streams in Java


Before exploring various input and output streams, let's look at 3 standard or default streams that
Java has to provide, which are also most commonly used:
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

● [Link]: This is the standard input stream ([Link]) that is used to read characters from
the keyboard or any other standard input device.
● [Link]: This is the standard output stream ([Link]) that is used to produce the result
of a program on an output device like the computer screen.

Types of Streams
Depending on the type of operations, streams can be divided into two primary classes:
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.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

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.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Types of Streams Depending on the Types of File

Depending on the types of file, Streams can be divided into two primary classes which can be
further divided into other classes as can be seen through the diagram below followed by the
explanations.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

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

Stream class Description

Buffered Input Stream It is used for Buffered Input Stream.

Data Input Stream It contains method for reading java standard datatypes.

File Input Stream This is used to reads from a file

Input Stream This is an abstract class that describes stream input.

Print Stream This contains the most used print() and println() method

Buffered Output Stream This is used for Buffered Output Stream.

Data Output Stream This contains method for writing java standard data types.

File Output Stream This is used to write to a file.

Output Stream This is an abstract class that describe stream output.

2. CharacterStream: 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:


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

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.

PrintWriter This contains the most used print() and println() method

Writer This is an abstract class that define character stream output.

BufferedWriter This is used to handle buffered output stream.

FileWriter This is used to output stream that writes to file.

FILTER AND PIPE STREAMS

Java streams provide powerful mechanisms for filtering and processing data through
pipelines. Here's a breakdown of how you can filter and pipe streams:

Filtering Streams
The filter() method is used to select elements from a stream that match a given condition. It takes
a Predicate as an argument, which is a functional interface that returns a boolean value.
import [Link];

import [Link];

import [Link];

public class StreamFilterExample {

public static void main(String[] args) {


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

// Filter out even numbers

List<Integer> oddNumbers = [Link]()

.filter(n -> n % 2 != 0)

.collect([Link]());

[Link]("Odd numbers: " + oddNumbers); // Output: Odd numbers: [1, 3, 5, 7,


9]

// Filter numbers greater than 5

List<Integer> greaterThanFive = [Link]()

.filter(n -> n > 5)

.collect([Link]());

[Link]("Numbers greater than 5: " + greaterThanFive);

Output:

Numbers greater than 5: [6, 7, 8, 9, 10]

Pipelining Streams
Stream operations can be chained together to form a pipeline. Each intermediate operation
returns a new stream, allowing you to perform multiple transformations on the data.
import [Link];

import [Link];

import [Link];

public class StreamPipelineExample {


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

public static void main(String[] args) {

List<String> names = [Link]("Alice", "Bob", "Charlie", "David", "Eve");

List<String> longNamesUpperCase = [Link]()

.filter(name -> [Link]() > 4) // Filter names longer than 4 characters

.map(String::toUpperCase) // Convert to uppercase

.collect([Link]());

[Link]("Long names in uppercase: " + longNamesUpperCase);

Output:

Long names in uppercase: [ALICE, CHARLIE, DAVID]

Key Concepts
● Intermediate Operations:
Operations like filter() and map() return a new stream, allowing for chaining. They are lazy,
meaning they are not executed until a terminal operation is called.
● Terminal Operations:
Operations like collect() or forEach() produce a result or a side-effect, triggering the processing
of the stream.
● Laziness:
Stream operations are performed only when necessary, optimizing performance.
Filter Streams ([Link])
In addition to the stream API, Java also has FilterInputStream and FilterOutputStream for
manipulating data at the I/O level. These streams can be chained to modify data as it is read or
written.
import [Link].*;

public class FilterStreamExample {


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

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

try (FileInputStream fileIn = new FileInputStream("[Link]");

BufferedInputStream bufferIn = new BufferedInputStream(fileIn);

DataInputStream dataIn = new DataInputStream(bufferIn)) {

int data = [Link]();

[Link]("Read int: " + data);

}}

BYTE CODE INTERPRETATION


Byte Code
Byte Code can be defined as an intermediate code generated by the compiler after the
compilation of source code(JAVA Program). This intermediate code makes Java a platform-
independent language.
How is Byte Code generated?
Compiler converts the source code or the Java program into the Byte Code(or machine code),
and secondly, the Interpreter executes the byte code on the system. The Interpreter can also be
called JVM(Java Virtual Machine). The byte code is the common piece between the
compiler(which creates it) and the Interpreter (which runs it).
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Bytecode interpretation in Java refers to how the Java Virtual Machine (JVM) executes compiled
Java code. When you compile a Java program, the compiler doesn't produce native machine code
directly executable by the processor. Instead, it generates an intermediate form called
bytecode. This bytecode is a set of instructions specific to the JVM.

Here's how the interpretation process works:


● Compilation:
The Java compiler converts the source code (.java files) into bytecode (.class files).
● Loading:
When you run a Java program, the JVM loads the bytecode from the .class files.
● Verification:
The JVM verifies the bytecode to ensure it is valid and safe to execute. This step helps prevent
security issues.
● Interpretation:
The JVM's interpreter reads the bytecode instructions one by one.
● Execution:
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

For each bytecode instruction, the interpreter performs the corresponding action on the
underlying hardware. This includes memory allocation, calculations, method calls, and other
operations.
The JVM's interpreter acts as a bridge between the platform-independent bytecode and the
specific hardware and operating system it's running on. This allows Java programs to be
platform-independent, meaning they can run on any system with a compatible JVM, without
recompilation.

While interpretation is a straightforward way to execute bytecode, it can be slower than


executing native machine code directly. To improve performance, modern JVMs often use Just-
In-Time (JIT) compilation, which compiles frequently executed bytecode into native code during
runtime, leading to faster execution.

INTERFACES
An Interface in Java programming language is defined as an abstract type used to specify the
behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains
static constants and abstract methods.

import [Link].*;
// Interface Declared
interface testInterface {
// public, static and final
final int a = 10;
// public and abstract
void display();
}
// Class implementing interface
class TestClass implements testInterface {
// Implementing the capabilities of
// Interface
public void display(){
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

[Link]("Geek");
}
}
class Geeks
{
public static void main(String[] args)
{
TestClass t = new TestClass();
[Link]();
[Link](t.a);
}
}
Output
Geek
10
Java Interfaces and Classes: Similarities and Differences

Similarities

An interface is similar to a class in the following ways −

● An interface can contain any number of methods.


● An interface is written in a file with a .java extension, with the name of the interface matching
the name of the file.
● The byte code of an interface appears in a .class file.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

● Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.

Declaring an Interface in Java

The interface keyword is used to declare an interface. Here is a simple example to declare an
interface −

Example to Declare a Java Interface

Following is an example of an interface −


/* File name : [Link] */
import [Link].*;
// Any number of import statements

public interface NameOfInterface {


// Any number of final, static fields
// Any number of abstract method declarations\
}
Propeties of Java Interface
Interfaces have the following properties −

● An interface is implicitly abstract. You do not need to use the abstract keyword while declaring
an interface.
● Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

● Methods in an interface are implicitly public.

Rules for implementing Java Interfaces

When implementation interfaces, there are several rules −

● A class can implement more than one interface at a time.


● A class can extend only one class, but implement many interfaces.
● An interface can extend another interface, in a similar way as a class can extend another class.

THREADING

Java threads are lightweight subprocesses, representing the smallest unit of execution with
separate paths. The main advantage of multiple threads is efficiency (allowing multiple things at
the same time). For example, in MS Word, one thread automatically formats the document while
another thread is taking user input. Additionally, multithreading ensures quick response, as other
threads can continue execution even if one gets stuck, keeping the application responsive.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

As shown in the above diagram, a thread runs inside the process, and there will be context-based
switching between threads. There can be multiple processes running in an OS, and each process
can have multiple threads running simultaneously. The Multithreading concept is popularly
applied in games, animation, etc.

Concept of Multitasking
To help users, the operating system provides users with 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 is 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


During its lifetime, a thread transitions through several states, they are:

1. New State
2. Active State
3. Waiting/Blocked State
4. Timed Waiting State
5. Terminated State
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Common Methods:
● start(): Starts the execution of a thread.
● run(): Contains the code that will be executed by the thread.
● sleep(): Pauses the thread for a specified amount of time.
● join(): Waits for a thread to complete its execution.
● isAlive(): Checks if a thread is still running.
● wait(), notify(), notifyAll(): Used for thread synchronization.
Thread Priorities:
● Threads have priorities ranging from MIN_PRIORITY (1) to MAX_PRIORITY (10),
with NORM_PRIORITY (5) as the default.
● Higher-priority threads are given preference by the operating system's scheduler.
Types of Threads:
● User Threads: Threads created by the application.
● Daemon Threads: Background threads that support user threads and terminate when all user
threads have finished.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Important Considerations:
● Thread Safety: Ensure that shared resources are accessed and modified in a thread-safe manner
using synchronization mechanisms.
● Deadlocks: Be aware of potential deadlocks when multiple threads are waiting for each other to
release resources.
● Context Switching: The overhead of switching between threads can impact performance.
class MyRunnable implements Runnable {
@Override
public void run() {
[Link]("Thread is running: " + [Link]().getName());
}
}

public class Main {


public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread1 = new Thread(myRunnable);
Thread thread2 = new Thread(myRunnable);
[Link]();
[Link]();
}
}
output
Thread is running: Thread-1
Thread is running: Thread-0

SWING
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window
Toolkit [AWT]. Java Swing offers much-improved functionality over AWT, new components,
expanded components features, and excellent event handling with drag-and-drop support.

Introduction of Java Swing


Swing has about four times the number of User Interface [UI] components as AWT and is part of
the standard Java distribution. By today's application GUI requirements, AWT is a limited
implementation, not quite capable of providing the components required for developing complex
GUIs required in modern commercial applications. The AWT component set has quite a few
bugs and does take up a lot of system resources when compared to equivalent Swing resources.
Netscape introduced its Internet Foundation Classes [IFC] library for use with Java. Its Classes
became very popular with programmers creating GUI's for commercial applications.
● 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 can be used to build (Develop) The Standalone swing GUI Apps as Servlets and
Applets
● It Employs model/view design architecture.
● 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.
● Swing Supports a Pluggable look and feel and Swing provides more powerful components.
● such as tables, lists, Scrollpanes, Colourchooser, tabbed pane, etc.
● Further Swing Follows MVC.

Difference between Java Swing and Java AWT


There are certain points from which Java Swing is different than Java AWT as mentioned below:
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Java AWT Java Swing

Java AWT is an API to develop GUI Swing is a part of Java Foundation Classes
applications in Java. and is used to create various applications.

The components of Java Swing are


Components of AWT are heavy weighted.
lightweight.

Components are platform dependent. Components are platform independent.

Execution Time is more than Swing. Execution Time is less than AWT.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Java AWT Java Swing

AWT components require [Link] Swing components requires [Link]


package. package.

Features Of Swing Class


● Pluggable look and feel.
● Uses MVC architecture.
● Lightweight Components
● Platform Independent
● Advanced features such as JTable, JTabbedPane, JScollPane, etc.
● Java is a platform-independent language and runs on any client machine, the GUI look and
feel, owned and delivered by a platform-specific O/S, simply does not affect an application's
GUI constructed using Swing components.

● Lightweight Components: Starting with the JDK 1.1, its AWT-supported lightweight
component development. For a component to qualify as lightweight, it must not depend on
any non-Java [O/s based) system classes. Swing components have their own view supported
by Java's look and feel classes.
● Pluggable Look and Feel: This feature enable the user to switch the look and feel of Swing
components without restarting an application. The Swing library supports components' look
and feels that remain the same across all platforms wherever the program runs. 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.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Swing Classes Hierarchy

// Java program using label (swing)

// to display the message “GFG WEB Site Click”

import [Link].*;

import [Link].*;

// Main class

class GFG {

// Main driver method

public static void main(String[] args)

// Creating instance of JFrame

JFrame frame = new JFrame();

// Creating instance of JButton


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

JButton button = new JButton(" GFG WebSite Click");

// x axis, y axis, width, height

[Link](150, 200, 220, 50);

// adding button in JFrame

[Link](button);

// 400 width and 500 height

[Link](500, 600);

// using no layout managers

[Link](null);

// making the frame visible

[Link](true);

Swing vs. JavaFX:


While Swing has been a popular choice for Java GUI development, JavaFX is now considered
the more modern and recommended option for new projects. JavaFX offers more advanced
features, better performance, and a more visually appealing user interface. Swing is still used in
legacy applications and for simpler GUI needs.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

JAVAFX (creating and delivering desktop applications and rich internet applications (RIAs) that can run
on various devices EX. Mobile Applications, Rich Internet Applications (RIAs), Desktop
Applications)

You might also like