SlideShare a Scribd company logo
JAVA (UNIT 3)
BY:SURBHI SAROHA
SYLLABUS
• Input/Output Programming: Basics
• Streams
• Byte and Character Stream
• Predefined streams
• Reading and writing from console and files
• Networking: Basics
Cont….
• Networking classes and interfaces
• Using java.net package
• Doing TCP/IP and Data-gram programming.
Input/Output Programming: Basics
• Java input and output is an essential concept while working on java programming.
• It consists of elements such as input, output and stream. The input is the data that
we give to the program.
• The output is the data what we receive from the program in the form of result.
• Stream represents flow of data or the sequence of data.
• To give input we use the input stream and to give output we use the output stream.
How input is read from the Keyboard?
• The “System.in” represents the keyboard.
• To read data from keyboard it should be connected to “InputStreamReader”.
• From the “InputStreamReader” it reads data from the keyboard and sends
the data to the “BufferedReader”.
• From the “BufferedReader” it reads data from InputStreamReader and stores
data in buffer.
• It has got methods so that data can be easily accessed.
Reading Input from Console
• Input can be given either from file or keyword. In java, input can be read
from console in 3 ways:
• BufferedReader
• StringTokenizer
• Scanner
BufferedReader – Java class
• Here, we use the class “BufferedReader” and create the object “bufferedreader”. We also
take integer value and fetch string from the user.
• BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in));
• int age = bufferedreader.read();
• String name = bufferedreader.readLine();
• From the eclipse window we also see an example of the same in the following code:
• Bufferedreader bufferedreader = new BufferedReader(
• New InputStreamReader(System.in));
• System.out.println(“enter name”);
CONT…..
• String name = bufferedreader.readline();
• System.out.println(“enter age”);
• int age = Integer.parseInt(bufferedreader.readline());
• int age1= bufferedreader.read();
• System.out.println(“I am” + name + “ “+age+”years old”);
• }
• }
String Tokenizer – Java class
• It can be used to accept multiple inputs from console in a single line where as
BufferedReader accepts only one input from a line. It uses delimiter (space, comma) to make
the input into tokens.
• The syntax is as follows:
• BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in));
• String input = bufferedreader.readline();
• StringTokenizer tokenizer = new StringTokenizer(input, “,”);
• String name = tokenizer.nextToken();
• int age=tokenizer.nextToken();
CONT….
• Once we enter eclipse and open the program, we view the code:
• BufferedReader bufferedreader = new BufferedReader(
• New InputStreamReader(System.in);
• System.out.println(“Enter your name and age separated by comma”);
• String Input = bufferedreader.readLine();
• StringTokenizer tokenizer = new StringTokenizer(Input, “,”);
CONT….
• String name = Tokenizer.newToken();
• int age = Integer.parseInt(tokenizer.nextToken());
• System.out.println(“I am”+name+age+”years old”);
• }
• }
Scanner – Java class
• It accepts multiple inputs from file or keyboard and divides into tokens. It has
methods to different types of input (int, float, string, long, double, byte) where
tokenizer does not have.
• The syntax is denoted below :
• Scanner scanner = new Scanner(System.in);
• int rollno = scanner.nextInt();
• String name = scanner.next();
• In the Eclipse window we view the following code:
CONT….
• Scanner.scanner = new Scanner (System.in);
• System.out.println(“Enter your name and age”);
• String name = scanner.next();
• int age=scanner.nextInt();
• System.out.println(“ I am “ “+name” “+age+” years old”);
• }
• }
Streams
• Introduced in Java 8, Stream API is used to process collections of objects. A stream
in Java is a sequence of objects that supports various methods which can be
pipelined to produce the desired result.
• Use of Stream in Java
• There uses of Stream in Java are mentioned below:
• Stream API is a way to express and process collections of objects.
• Enable us to perform operations like filtering, mapping,reducing and sorting.
How to Create Java Stream?
• Java Stream Creation is one of the most basic steps before considering the
functionalities of the Java Stream. Below is the syntax given on how to
declare Java Stream.
• Syntax
• Stream<T> stream;
• Here T is either a class, object, or data type depending upon the declaration.
Java Stream Features
• The features of Java stream are mentioned below:
• A stream is not a data structure instead it takes input from the Collections,
Arrays or I/O channels.
• Streams don’t change the original data structure, they only provide the result
as per the pipelined methods.
• Each intermediate operation is lazily executed and returns a stream as a
result, hence various intermediate operations can be pipelined. Terminal
operations mark the end of the stream and return the result.
Byte and Character Stream
• Character Stream
• In Java, characters are stored using Unicode conventions.
• Character stream automatically allows us to read/write data character by character.
• For example, FileReader and FileWriter are character streams used to read from the
source and write to the destination.
•
Byte Stream
• Byte streams process data byte by byte (8 bits).
• For example, FileInputStream is used to read from the source and
FileOutputStream to write to the destination.
Predefined streams
• All Java programs automatically import the java.lang package.
• This package defines a class called System, which encapsulates several aspects of the run-
time environment.
• Among other things, it contains three predefined stream variables, called in, out, and err.
These fields are declared as public, final, and static within System. This means that they
can be used by any other part of your program and without reference to a
specific System object.
• System.out refers to the standard output stream. By default, this is the
console. System.in refers to standard input, which is by default the
keyboard. System.err refers to the standard error stream, which is also the console by
default.
Predefined streams
Program to show use of System.in of Java
Predefined Streams
• import java.io.*;
• class InputEg
• {
• public static void main( String args[] ) throws IOException
• {
• String city;
• BufferedReader br = new BufferedReader ( new InputStreamReader
(System.in) );
Cont……
• System.out.println ( “Where do you live?" );
• city = br.readLine();
• System.out.println ( “You have entered " + city + " city" );
• }
• }
Java Predefined Stream for Standard Error
• System.err is the stream used for standard error in Java. This stream is an object
of PrintStream stream.
• System.err is similar to System.out but it is most commonly used inside the catch section of
the try / catch block. A sample of the block is as follows:
• try {
• // Code for execution
• }
• catch ( Exception e) {
• System.err.println ( “Error in code: ” + e );
Reading and writing from console and files
• By default, to read from system console, we can use the Console class. This class provides
methods to access the character-based console, if any, associated with the current Java
process. To get access to Console, call the method System.console().
• Console gives three ways to read the input:
• String readLine() – reads a single line of text from the console.
• char[] readPassword() – reads a password or encrypted text from the console with echoing
disabled
• Reader reader() – retrieves the Reader object associated with this console. This reader is
supposed to be used by sophisticated applications. For example, Scanner object which
utilizes the rich parsing/scanning functionality on top of the underlying Reader.
1.1. Reading Input with readLine()
• Console console = System.console();
• if(console == null) {
• System.out.println("Console is not available to current JVM process");
• return;
• }
• String userName = console.readLine("Enter the username: ");
• System.out.println("Entered username: " + userName);
1.2. Reading Input with readPassword()
• Console console = System.console();
• if(console == null) {
• System.out.println("Console is not available to current JVM process");
• return;
• }
• char[] password = console.readPassword("Enter the password: ");
• System.out.println("Entered password: " + new String(password));
1.3. Read Input with reader()
• Console console = System.console();
• if(console == null) {
• System.out.println("Console is not available to current JVM process");
• return;
• }
• Reader consoleReader = console.reader();
• Scanner scanner = new Scanner(consoleReader);
CONT…..
• System.out.println("Enter age:");
• int age = scanner.nextInt();
• System.out.println("Entered age: " + age);
• scanner.close();
2. Writing Output to Console
• The easiest way to write the output data to console is System.out.println()
statements. Still, we can use printf() methods to write formatted text to
console.
• 2.1. Writing with System.out.println
• System.out.println("Hello, world!");
2.2. Writing with printf()
• The printf(String format, Object... args) method takes an output string and
multiple parameters which are substituted in the given string to produce the
formatted output content.
• This formatted output is written in the console.
• String name = "Lokesh";
• int age = 38;
• console.printf("My name is %s and my age is %d", name, age);
Networking: Basics
• The working of Computer Networks can be simply defined as rules or protocols which help in sending and
receiving data via the links which allow Computer networks to communicate.
• Each device has an IP Address, that helps in identifying a device.
• Network: A network is a collection of computers and devices that are connected together to enable
communication and data exchange.
• Nodes: Nodes are devices that are connected to a network. These can include computers, Servers,
Printers, Routers, Switches, and other devices.
• Protocol: A protocol is a set of rules and standards that govern how data is transmitted over a network.
Examples of protocols include TCP/IP, HTTP, and FTP.
• Topology: Network topology refers to the physical and logical arrangement of nodes on a network. The
common network topologies include bus, star, ring, mesh, and tree.
CONT…..
• Service Provider Networks: These types of Networks give permission to take Network
Capacity and Functionality on lease from the Provider. Service Provider Networks include
Wireless Communications, Data Carriers, etc.
• IP Address: An IP address is a unique numerical identifier that is assigned to every device on a
network. IP addresses are used to identify devices and enable communication between them.
• DNS: The Domain Name System (DNS) is a protocol that is used to translate human-readable
domain names (such as www.google.com) into IP addresses that computers can understand.
• Firewall: A firewall is a security device that is used to monitor and control incoming and
outgoing network traffic. Firewalls are used to protect networks from unauthorized access and
other security threats.
Networking classes and interfaces
• When computing devices such as laptops, desktops, servers, smartphones, and
tablets and an eternally-expanding arrangement of IoT gadgets such as cameras,
door locks, doorbells, refrigerators, audio/visual systems, thermostats, and various
sensors are sharing information and data with each other is known as networking.
• What is Java Networking?
• Networking supplements a lot of power to simple programs. With networks, a
single program can regain information stored in millions of computers positioned
anywhere in the world. Java is the leading programming language composed from
scratch with networking in mind. Java Networking is a notion of combining two or
more computing devices together to share resources.
Java Networking classes
• The java.net package of the Java programming language includes various
classes that provide an easy-to-use means to access network resources. The
classes covered in the java.net package are given as follows –
• CacheRequest – The CacheRequest class is used in java whenever there is a
need to store resources in ResponseCache. The objects of this class provide
an edge for the OutputStream object to store resource data into the cache.
CONT….
• CookieHandler – The CookieHandler class is used in Java to implement a callback mechanism
for securing up an HTTP state management policy implementation inside the HTTP protocol
handler. The HTTP state management mechanism specifies the mechanism of how to make
HTTP requests and responses.
• CookieManager – The CookieManager class is used to provide a precise implementation of
CookieHandler. This class separates the storage of cookies from the policy surrounding
accepting and rejecting cookies. A CookieManager comprises a CookieStore and a CookiePolicy.
• DatagramPacket – The DatagramPacket class is used to provide a facility for the connectionless
transfer of messages from one system to another. This class provides tools for the production of
datagram packets for connectionless transmission by applying the datagram socket class.
CONT….
• InetAddress – The InetAddress class is used to provide methods to get the IP address of any hostname. An
IP address is expressed by a 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6
addresses.
• Server Socket – The ServerSocket class is used for implementing system-independent implementation of
the server-side of a client/server Socket Connection. The constructor for ServerSocket class throws an
exception if it can’t listen on the specified port. For example – it will throw an exception if the port is
already being used.
• Socket – The Socket class is used to create socket objects that help the users in implementing all
fundamental socket operations. The users can implement various networking actions such as sending, reading
data, and closing connections. Each Socket object built using java.net.Socket class has been connected
exactly with 1 remote host; for connecting to another host, a user must create a new socket object.
CONT…
• InetAddress – The InetAddress class is used to provide methods to get the IP address of any hostname. An
IP address is expressed by a 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6
addresses.
• Server Socket – The ServerSocket class is used for implementing system-independent implementation of
the server-side of a client/server Socket Connection. The constructor for ServerSocket class throws an
exception if it can’t listen on the specified port. For example – it will throw an exception if the port is
already being used.
• Socket – The Socket class is used to create socket objects that help the users in implementing all
fundamental socket operations. The users can implement various networking actions such as sending, reading
data, and closing connections. Each Socket object built using java.net.Socket class has been connected
exactly with 1 remote host; for connecting to another host, a user must create a new socket object.
CONT….
• URLConnection – The URLConnection class in Java is an abstract class
describing a connection of a resource as defined by a similar URL. The
URLConnection class is used for assisting two distinct yet interrelated
purposes. Firstly it provides control on interaction with a server(especially an
HTTP server) than a URL class. Furthermore, with a URLConnection, a user
can verify the header transferred by the server and can react consequently. A
user can also configure header fields used in client requests using
URLConnection.
Java Networking Interfaces
• The java.net package of the Java programming language includes various
interfaces also that provide an easy-to-use means to access network
resources. The interfaces included in the java.net package are as follows:
• CookiePolicy – The CookiePolicy interface in the java.net package provides
the classes for implementing various networking applications. It decides
which cookies should be accepted and which should be rejected. In
CookiePolicy, there are three pre-defined policy implementations, namely
ACCEPT_ALL, ACCEPT_NONE, and ACCEPT_ORIGINAL_SERVER.
CONT…..
• CookieStore – A CookieStore is an interface that describes a storage space for cookies.
CookieManager combines the cookies to the CookieStore for each HTTP response and
recovers cookies from the CookieStore for each HTTP request.
• FileNameMap – The FileNameMap interface is an uncomplicated interface that
implements a tool to outline a file name and a MIME type string. FileNameMap charges a
filename map ( known as a mimetable) from a data file.
• SocketOption – The SocketOption interface helps the users to control the behavior of
sockets. Often, it is essential to develop necessary features in Sockets. SocketOptions allows
the user to set various standard options.
CONT…..
• SocketImplFactory – The SocketImplFactory interface defines a factory for
SocketImpl instances. It is used by the socket class to create socket
implementations that implement various policies.
• ProtocolFamily – This interface represents a family of communication
protocols. The ProtocolFamily interface contains a method known as name(),
which returns the name of the protocol family.
Using java.net package
JAVA (UNIT 3)
JAVA (UNIT 3)
Doing TCP/IP and Data-gram programming.
• TCP/IP-style networking provides a serialized, predictable, reliable stream of packet
data. This is not without its cost, however.
• TCP includes algorithms for dealing with congestion control on crowded networks,
as well as pessimistic expectations about packet loss.
• This leads to inefficient way to transport data.
• Clients and servers that communicate via a reliable channel, such as a TCP socket,
have a dedicated point-to-point channel between themselves. To communicate, they
establish a connection, transmit the data, and then close the connection. All data
sent over the channel is received in the same order in which it was sent. This is
guaranteed by the channel.
Datagram
• A datagram is an independent, self-contained message sent over the network whose
arrival, arrival time, and content are not guaranteed.
• Datagrams plays a vital role as an alternative.
• Datagrams are bundles of information passed between machines. Once the
datagram has been released to its intended target, there is no assurance that it will
arrive or even that someone will be there to catch it.
• Likewise, when the datagram is received, there is no assurance that it hasn’t been
damaged in transit or that whoever sent it is still there to receive a response and it is
crucial point to note.
// Java program to illustrate
datagrams
import java.net.*;
class WriteServer {
// Specified server port
public static int serverPort = 998;
// Specified client port
public static int clientPort = 999;
public static int buffer_size = 1024;
public static DatagramSocket ds;
// an array of buffer_size
public static byte buffer[] = new byte[buffer_size];
Cont….
// Function for server
public static void TheServer() throws Exception
{
int pos = 0;
while (true) {
int c = System.in.read();
switch (c) {
case -1:
// -1 is given then server quits and returns
System.out.println("Server Quits.");
return;
case 'r':
break; // loop broken
case 'n':
// send the data to client
Cont….
ds.send(new DatagramPacket(buffer, pos,
InetAddress.getLocalHost(), clientPort));
pos = 0;
break;
default:
// otherwise put the input in buffer array
buffer[pos++] = (byte)c;
}
}
}
// Function for client
public static void TheClient() throws Exception
{
while (true) {
Cont….
// first one is array and later is its size
DatagramPacket p = new DatagramPacket(buffer, buffer.length);
ds.receive(p);
// printing the data which has been sent by the server
System.out.println(new String(p.getData(), 0, p.getLength()));
}
}
// main driver function
public static void main(String args[]) throws Exception
{
// if WriteServer 1 passed then this will run the server function
// otherwise client function will run
if (args.length == 1) {
ds = new DatagramSocket(serverPort);
TheServer();
}
Cont….
else {
ds = new DatagramSocket(clientPort);
TheClient();
}
}
}
THANK YOU 
Ad

More Related Content

Similar to JAVA (UNIT 3) (20)

Java I/O
Java I/OJava I/O
Java I/O
Jayant Dalvi
 
FILE OPERATIONS.pptx
FILE OPERATIONS.pptxFILE OPERATIONS.pptx
FILE OPERATIONS.pptx
DeepasCSE
 
7 streams and error handling in java
7 streams and error handling in java7 streams and error handling in java
7 streams and error handling in java
Jyoti Verma
 
Java sockets
Java socketsJava sockets
Java sockets
Stephen Pradeep
 
Unit 4 - Javadfjjjjjjjjjjjjjjjaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa IO.pdf
Unit 4 - Javadfjjjjjjjjjjjjjjjaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa IO.pdfUnit 4 - Javadfjjjjjjjjjjjjjjjaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa IO.pdf
Unit 4 - Javadfjjjjjjjjjjjjjjjaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa IO.pdf
kassyemariyam21
 
Java I/O
Java I/OJava I/O
Java I/O
Jussi Pohjolainen
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
HindAlmisbahi
 
Oodp mod4
Oodp mod4Oodp mod4
Oodp mod4
cs19club
 
U-III Prt-2.pptx0 for Java and hardware coding...
U-III Prt-2.pptx0 for Java and hardware coding...U-III Prt-2.pptx0 for Java and hardware coding...
U-III Prt-2.pptx0 for Java and hardware coding...
zainmkhan20
 
Java Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O MechanismsJava Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O Mechanisms
Subhadra Sundar Chakraborty
 
iostream_fstream_intro.ppt Upstream iostream
iostream_fstream_intro.ppt Upstream iostreamiostream_fstream_intro.ppt Upstream iostream
iostream_fstream_intro.ppt Upstream iostream
pradyumna68
 
Files io
Files ioFiles io
Files io
Narayana Swamy
 
OOPs & C++(UNIT 5)
OOPs & C++(UNIT 5)OOPs & C++(UNIT 5)
OOPs & C++(UNIT 5)
Dr. SURBHI SAROHA
 
13 file handling in C++.pptx oops object oriented programming
13 file handling in C++.pptx oops object oriented programming13 file handling in C++.pptx oops object oriented programming
13 file handling in C++.pptx oops object oriented programming
archana22486y
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
 
Wk_10_Scanner and BufferedReader Class in Java.pptx
Wk_10_Scanner and BufferedReader Class in Java.pptxWk_10_Scanner and BufferedReader Class in Java.pptx
Wk_10_Scanner and BufferedReader Class in Java.pptx
percivalfernandez2
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
Gera Paulos
 
Os lectures
Os lecturesOs lectures
Os lectures
Adnan Ghafoor
 
Java input
Java inputJava input
Java input
Jin Castor
 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
Ravi Chythanya
 
FILE OPERATIONS.pptx
FILE OPERATIONS.pptxFILE OPERATIONS.pptx
FILE OPERATIONS.pptx
DeepasCSE
 
7 streams and error handling in java
7 streams and error handling in java7 streams and error handling in java
7 streams and error handling in java
Jyoti Verma
 
Unit 4 - Javadfjjjjjjjjjjjjjjjaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa IO.pdf
Unit 4 - Javadfjjjjjjjjjjjjjjjaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa IO.pdfUnit 4 - Javadfjjjjjjjjjjjjjjjaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa IO.pdf
Unit 4 - Javadfjjjjjjjjjjjjjjjaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa IO.pdf
kassyemariyam21
 
U-III Prt-2.pptx0 for Java and hardware coding...
U-III Prt-2.pptx0 for Java and hardware coding...U-III Prt-2.pptx0 for Java and hardware coding...
U-III Prt-2.pptx0 for Java and hardware coding...
zainmkhan20
 
iostream_fstream_intro.ppt Upstream iostream
iostream_fstream_intro.ppt Upstream iostreamiostream_fstream_intro.ppt Upstream iostream
iostream_fstream_intro.ppt Upstream iostream
pradyumna68
 
13 file handling in C++.pptx oops object oriented programming
13 file handling in C++.pptx oops object oriented programming13 file handling in C++.pptx oops object oriented programming
13 file handling in C++.pptx oops object oriented programming
archana22486y
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
SadhilAggarwal
 
Wk_10_Scanner and BufferedReader Class in Java.pptx
Wk_10_Scanner and BufferedReader Class in Java.pptxWk_10_Scanner and BufferedReader Class in Java.pptx
Wk_10_Scanner and BufferedReader Class in Java.pptx
percivalfernandez2
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
Gera Paulos
 

More from Dr. SURBHI SAROHA (20)

Deep learning(UNIT 3) BY Ms SURBHI SAROHA
Deep learning(UNIT 3) BY Ms SURBHI SAROHADeep learning(UNIT 3) BY Ms SURBHI SAROHA
Deep learning(UNIT 3) BY Ms SURBHI SAROHA
Dr. SURBHI SAROHA
 
MOBILE COMPUTING UNIT 2 by surbhi saroha
MOBILE COMPUTING UNIT 2 by surbhi sarohaMOBILE COMPUTING UNIT 2 by surbhi saroha
MOBILE COMPUTING UNIT 2 by surbhi saroha
Dr. SURBHI SAROHA
 
Mobile Computing UNIT 1 by surbhi saroha
Mobile Computing UNIT 1 by surbhi sarohaMobile Computing UNIT 1 by surbhi saroha
Mobile Computing UNIT 1 by surbhi saroha
Dr. SURBHI SAROHA
 
DEEP LEARNING (UNIT 2 ) by surbhi saroha
DEEP LEARNING (UNIT 2 ) by surbhi sarohaDEEP LEARNING (UNIT 2 ) by surbhi saroha
DEEP LEARNING (UNIT 2 ) by surbhi saroha
Dr. SURBHI SAROHA
 
Introduction to Deep Leaning(UNIT 1).pptx
Introduction to Deep Leaning(UNIT 1).pptxIntroduction to Deep Leaning(UNIT 1).pptx
Introduction to Deep Leaning(UNIT 1).pptx
Dr. SURBHI SAROHA
 
Cloud Computing (Infrastructure as a Service)UNIT 2
Cloud Computing (Infrastructure as a Service)UNIT 2Cloud Computing (Infrastructure as a Service)UNIT 2
Cloud Computing (Infrastructure as a Service)UNIT 2
Dr. SURBHI SAROHA
 
Management Information System(Unit 2).pptx
Management Information System(Unit 2).pptxManagement Information System(Unit 2).pptx
Management Information System(Unit 2).pptx
Dr. SURBHI SAROHA
 
Searching in Data Structure(Linear search and Binary search)
Searching in Data Structure(Linear search and Binary search)Searching in Data Structure(Linear search and Binary search)
Searching in Data Structure(Linear search and Binary search)
Dr. SURBHI SAROHA
 
Management Information System(UNIT 1).pptx
Management Information System(UNIT 1).pptxManagement Information System(UNIT 1).pptx
Management Information System(UNIT 1).pptx
Dr. SURBHI SAROHA
 
Introduction to Cloud Computing(UNIT 1).pptx
Introduction to Cloud Computing(UNIT 1).pptxIntroduction to Cloud Computing(UNIT 1).pptx
Introduction to Cloud Computing(UNIT 1).pptx
Dr. SURBHI SAROHA
 
JAVA (UNIT 5)
JAVA (UNIT 5)JAVA (UNIT 5)
JAVA (UNIT 5)
Dr. SURBHI SAROHA
 
DBMS (UNIT 5)
DBMS (UNIT 5)DBMS (UNIT 5)
DBMS (UNIT 5)
Dr. SURBHI SAROHA
 
DBMS UNIT 4
DBMS UNIT 4DBMS UNIT 4
DBMS UNIT 4
Dr. SURBHI SAROHA
 
JAVA(UNIT 4)
JAVA(UNIT 4)JAVA(UNIT 4)
JAVA(UNIT 4)
Dr. SURBHI SAROHA
 
OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)
Dr. SURBHI SAROHA
 
DBMS UNIT 3
DBMS UNIT 3DBMS UNIT 3
DBMS UNIT 3
Dr. SURBHI SAROHA
 
Keys in dbms(UNIT 2)
Keys in dbms(UNIT 2)Keys in dbms(UNIT 2)
Keys in dbms(UNIT 2)
Dr. SURBHI SAROHA
 
DBMS (UNIT 2)
DBMS (UNIT 2)DBMS (UNIT 2)
DBMS (UNIT 2)
Dr. SURBHI SAROHA
 
JAVA UNIT 2
JAVA UNIT 2JAVA UNIT 2
JAVA UNIT 2
Dr. SURBHI SAROHA
 
Database Management System(UNIT 1)
Database Management System(UNIT 1)Database Management System(UNIT 1)
Database Management System(UNIT 1)
Dr. SURBHI SAROHA
 
Deep learning(UNIT 3) BY Ms SURBHI SAROHA
Deep learning(UNIT 3) BY Ms SURBHI SAROHADeep learning(UNIT 3) BY Ms SURBHI SAROHA
Deep learning(UNIT 3) BY Ms SURBHI SAROHA
Dr. SURBHI SAROHA
 
MOBILE COMPUTING UNIT 2 by surbhi saroha
MOBILE COMPUTING UNIT 2 by surbhi sarohaMOBILE COMPUTING UNIT 2 by surbhi saroha
MOBILE COMPUTING UNIT 2 by surbhi saroha
Dr. SURBHI SAROHA
 
Mobile Computing UNIT 1 by surbhi saroha
Mobile Computing UNIT 1 by surbhi sarohaMobile Computing UNIT 1 by surbhi saroha
Mobile Computing UNIT 1 by surbhi saroha
Dr. SURBHI SAROHA
 
DEEP LEARNING (UNIT 2 ) by surbhi saroha
DEEP LEARNING (UNIT 2 ) by surbhi sarohaDEEP LEARNING (UNIT 2 ) by surbhi saroha
DEEP LEARNING (UNIT 2 ) by surbhi saroha
Dr. SURBHI SAROHA
 
Introduction to Deep Leaning(UNIT 1).pptx
Introduction to Deep Leaning(UNIT 1).pptxIntroduction to Deep Leaning(UNIT 1).pptx
Introduction to Deep Leaning(UNIT 1).pptx
Dr. SURBHI SAROHA
 
Cloud Computing (Infrastructure as a Service)UNIT 2
Cloud Computing (Infrastructure as a Service)UNIT 2Cloud Computing (Infrastructure as a Service)UNIT 2
Cloud Computing (Infrastructure as a Service)UNIT 2
Dr. SURBHI SAROHA
 
Management Information System(Unit 2).pptx
Management Information System(Unit 2).pptxManagement Information System(Unit 2).pptx
Management Information System(Unit 2).pptx
Dr. SURBHI SAROHA
 
Searching in Data Structure(Linear search and Binary search)
Searching in Data Structure(Linear search and Binary search)Searching in Data Structure(Linear search and Binary search)
Searching in Data Structure(Linear search and Binary search)
Dr. SURBHI SAROHA
 
Management Information System(UNIT 1).pptx
Management Information System(UNIT 1).pptxManagement Information System(UNIT 1).pptx
Management Information System(UNIT 1).pptx
Dr. SURBHI SAROHA
 
Introduction to Cloud Computing(UNIT 1).pptx
Introduction to Cloud Computing(UNIT 1).pptxIntroduction to Cloud Computing(UNIT 1).pptx
Introduction to Cloud Computing(UNIT 1).pptx
Dr. SURBHI SAROHA
 
Database Management System(UNIT 1)
Database Management System(UNIT 1)Database Management System(UNIT 1)
Database Management System(UNIT 1)
Dr. SURBHI SAROHA
 
Ad

Recently uploaded (20)

How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Ad

JAVA (UNIT 3)

  • 2. SYLLABUS • Input/Output Programming: Basics • Streams • Byte and Character Stream • Predefined streams • Reading and writing from console and files • Networking: Basics
  • 3. Cont…. • Networking classes and interfaces • Using java.net package • Doing TCP/IP and Data-gram programming.
  • 4. Input/Output Programming: Basics • Java input and output is an essential concept while working on java programming. • It consists of elements such as input, output and stream. The input is the data that we give to the program. • The output is the data what we receive from the program in the form of result. • Stream represents flow of data or the sequence of data. • To give input we use the input stream and to give output we use the output stream.
  • 5. How input is read from the Keyboard? • The “System.in” represents the keyboard. • To read data from keyboard it should be connected to “InputStreamReader”. • From the “InputStreamReader” it reads data from the keyboard and sends the data to the “BufferedReader”. • From the “BufferedReader” it reads data from InputStreamReader and stores data in buffer. • It has got methods so that data can be easily accessed.
  • 6. Reading Input from Console • Input can be given either from file or keyword. In java, input can be read from console in 3 ways: • BufferedReader • StringTokenizer • Scanner
  • 7. BufferedReader – Java class • Here, we use the class “BufferedReader” and create the object “bufferedreader”. We also take integer value and fetch string from the user. • BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in)); • int age = bufferedreader.read(); • String name = bufferedreader.readLine(); • From the eclipse window we also see an example of the same in the following code: • Bufferedreader bufferedreader = new BufferedReader( • New InputStreamReader(System.in)); • System.out.println(“enter name”);
  • 8. CONT….. • String name = bufferedreader.readline(); • System.out.println(“enter age”); • int age = Integer.parseInt(bufferedreader.readline()); • int age1= bufferedreader.read(); • System.out.println(“I am” + name + “ “+age+”years old”); • } • }
  • 9. String Tokenizer – Java class • It can be used to accept multiple inputs from console in a single line where as BufferedReader accepts only one input from a line. It uses delimiter (space, comma) to make the input into tokens. • The syntax is as follows: • BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in)); • String input = bufferedreader.readline(); • StringTokenizer tokenizer = new StringTokenizer(input, “,”); • String name = tokenizer.nextToken(); • int age=tokenizer.nextToken();
  • 10. CONT…. • Once we enter eclipse and open the program, we view the code: • BufferedReader bufferedreader = new BufferedReader( • New InputStreamReader(System.in); • System.out.println(“Enter your name and age separated by comma”); • String Input = bufferedreader.readLine(); • StringTokenizer tokenizer = new StringTokenizer(Input, “,”);
  • 11. CONT…. • String name = Tokenizer.newToken(); • int age = Integer.parseInt(tokenizer.nextToken()); • System.out.println(“I am”+name+age+”years old”); • } • }
  • 12. Scanner – Java class • It accepts multiple inputs from file or keyboard and divides into tokens. It has methods to different types of input (int, float, string, long, double, byte) where tokenizer does not have. • The syntax is denoted below : • Scanner scanner = new Scanner(System.in); • int rollno = scanner.nextInt(); • String name = scanner.next(); • In the Eclipse window we view the following code:
  • 13. CONT…. • Scanner.scanner = new Scanner (System.in); • System.out.println(“Enter your name and age”); • String name = scanner.next(); • int age=scanner.nextInt(); • System.out.println(“ I am “ “+name” “+age+” years old”); • } • }
  • 14. Streams • Introduced in Java 8, Stream API is used to process collections of objects. A stream in Java is a sequence of objects that supports various methods which can be pipelined to produce the desired result. • Use of Stream in Java • There uses of Stream in Java are mentioned below: • Stream API is a way to express and process collections of objects. • Enable us to perform operations like filtering, mapping,reducing and sorting.
  • 15. How to Create Java Stream? • Java Stream Creation is one of the most basic steps before considering the functionalities of the Java Stream. Below is the syntax given on how to declare Java Stream. • Syntax • Stream<T> stream; • Here T is either a class, object, or data type depending upon the declaration.
  • 16. Java Stream Features • The features of Java stream are mentioned below: • A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels. • Streams don’t change the original data structure, they only provide the result as per the pipelined methods. • Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.
  • 17. Byte and Character Stream • Character Stream • In Java, characters are stored using Unicode conventions. • Character stream automatically allows us to read/write data character by character. • For example, FileReader and FileWriter are character streams used to read from the source and write to the destination. •
  • 18. Byte Stream • Byte streams process data byte by byte (8 bits). • For example, FileInputStream is used to read from the source and FileOutputStream to write to the destination.
  • 19. Predefined streams • All Java programs automatically import the java.lang package. • This package defines a class called System, which encapsulates several aspects of the run- time environment. • Among other things, it contains three predefined stream variables, called in, out, and err. These fields are declared as public, final, and static within System. This means that they can be used by any other part of your program and without reference to a specific System object. • System.out refers to the standard output stream. By default, this is the console. System.in refers to standard input, which is by default the keyboard. System.err refers to the standard error stream, which is also the console by default.
  • 21. Program to show use of System.in of Java Predefined Streams • import java.io.*; • class InputEg • { • public static void main( String args[] ) throws IOException • { • String city; • BufferedReader br = new BufferedReader ( new InputStreamReader (System.in) );
  • 22. Cont…… • System.out.println ( “Where do you live?" ); • city = br.readLine(); • System.out.println ( “You have entered " + city + " city" ); • } • }
  • 23. Java Predefined Stream for Standard Error • System.err is the stream used for standard error in Java. This stream is an object of PrintStream stream. • System.err is similar to System.out but it is most commonly used inside the catch section of the try / catch block. A sample of the block is as follows: • try { • // Code for execution • } • catch ( Exception e) { • System.err.println ( “Error in code: ” + e );
  • 24. Reading and writing from console and files • By default, to read from system console, we can use the Console class. This class provides methods to access the character-based console, if any, associated with the current Java process. To get access to Console, call the method System.console(). • Console gives three ways to read the input: • String readLine() – reads a single line of text from the console. • char[] readPassword() – reads a password or encrypted text from the console with echoing disabled • Reader reader() – retrieves the Reader object associated with this console. This reader is supposed to be used by sophisticated applications. For example, Scanner object which utilizes the rich parsing/scanning functionality on top of the underlying Reader.
  • 25. 1.1. Reading Input with readLine() • Console console = System.console(); • if(console == null) { • System.out.println("Console is not available to current JVM process"); • return; • } • String userName = console.readLine("Enter the username: "); • System.out.println("Entered username: " + userName);
  • 26. 1.2. Reading Input with readPassword() • Console console = System.console(); • if(console == null) { • System.out.println("Console is not available to current JVM process"); • return; • } • char[] password = console.readPassword("Enter the password: "); • System.out.println("Entered password: " + new String(password));
  • 27. 1.3. Read Input with reader() • Console console = System.console(); • if(console == null) { • System.out.println("Console is not available to current JVM process"); • return; • } • Reader consoleReader = console.reader(); • Scanner scanner = new Scanner(consoleReader);
  • 28. CONT….. • System.out.println("Enter age:"); • int age = scanner.nextInt(); • System.out.println("Entered age: " + age); • scanner.close();
  • 29. 2. Writing Output to Console • The easiest way to write the output data to console is System.out.println() statements. Still, we can use printf() methods to write formatted text to console. • 2.1. Writing with System.out.println • System.out.println("Hello, world!");
  • 30. 2.2. Writing with printf() • The printf(String format, Object... args) method takes an output string and multiple parameters which are substituted in the given string to produce the formatted output content. • This formatted output is written in the console. • String name = "Lokesh"; • int age = 38; • console.printf("My name is %s and my age is %d", name, age);
  • 31. Networking: Basics • The working of Computer Networks can be simply defined as rules or protocols which help in sending and receiving data via the links which allow Computer networks to communicate. • Each device has an IP Address, that helps in identifying a device. • Network: A network is a collection of computers and devices that are connected together to enable communication and data exchange. • Nodes: Nodes are devices that are connected to a network. These can include computers, Servers, Printers, Routers, Switches, and other devices. • Protocol: A protocol is a set of rules and standards that govern how data is transmitted over a network. Examples of protocols include TCP/IP, HTTP, and FTP. • Topology: Network topology refers to the physical and logical arrangement of nodes on a network. The common network topologies include bus, star, ring, mesh, and tree.
  • 32. CONT….. • Service Provider Networks: These types of Networks give permission to take Network Capacity and Functionality on lease from the Provider. Service Provider Networks include Wireless Communications, Data Carriers, etc. • IP Address: An IP address is a unique numerical identifier that is assigned to every device on a network. IP addresses are used to identify devices and enable communication between them. • DNS: The Domain Name System (DNS) is a protocol that is used to translate human-readable domain names (such as www.google.com) into IP addresses that computers can understand. • Firewall: A firewall is a security device that is used to monitor and control incoming and outgoing network traffic. Firewalls are used to protect networks from unauthorized access and other security threats.
  • 33. Networking classes and interfaces • When computing devices such as laptops, desktops, servers, smartphones, and tablets and an eternally-expanding arrangement of IoT gadgets such as cameras, door locks, doorbells, refrigerators, audio/visual systems, thermostats, and various sensors are sharing information and data with each other is known as networking. • What is Java Networking? • Networking supplements a lot of power to simple programs. With networks, a single program can regain information stored in millions of computers positioned anywhere in the world. Java is the leading programming language composed from scratch with networking in mind. Java Networking is a notion of combining two or more computing devices together to share resources.
  • 34. Java Networking classes • The java.net package of the Java programming language includes various classes that provide an easy-to-use means to access network resources. The classes covered in the java.net package are given as follows – • CacheRequest – The CacheRequest class is used in java whenever there is a need to store resources in ResponseCache. The objects of this class provide an edge for the OutputStream object to store resource data into the cache.
  • 35. CONT…. • CookieHandler – The CookieHandler class is used in Java to implement a callback mechanism for securing up an HTTP state management policy implementation inside the HTTP protocol handler. The HTTP state management mechanism specifies the mechanism of how to make HTTP requests and responses. • CookieManager – The CookieManager class is used to provide a precise implementation of CookieHandler. This class separates the storage of cookies from the policy surrounding accepting and rejecting cookies. A CookieManager comprises a CookieStore and a CookiePolicy. • DatagramPacket – The DatagramPacket class is used to provide a facility for the connectionless transfer of messages from one system to another. This class provides tools for the production of datagram packets for connectionless transmission by applying the datagram socket class.
  • 36. CONT…. • InetAddress – The InetAddress class is used to provide methods to get the IP address of any hostname. An IP address is expressed by a 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses. • Server Socket – The ServerSocket class is used for implementing system-independent implementation of the server-side of a client/server Socket Connection. The constructor for ServerSocket class throws an exception if it can’t listen on the specified port. For example – it will throw an exception if the port is already being used. • Socket – The Socket class is used to create socket objects that help the users in implementing all fundamental socket operations. The users can implement various networking actions such as sending, reading data, and closing connections. Each Socket object built using java.net.Socket class has been connected exactly with 1 remote host; for connecting to another host, a user must create a new socket object.
  • 37. CONT… • InetAddress – The InetAddress class is used to provide methods to get the IP address of any hostname. An IP address is expressed by a 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses. • Server Socket – The ServerSocket class is used for implementing system-independent implementation of the server-side of a client/server Socket Connection. The constructor for ServerSocket class throws an exception if it can’t listen on the specified port. For example – it will throw an exception if the port is already being used. • Socket – The Socket class is used to create socket objects that help the users in implementing all fundamental socket operations. The users can implement various networking actions such as sending, reading data, and closing connections. Each Socket object built using java.net.Socket class has been connected exactly with 1 remote host; for connecting to another host, a user must create a new socket object.
  • 38. CONT…. • URLConnection – The URLConnection class in Java is an abstract class describing a connection of a resource as defined by a similar URL. The URLConnection class is used for assisting two distinct yet interrelated purposes. Firstly it provides control on interaction with a server(especially an HTTP server) than a URL class. Furthermore, with a URLConnection, a user can verify the header transferred by the server and can react consequently. A user can also configure header fields used in client requests using URLConnection.
  • 39. Java Networking Interfaces • The java.net package of the Java programming language includes various interfaces also that provide an easy-to-use means to access network resources. The interfaces included in the java.net package are as follows: • CookiePolicy – The CookiePolicy interface in the java.net package provides the classes for implementing various networking applications. It decides which cookies should be accepted and which should be rejected. In CookiePolicy, there are three pre-defined policy implementations, namely ACCEPT_ALL, ACCEPT_NONE, and ACCEPT_ORIGINAL_SERVER.
  • 40. CONT….. • CookieStore – A CookieStore is an interface that describes a storage space for cookies. CookieManager combines the cookies to the CookieStore for each HTTP response and recovers cookies from the CookieStore for each HTTP request. • FileNameMap – The FileNameMap interface is an uncomplicated interface that implements a tool to outline a file name and a MIME type string. FileNameMap charges a filename map ( known as a mimetable) from a data file. • SocketOption – The SocketOption interface helps the users to control the behavior of sockets. Often, it is essential to develop necessary features in Sockets. SocketOptions allows the user to set various standard options.
  • 41. CONT….. • SocketImplFactory – The SocketImplFactory interface defines a factory for SocketImpl instances. It is used by the socket class to create socket implementations that implement various policies. • ProtocolFamily – This interface represents a family of communication protocols. The ProtocolFamily interface contains a method known as name(), which returns the name of the protocol family.
  • 45. Doing TCP/IP and Data-gram programming. • TCP/IP-style networking provides a serialized, predictable, reliable stream of packet data. This is not without its cost, however. • TCP includes algorithms for dealing with congestion control on crowded networks, as well as pessimistic expectations about packet loss. • This leads to inefficient way to transport data. • Clients and servers that communicate via a reliable channel, such as a TCP socket, have a dedicated point-to-point channel between themselves. To communicate, they establish a connection, transmit the data, and then close the connection. All data sent over the channel is received in the same order in which it was sent. This is guaranteed by the channel.
  • 46. Datagram • A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed. • Datagrams plays a vital role as an alternative. • Datagrams are bundles of information passed between machines. Once the datagram has been released to its intended target, there is no assurance that it will arrive or even that someone will be there to catch it. • Likewise, when the datagram is received, there is no assurance that it hasn’t been damaged in transit or that whoever sent it is still there to receive a response and it is crucial point to note.
  • 47. // Java program to illustrate datagrams import java.net.*; class WriteServer { // Specified server port public static int serverPort = 998; // Specified client port public static int clientPort = 999; public static int buffer_size = 1024; public static DatagramSocket ds; // an array of buffer_size public static byte buffer[] = new byte[buffer_size];
  • 48. Cont…. // Function for server public static void TheServer() throws Exception { int pos = 0; while (true) { int c = System.in.read(); switch (c) { case -1: // -1 is given then server quits and returns System.out.println("Server Quits."); return; case 'r': break; // loop broken case 'n': // send the data to client
  • 49. Cont…. ds.send(new DatagramPacket(buffer, pos, InetAddress.getLocalHost(), clientPort)); pos = 0; break; default: // otherwise put the input in buffer array buffer[pos++] = (byte)c; } } } // Function for client public static void TheClient() throws Exception { while (true) {
  • 50. Cont…. // first one is array and later is its size DatagramPacket p = new DatagramPacket(buffer, buffer.length); ds.receive(p); // printing the data which has been sent by the server System.out.println(new String(p.getData(), 0, p.getLength())); } } // main driver function public static void main(String args[]) throws Exception { // if WriteServer 1 passed then this will run the server function // otherwise client function will run if (args.length == 1) { ds = new DatagramSocket(serverPort); TheServer(); }
  • 51. Cont…. else { ds = new DatagramSocket(clientPort); TheClient(); } } } THANK YOU 