SlideShare a Scribd company logo
1 of 51
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
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 ļŠ

More Related Content

Similar to JAVA (UNIT 3)

FILE OPERATIONS.pptx
FILE OPERATIONS.pptxFILE OPERATIONS.pptx
FILE OPERATIONS.pptxDeepasCSE
Ā 
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 javaJyoti Verma
Ā 
Oodp mod4
Oodp mod4Oodp mod4
Oodp mod4cs19club
Ā 
OOPs & C++(UNIT 5)
OOPs & C++(UNIT 5)OOPs & C++(UNIT 5)
OOPs & C++(UNIT 5)SURBHI SAROHA
Ā 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxSadhilAggarwal
Ā 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2Gera Paulos
Ā 
Java input
Java inputJava input
Java inputJin Castor
Ā 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)Om Ganesh
Ā 
PYTHON PROGRAMMING.pptx
PYTHON PROGRAMMING.pptxPYTHON PROGRAMMING.pptx
PYTHON PROGRAMMING.pptxswarna627082
Ā 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OWebStackAcademy
Ā 
C5 c++ development environment
C5 c++ development environmentC5 c++ development environment
C5 c++ development environmentsnchnchl
Ā 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptxcherryreddygannu
Ā 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6Berk Soysal
Ā 

Similar to JAVA (UNIT 3) (20)

FILE OPERATIONS.pptx
FILE OPERATIONS.pptxFILE OPERATIONS.pptx
FILE OPERATIONS.pptx
Ā 
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
Ā 
Java sockets
Java socketsJava sockets
Java sockets
Ā 
Java I/O
Java I/OJava I/O
Java I/O
Ā 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
Ā 
Oodp mod4
Oodp mod4Oodp mod4
Oodp mod4
Ā 
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
Ā 
Files io
Files ioFiles io
Files io
Ā 
OOPs & C++(UNIT 5)
OOPs & C++(UNIT 5)OOPs & C++(UNIT 5)
OOPs & C++(UNIT 5)
Ā 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
Ā 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
Ā 
Os lectures
Os lecturesOs lectures
Os lectures
Ā 
Java input
Java inputJava input
Java input
Ā 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
Ā 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
Ā 
PYTHON PROGRAMMING.pptx
PYTHON PROGRAMMING.pptxPYTHON PROGRAMMING.pptx
PYTHON PROGRAMMING.pptx
Ā 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Ā 
C5 c++ development environment
C5 c++ development environmentC5 c++ development environment
C5 c++ development environment
Ā 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
Ā 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6
Ā 

More from 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 2SURBHI SAROHA
Ā 
Management Information System(Unit 2).pptx
Management Information System(Unit 2).pptxManagement Information System(Unit 2).pptx
Management Information System(Unit 2).pptxSURBHI 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)SURBHI SAROHA
Ā 
Management Information System(UNIT 1).pptx
Management Information System(UNIT 1).pptxManagement Information System(UNIT 1).pptx
Management Information System(UNIT 1).pptxSURBHI 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).pptxSURBHI SAROHA
Ā 
OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)SURBHI SAROHA
Ā 
Keys in dbms(UNIT 2)
Keys in dbms(UNIT 2)Keys in dbms(UNIT 2)
Keys in dbms(UNIT 2)SURBHI SAROHA
Ā 
Database Management System(UNIT 1)
Database Management System(UNIT 1)Database Management System(UNIT 1)
Database Management System(UNIT 1)SURBHI SAROHA
Ā 
Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1SURBHI SAROHA
Ā 
Database Management System(UNIT 1)
Database Management System(UNIT 1)Database Management System(UNIT 1)
Database Management System(UNIT 1)SURBHI SAROHA
Ā 
OOPs & C++ UNIT 3
OOPs & C++ UNIT 3OOPs & C++ UNIT 3
OOPs & C++ UNIT 3SURBHI SAROHA
Ā 
OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)SURBHI SAROHA
Ā 
Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)SURBHI SAROHA
Ā 

More from SURBHI SAROHA (20)

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
Ā 
Management Information System(Unit 2).pptx
Management Information System(Unit 2).pptxManagement Information System(Unit 2).pptx
Management Information System(Unit 2).pptx
Ā 
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)
Ā 
Management Information System(UNIT 1).pptx
Management Information System(UNIT 1).pptxManagement Information System(UNIT 1).pptx
Management Information System(UNIT 1).pptx
Ā 
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
Ā 
JAVA (UNIT 5)
JAVA (UNIT 5)JAVA (UNIT 5)
JAVA (UNIT 5)
Ā 
DBMS (UNIT 5)
DBMS (UNIT 5)DBMS (UNIT 5)
DBMS (UNIT 5)
Ā 
DBMS UNIT 4
DBMS UNIT 4DBMS UNIT 4
DBMS UNIT 4
Ā 
JAVA(UNIT 4)
JAVA(UNIT 4)JAVA(UNIT 4)
JAVA(UNIT 4)
Ā 
OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)
Ā 
DBMS UNIT 3
DBMS UNIT 3DBMS UNIT 3
DBMS UNIT 3
Ā 
Keys in dbms(UNIT 2)
Keys in dbms(UNIT 2)Keys in dbms(UNIT 2)
Keys in dbms(UNIT 2)
Ā 
DBMS (UNIT 2)
DBMS (UNIT 2)DBMS (UNIT 2)
DBMS (UNIT 2)
Ā 
JAVA UNIT 2
JAVA UNIT 2JAVA UNIT 2
JAVA UNIT 2
Ā 
Database Management System(UNIT 1)
Database Management System(UNIT 1)Database Management System(UNIT 1)
Database Management System(UNIT 1)
Ā 
Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1
Ā 
Database Management System(UNIT 1)
Database Management System(UNIT 1)Database Management System(UNIT 1)
Database Management System(UNIT 1)
Ā 
OOPs & C++ UNIT 3
OOPs & C++ UNIT 3OOPs & C++ UNIT 3
OOPs & C++ UNIT 3
Ā 
OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)OOPS USING C++(UNIT 2)
OOPS USING C++(UNIT 2)
Ā 
Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)Object Oriented Programming using C++(UNIT 1)
Object Oriented Programming using C++(UNIT 1)
Ā 

Recently uploaded

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
Ā 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
Ā 
ą¤­ą¤¾ą¤°ą¤¤-ą¤°ą„‹ą¤® ą¤µą„ą¤Æą¤¾ą¤Ŗą¤¾ą¤°.pptx, Indo-Roman Trade,
ą¤­ą¤¾ą¤°ą¤¤-ą¤°ą„‹ą¤® ą¤µą„ą¤Æą¤¾ą¤Ŗą¤¾ą¤°.pptx, Indo-Roman Trade,ą¤­ą¤¾ą¤°ą¤¤-ą¤°ą„‹ą¤® ą¤µą„ą¤Æą¤¾ą¤Ŗą¤¾ą¤°.pptx, Indo-Roman Trade,
ą¤­ą¤¾ą¤°ą¤¤-ą¤°ą„‹ą¤® ą¤µą„ą¤Æą¤¾ą¤Ŗą¤¾ą¤°.pptx, Indo-Roman Trade,Virag Sontakke
Ā 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
Ā 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
Ā 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
Ā 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
Ā 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
Ā 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
Ā 
18-04-UA_REPORT_MEDIALITERAŠ”Y_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAŠ”Y_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAŠ”Y_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAŠ”Y_INDEX-DM_23-1-final-eng.pdfssuser54595a
Ā 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
Ā 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
Ā 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
Ā 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
Ā 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
Ā 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
Ā 
ā€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
ā€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...ā€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
ā€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
Ā 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
Ā 

Recently uploaded (20)

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
Ā 
Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”
Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”
Model Call Girl in Tilak Nagar Delhi reach out to us at šŸ”9953056974šŸ”
Ā 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
Ā 
ą¤­ą¤¾ą¤°ą¤¤-ą¤°ą„‹ą¤® ą¤µą„ą¤Æą¤¾ą¤Ŗą¤¾ą¤°.pptx, Indo-Roman Trade,
ą¤­ą¤¾ą¤°ą¤¤-ą¤°ą„‹ą¤® ą¤µą„ą¤Æą¤¾ą¤Ŗą¤¾ą¤°.pptx, Indo-Roman Trade,ą¤­ą¤¾ą¤°ą¤¤-ą¤°ą„‹ą¤® ą¤µą„ą¤Æą¤¾ą¤Ŗą¤¾ą¤°.pptx, Indo-Roman Trade,
ą¤­ą¤¾ą¤°ą¤¤-ą¤°ą„‹ą¤® ą¤µą„ą¤Æą¤¾ą¤Ŗą¤¾ą¤°.pptx, Indo-Roman Trade,
Ā 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
Ā 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
Ā 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
Ā 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
Ā 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
Ā 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
Ā 
18-04-UA_REPORT_MEDIALITERAŠ”Y_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAŠ”Y_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAŠ”Y_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAŠ”Y_INDEX-DM_23-1-final-eng.pdf
Ā 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
Ā 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
Ā 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
Ā 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
Ā 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Ā 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
Ā 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
Ā 
ā€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
ā€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...ā€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
ā€œOh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
Ā 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
Ā 

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.
  • 43.
  • 44.
  • 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 ļŠ