SlideShare ist ein Scribd-Unternehmen logo
1 von 8
Java Programming
Question 1- What are the difference between an interface and an abstract class?
While deciding when to use interface and abstract class, it’s important to know difference
between abstract class and interface in Java. In my opinion, following two differences
between them drives decision about when to use abstract class or interface in Java.
1) Interface in Java can only contains declaration. You can not declare any concrete
methods inside interface. On the other hand abstract class may contain both abstract and
concrete methods, which makes abstract class an ideal place to provide common or default
functionality. I suggest reading my post 10 things to know about interface in Java to know
more about interfaces, particularly in Java programming language.
2) Java interface can extend multiple interfaces also Java class can implement multiple
interfaces, which means interface can provide more polymorphism support than abstract
class. By extending abstract class, a class can only participate in one Type hierarchy but by
using interface it can be part of multiple type hierarchies. E.g. a class can be Runnable and
Displayable at same time. One example I can remember of this is writing GUI application in
J2ME, where class extends Canvas and implements Command Listener to provide both
graphic and event-handling functionality..
3) In order to implement interface in Java, until your class is abstract, you need to provide
implementation of all methods, which is very painful. On the other hand abstract class may
help you in this case by providing default implementation. Because of this reason, I prefer to
have minimum methods in interface, starting from just one, I don't like idea of marker
interface, once annotation is introduced in Java 5. If you look JDK or any framework like
Spring, which I does to understand OOPS and design patter better, you will find that most of
interface contains only one or two methods e.g. Runnable, Callable, Action Listener etc.
I haven't included all syntactical difference between abstract class and interface in Java
here, because focus here to learn when to use abstract class and interface and choosing
one over other. Nevertheless you can see difference between interface and abstract class to
find all those syntactical differences.
Question 2- Describe Exception Handling in JAVA
A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code. When an exceptional condition arises, an object representing
that exception is created and thrown in the method that caused the error. That method may
choose to handle the exception itself, or pass it on. Exceptions can be generated by the
Java run-time system, or they can be manually generated by the code. Exceptions thrown by
Java relate to fundamental errors that violate the rules of the Java language or the
constraints of the Java execution environment. Manually generated exceptions are typically
used to report some error condition to the caller of a method.
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
Program statements that must be monitored for exceptions are contained within a try block.
If an exception occurs within the try block, it is thrown. The code can catch this exception
(using catch) and handle it in some rational manner. System-generated exceptions are
automatically thrown by the Java run-time system. To manually throw an exception, use the
keyword throw. Any exception that is thrown out of a method must be specified as such by a
throws clause. Any code that absolutely must be executed before a method returns is put in
a finally block.
When an error occurs within a method, the method creates an object and hands it off to the
runtime system. The object, called an exception object, contains information about the error,
including its type and the state of the program when the error occurred. Creating an
exception object and handing it to the runtime system is called throwing an exception.
After a method throws an exception, the runtime system attempts to find something to
handle it. The set of possible "something’s" to handle the exception is the ordered list of
methods that had been called to get to the method where the error occurred. The list of
methods is known as the call stack
The runtime system searches the call stack for a method that contains a block of code that can
handle the exception. This block of code is called an exception handler. The search begins
with the method in which the error occurred and proceeds through the call stack in the reverse
order in which the methods were called. When an appropriate handler is found, the runtime
system passes the exception to the handler. An exception handler is considered appropriate if
the type of the exception object thrown matches the type that can be handled by the handler.
The exception handler chosen is said to catch the exception. If the runtime system
exhaustively searches all the methods on the call stack without finding an appropriate
exception handler, as shown in the next figure, the runtime system (and, consequently, the
program) terminates.
Question 3- Describe the following with respect to implementation of Sockets in
Java:
Question 3 a. Reading from and Writing to a Socket
Let's look at a simple example that illustrates how a program can establish a connection to a
server program using the Socket class and then, how the client can send data to and receive
data from the server through the socket.
The example program implements a client, EchoClient, that connects to the Echo server. The
Echo server simply receives data from its client and echoes it back. The Echo server is a well-
known service that clients can rendezvous with on port 7.
EchoClient creates a socket thereby getting a connection to the Echo server. It reads input
from the user on the standard input stream, and then forwards that text to the Echo server by
writing the text to the socket. The server echoes the input back through the socket to the
client. The client program reads and displays the data passed back to it from the server:
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("taranis", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: taranis.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
Note that EchoClient both writes to and reads from its socket, thereby sending data to and
receiving data from the Echo server.
Let's walk through the program and investigate the interesting parts. The three statements in
the try block of the main method are critical. These lines establish the socket connection
between the client and the server and open a PrintWriter and a BufferedReader on the socket:
echoSocket = new Socket("taranis", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader( new InputStreamReader(echoSocket.getInputStream()));
Question 3 b. Writing the Server Side of a Socket
This section shows you how to write a server and the client that goes with it. The server in the
client/server pair serves up Knock Knock jokes. Knock Knock jokes are favored by children
and are usually vehicles for bad puns. They go like this:
Server: "Knock knock!"
Client: "Who's there?"
Server: "Dexter."
Client: "Dexter who?"
Server: "Dexter halls with boughs of holly."
Client: "Groan."
The example consists of two independently running Java programs: the client program and
the server program. The client program is implemented by a single class, KnockKnockClient,
and is very similar to the EchoClient example from the previous section. The server program
is implemented by two classes: KnockKnockServer and KnockKnockProtocol,
KnockKnockServer contains the main method for the server program and performs the work
of listening to the port, establishing connections, and reading from and writing to the socket.
KnockKnockProtocol serves up the jokes. It keeps track of the current joke, the current state
(sent knock knock, sent clue, and so on), and returns the various text pieces of the joke
depending on the current state. This object implements the protocol-the language that the
client and server have agreed to use to communicate.
The following section looks in detail at each class in both the client and the server and then
shows you how to run them.
The Knock Knock Server
This section walks through the code that implements the Knock Knock server program. Here
is the complete source for the KnockKnockServer class.
The server program begins by creating a new ServerSocket object to listen on a specific port
(see the statement in bold in the following code segment). When writing a server, choose a
port that is not already dedicated to some other service. KnockKnockServer listens on port
4444 because 4 happens to be my favorite number and port 4444 is not being used for
anything else in my environment:
try {
serverSocket = new ServerSocket(4444);
}
catch (IOException e) {
System.out.println("Could not listen on port: 4444");
System.exit(-1);
}
ServerSocket is a java.net class that provides a system-independent implementation of the
server side of a client/server socket connection. The constructor for ServerSocket throws an
exception if it can't listen on the specified port (for example, the port is already being used).
In this case, the KnockKnockServer has no choice but to exit.
If the server successfully binds to its port, then the ServerSocket object is successfully
created and the server continues to the next step--accepting a connection from a client (shown
in bold):
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
}
catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
The accept method waits until a client starts up and requests a connection on the host and port
of this server (in this example, the server is running on the hypothetical machine taranis on
port 4444). When a connection is requested and successfully established, the accept method
returns a new Socket object which is bound to the same local port and has its remote address
and remote port set to that of the client. The server can communicate with the client over this
new Socket and continue to listen for client connection requests on the original ServerSocket
This particular version of the program doesn't listen for more client connection requests.
However, a modified version of the program is provided in Supporting Multiple Clients.
After the server successfully establishes a connection with a client, it communicates with the
client using this code:
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
// initiate conversation with client
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
The Knock Knock Protocol
The KnockKnockProtocol class implements the protocol that the client and server use to
communicate. This class keeps track of where the client and the server are in their
conversation and serves up the server's response to the client's statements. The
KnockKnockServer object contains the text of all the jokes and makes sure that the client
gives the proper response to the server's statements. It wouldn't do to have the client say
"Dexter who?" when the server says "Knock! Knock!"
All client/server pairs must have some protocol by which they speak to each other; otherwise,
the data that passes back and forth would be meaningless. The protocol that your own clients
and servers use depends entirely on the communication required by them to accomplish the
task.
The Knock Knock Client
The KnockKnockClient class implements the client program that speaks to the
KnockKnockServer. KnockKnockClient is based on the EchoClient program in the previous
section, Reading from and Writing to a Socket and should be somewhat familiar to you. But
we'll go over the program anyway and look at what's happening in the client in the context of
what's going on in the server.
When you start the client program, the server should already be running and listening to the
port, waiting for a client to request a connection. So, the first thing the client program does is
to open a socket that is connected to the server running on the hostname and port specified:
Question 4- Define RMI. Define the architecture of RMI invocation.
Remote Method Invocation (RMI) technology, first introduced in JDK 1.1, elevates network
programming to a higher plane. Although RMI is relatively easy to use, it is a remarkably
powerful technology and exposes the average Java developer to an entirely new paradigm--
the world of distributed object computing.
This course provides you with an in-depth introduction to this versatile technology. RMI has
evolved considerably since JDK 1.1, and has been significantly upgraded under the Java 2
SDK. Where applicable, the differences between the two releases will be indicated.
The design goal for the RMI architecture was to create a Java distributed object model that
integrates naturally into the Java programming language and the local object model. RMI
architects have succeeded; creating a system that extends the safety and robustness of the
Java architecture to the distributed computing world.
Interfaces: The Heart of RMI
The RMI architecture is based on one important principle: the definition of behavior
and the implementation of that behavior are separate concepts. RMI allows the code that
defines the behavior and the code that implements the behavior to remain separate and to run
on separate JVMs.
This fits nicely with the needs of a distributed system where clients are concerned
about the definition of a service and servers are focused on providing the service.
Specifically, in RMI, the definition of a remote service is coded using a Java
interface. The implementation of the remote service is coded in a class. Therefore, the key to
understanding RMI is to remember that interfaces define behavior and classes define
implementation. Remember that a Java interface does not contain executable code. RMI
supports two classes that implement the same interface. The first class is the implementation
of the behavior, and it runs on the server. The second class acts as a proxy for the remote
service and it runs on the client.
A client program makes method calls on the proxy object, RMI sends the request to the
remote JVM, and forwards it to the implementation. Any return values provided by the
implementation are sent back to the proxy and then to the client's program.
RMI Architecture Layers:
With an understanding of the high-level RMI architecture, take a look under the covers to see
its implementation. The RMI implementation is essentially built from three abstraction
layers. The first is the Stub and Skeleton layer, which lies just beneath the view of the
developer. This layer intercepts method calls made by the client to the interface reference
variable and redirects these calls to a remote RMI service.
The next layer is the Remote Reference Layer. This layer understands how to interpret and
manage references made from clients to the remote service objects. In JDK 1.1, this layer
connects clients to remote service objects that are running and exported on a server. The
connection is a one-to-one (unicast) link. In the Java 2 SDK, this layer was enhanced to
support the activation of dormant remote service objects via Remote Object Activation.
The transport layer is based on TCP/IP connections between machines in a network. It
provides basic connectivity, as well as some firewall penetration strategies.
By using a layered architecture each of the layers could be enhanced or replaced without
affecting the rest of the system. For example, the transport layer could be replaced by a
UDP/IP layer without affecting the upper layers.
Stub and Skeleton Layer:
The stub and skeleton layer of RMI lie just beneath the view of the Java developer. In this
layer, RMI uses the Proxy design pattern as described in the book, Design Patterns by
Gamma, Helm, Johnson and Vlissides. In the Proxy pattern, an object in one context is
represented by another (the proxy) in a separate context. The proxy knows how to forward
method calls between the participating objects. The following class diagram illustrates the
Proxy pattern.
Remote Reference Layer
The Remote Reference Layers defines and supports the invocation semantics of the RMI
connection. This layer provides a RemoteRef object that represents the link to the remote
service implementation object.
The stub objects use the invoke() method in RemoteRef to forward the method call. The
RemoteRef object understands the invocation semantics for remote services.
The JDK 1.1 implementation of RMI provides only one way for clients to connect to remote
service implementations: a unicast, point-to-point connection. Before a client can use a
remote service, the remote service must be instantiated on the server and exported to the RMI
system. (If it is the primary service, it must also be named and registered in the RMI
Registry).
The Java 2 SDK implementation of RMI adds a new semantic for the client-server
connection. In this version, RMI supports activatable remote objects. When a method call is
made to the proxy for an activatable object, RMI determines if the remote service
implementation object is dormant. If it is dormant, RMI will instantiate the object and restore
its state from a disk file. Once an activatable object is in memory, it behaves just like JDK 1.1
remote service implementation objects.
Other types of connection semantics are possible. For example, with multicast, a single proxy
could send a method request to multiple implementations simultaneously and accept the first
reply (this improves response time and possibly improves availability). In the future, Sun
may add additional invocation semantics to RMI.
Transport Layer:
The Transport Layer makes the connection between JVMs. All connections are stream-based
network connections that use TCP/IP.
Even if two JVMs are running on the same physical computer, they connect through their
host computer's TCP/IP network protocol stack. (This is why you must have an operational
TCP/IP configuration on your computer to run the Exercises in this course). The following
diagram shows the unfettered use of TCP/IP connections between JVMs.
Question 5.a- Write Java program to print the address of the study center.
class Address
{
public static void main(String arg[])
{
String name="SIKKIM MANIPAL UNIVERSITY UTTARAKHAND,INDIA";
String center="IT CAMPUS ,HALDWANI";
String detail="2ND FLOOR, UTTRANCHAL TRADE CENTRE, NAINITAL RD,TIKONIA ";
String tel="05946-260225, 9259937438";
System.out.println(name);System.out.println(center);
System.out.println(detail);System.out.println(tel);
}
}
Question 5.b- Write a Java program to find the sum of 1+3+5+…. for 10 terms in
the series.
import java.io.*;
class sum
{
public static void main(String arg[])throws IOException
{
InputStreamReader read=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(read);
int i,n,s=0;
System.out.println(“Enter nth term=”);
n=Integer.parseInt(in.readLine());
for(i=0;i<=n;i++)
{
if(i%2!=0)
{
s=s+i;
}
}
System.out.println(“Sum of series=”+s);
}
}
Question 6- Write a program to copy one file to another file?
import java.io.*;
public class Main {
public static void main(String[] args)
throws Exception {
BufferedWriter out1 = new BufferedWriter
(new FileWriter("srcfile"));
out1.write("string to be copiedn");
out1.close();
InputStream in = new FileInputStream
(new File("srcfile"));
OutputStream out = new FileOutputStream
(new File("destnfile"));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
BufferedReader in1 = new BufferedReader
(new FileReader("destnfile"));
String str;
while ((str = in1.readLine()) != null) {
System.out.println(str);
}
in.close();
}
}

Weitere ähnliche Inhalte

Kürzlich hochgeladen

Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
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
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 

Kürzlich hochgeladen (20)

Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
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
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 

Empfohlen

AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 

Empfohlen (20)

AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 

Master of Computer Application (MCA) – Semester 4 MC0078 – Java Programming

  • 1. Java Programming Question 1- What are the difference between an interface and an abstract class? While deciding when to use interface and abstract class, it’s important to know difference between abstract class and interface in Java. In my opinion, following two differences between them drives decision about when to use abstract class or interface in Java. 1) Interface in Java can only contains declaration. You can not declare any concrete methods inside interface. On the other hand abstract class may contain both abstract and concrete methods, which makes abstract class an ideal place to provide common or default functionality. I suggest reading my post 10 things to know about interface in Java to know more about interfaces, particularly in Java programming language. 2) Java interface can extend multiple interfaces also Java class can implement multiple interfaces, which means interface can provide more polymorphism support than abstract class. By extending abstract class, a class can only participate in one Type hierarchy but by using interface it can be part of multiple type hierarchies. E.g. a class can be Runnable and Displayable at same time. One example I can remember of this is writing GUI application in J2ME, where class extends Canvas and implements Command Listener to provide both graphic and event-handling functionality.. 3) In order to implement interface in Java, until your class is abstract, you need to provide implementation of all methods, which is very painful. On the other hand abstract class may help you in this case by providing default implementation. Because of this reason, I prefer to have minimum methods in interface, starting from just one, I don't like idea of marker interface, once annotation is introduced in Java 5. If you look JDK or any framework like Spring, which I does to understand OOPS and design patter better, you will find that most of interface contains only one or two methods e.g. Runnable, Callable, Action Listener etc. I haven't included all syntactical difference between abstract class and interface in Java here, because focus here to learn when to use abstract class and interface and choosing one over other. Nevertheless you can see difference between interface and abstract class to find all those syntactical differences. Question 2- Describe Exception Handling in JAVA A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Exceptions can be generated by the Java run-time system, or they can be manually generated by the code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. Manually generated exceptions are typically used to report some error condition to the caller of a method. Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Program statements that must be monitored for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. The code can catch this exception (using catch) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed before a method returns is put in a finally block. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error,
  • 2. including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception. After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "something’s" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the next figure, the runtime system (and, consequently, the program) terminates. Question 3- Describe the following with respect to implementation of Sockets in Java: Question 3 a. Reading from and Writing to a Socket Let's look at a simple example that illustrates how a program can establish a connection to a server program using the Socket class and then, how the client can send data to and receive data from the server through the socket. The example program implements a client, EchoClient, that connects to the Echo server. The Echo server simply receives data from its client and echoes it back. The Echo server is a well- known service that clients can rendezvous with on port 7. EchoClient creates a socket thereby getting a connection to the Echo server. It reads input from the user on the standard input stream, and then forwards that text to the Echo server by writing the text to the socket. The server echoes the input back through the socket to the client. The client program reads and displays the data passed back to it from the server: import java.io.*; import java.net.*; public class EchoClient { public static void main(String[] args) throws IOException { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; try { echoSocket = new Socket("taranis", 7); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: taranis."); System.exit(1);
  • 3. } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: taranis."); System.exit(1); } BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } out.close(); in.close(); stdIn.close(); echoSocket.close(); } } Note that EchoClient both writes to and reads from its socket, thereby sending data to and receiving data from the Echo server. Let's walk through the program and investigate the interesting parts. The three statements in the try block of the main method are critical. These lines establish the socket connection between the client and the server and open a PrintWriter and a BufferedReader on the socket: echoSocket = new Socket("taranis", 7); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader( new InputStreamReader(echoSocket.getInputStream())); Question 3 b. Writing the Server Side of a Socket This section shows you how to write a server and the client that goes with it. The server in the client/server pair serves up Knock Knock jokes. Knock Knock jokes are favored by children and are usually vehicles for bad puns. They go like this: Server: "Knock knock!" Client: "Who's there?" Server: "Dexter." Client: "Dexter who?" Server: "Dexter halls with boughs of holly." Client: "Groan." The example consists of two independently running Java programs: the client program and the server program. The client program is implemented by a single class, KnockKnockClient, and is very similar to the EchoClient example from the previous section. The server program is implemented by two classes: KnockKnockServer and KnockKnockProtocol, KnockKnockServer contains the main method for the server program and performs the work of listening to the port, establishing connections, and reading from and writing to the socket. KnockKnockProtocol serves up the jokes. It keeps track of the current joke, the current state (sent knock knock, sent clue, and so on), and returns the various text pieces of the joke
  • 4. depending on the current state. This object implements the protocol-the language that the client and server have agreed to use to communicate. The following section looks in detail at each class in both the client and the server and then shows you how to run them. The Knock Knock Server This section walks through the code that implements the Knock Knock server program. Here is the complete source for the KnockKnockServer class. The server program begins by creating a new ServerSocket object to listen on a specific port (see the statement in bold in the following code segment). When writing a server, choose a port that is not already dedicated to some other service. KnockKnockServer listens on port 4444 because 4 happens to be my favorite number and port 4444 is not being used for anything else in my environment: try { serverSocket = new ServerSocket(4444); } catch (IOException e) { System.out.println("Could not listen on port: 4444"); System.exit(-1); } ServerSocket is a java.net class that provides a system-independent implementation of the server side of a client/server socket connection. The constructor for ServerSocket throws an exception if it can't listen on the specified port (for example, the port is already being used). In this case, the KnockKnockServer has no choice but to exit. If the server successfully binds to its port, then the ServerSocket object is successfully created and the server continues to the next step--accepting a connection from a client (shown in bold): Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.out.println("Accept failed: 4444"); System.exit(-1); } The accept method waits until a client starts up and requests a connection on the host and port of this server (in this example, the server is running on the hypothetical machine taranis on port 4444). When a connection is requested and successfully established, the accept method returns a new Socket object which is bound to the same local port and has its remote address and remote port set to that of the client. The server can communicate with the client over this new Socket and continue to listen for client connection requests on the original ServerSocket This particular version of the program doesn't listen for more client connection requests. However, a modified version of the program is provided in Supporting Multiple Clients. After the server successfully establishes a connection with a client, it communicates with the client using this code:
  • 5. PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine, outputLine; // initiate conversation with client KnockKnockProtocol kkp = new KnockKnockProtocol(); outputLine = kkp.processInput(null); out.println(outputLine); while ((inputLine = in.readLine()) != null) { outputLine = kkp.processInput(inputLine); out.println(outputLine); if (outputLine.equals("Bye.")) break; } The Knock Knock Protocol The KnockKnockProtocol class implements the protocol that the client and server use to communicate. This class keeps track of where the client and the server are in their conversation and serves up the server's response to the client's statements. The KnockKnockServer object contains the text of all the jokes and makes sure that the client gives the proper response to the server's statements. It wouldn't do to have the client say "Dexter who?" when the server says "Knock! Knock!" All client/server pairs must have some protocol by which they speak to each other; otherwise, the data that passes back and forth would be meaningless. The protocol that your own clients and servers use depends entirely on the communication required by them to accomplish the task. The Knock Knock Client The KnockKnockClient class implements the client program that speaks to the KnockKnockServer. KnockKnockClient is based on the EchoClient program in the previous section, Reading from and Writing to a Socket and should be somewhat familiar to you. But we'll go over the program anyway and look at what's happening in the client in the context of what's going on in the server. When you start the client program, the server should already be running and listening to the port, waiting for a client to request a connection. So, the first thing the client program does is to open a socket that is connected to the server running on the hostname and port specified: Question 4- Define RMI. Define the architecture of RMI invocation. Remote Method Invocation (RMI) technology, first introduced in JDK 1.1, elevates network programming to a higher plane. Although RMI is relatively easy to use, it is a remarkably powerful technology and exposes the average Java developer to an entirely new paradigm-- the world of distributed object computing. This course provides you with an in-depth introduction to this versatile technology. RMI has evolved considerably since JDK 1.1, and has been significantly upgraded under the Java 2 SDK. Where applicable, the differences between the two releases will be indicated. The design goal for the RMI architecture was to create a Java distributed object model that integrates naturally into the Java programming language and the local object model. RMI architects have succeeded; creating a system that extends the safety and robustness of the Java architecture to the distributed computing world.
  • 6. Interfaces: The Heart of RMI The RMI architecture is based on one important principle: the definition of behavior and the implementation of that behavior are separate concepts. RMI allows the code that defines the behavior and the code that implements the behavior to remain separate and to run on separate JVMs. This fits nicely with the needs of a distributed system where clients are concerned about the definition of a service and servers are focused on providing the service. Specifically, in RMI, the definition of a remote service is coded using a Java interface. The implementation of the remote service is coded in a class. Therefore, the key to understanding RMI is to remember that interfaces define behavior and classes define implementation. Remember that a Java interface does not contain executable code. RMI supports two classes that implement the same interface. The first class is the implementation of the behavior, and it runs on the server. The second class acts as a proxy for the remote service and it runs on the client. A client program makes method calls on the proxy object, RMI sends the request to the remote JVM, and forwards it to the implementation. Any return values provided by the implementation are sent back to the proxy and then to the client's program. RMI Architecture Layers: With an understanding of the high-level RMI architecture, take a look under the covers to see its implementation. The RMI implementation is essentially built from three abstraction layers. The first is the Stub and Skeleton layer, which lies just beneath the view of the developer. This layer intercepts method calls made by the client to the interface reference variable and redirects these calls to a remote RMI service. The next layer is the Remote Reference Layer. This layer understands how to interpret and manage references made from clients to the remote service objects. In JDK 1.1, this layer connects clients to remote service objects that are running and exported on a server. The connection is a one-to-one (unicast) link. In the Java 2 SDK, this layer was enhanced to support the activation of dormant remote service objects via Remote Object Activation. The transport layer is based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies. By using a layered architecture each of the layers could be enhanced or replaced without affecting the rest of the system. For example, the transport layer could be replaced by a UDP/IP layer without affecting the upper layers. Stub and Skeleton Layer: The stub and skeleton layer of RMI lie just beneath the view of the Java developer. In this layer, RMI uses the Proxy design pattern as described in the book, Design Patterns by Gamma, Helm, Johnson and Vlissides. In the Proxy pattern, an object in one context is represented by another (the proxy) in a separate context. The proxy knows how to forward method calls between the participating objects. The following class diagram illustrates the Proxy pattern. Remote Reference Layer The Remote Reference Layers defines and supports the invocation semantics of the RMI connection. This layer provides a RemoteRef object that represents the link to the remote service implementation object.
  • 7. The stub objects use the invoke() method in RemoteRef to forward the method call. The RemoteRef object understands the invocation semantics for remote services. The JDK 1.1 implementation of RMI provides only one way for clients to connect to remote service implementations: a unicast, point-to-point connection. Before a client can use a remote service, the remote service must be instantiated on the server and exported to the RMI system. (If it is the primary service, it must also be named and registered in the RMI Registry). The Java 2 SDK implementation of RMI adds a new semantic for the client-server connection. In this version, RMI supports activatable remote objects. When a method call is made to the proxy for an activatable object, RMI determines if the remote service implementation object is dormant. If it is dormant, RMI will instantiate the object and restore its state from a disk file. Once an activatable object is in memory, it behaves just like JDK 1.1 remote service implementation objects. Other types of connection semantics are possible. For example, with multicast, a single proxy could send a method request to multiple implementations simultaneously and accept the first reply (this improves response time and possibly improves availability). In the future, Sun may add additional invocation semantics to RMI. Transport Layer: The Transport Layer makes the connection between JVMs. All connections are stream-based network connections that use TCP/IP. Even if two JVMs are running on the same physical computer, they connect through their host computer's TCP/IP network protocol stack. (This is why you must have an operational TCP/IP configuration on your computer to run the Exercises in this course). The following diagram shows the unfettered use of TCP/IP connections between JVMs. Question 5.a- Write Java program to print the address of the study center. class Address { public static void main(String arg[]) { String name="SIKKIM MANIPAL UNIVERSITY UTTARAKHAND,INDIA"; String center="IT CAMPUS ,HALDWANI"; String detail="2ND FLOOR, UTTRANCHAL TRADE CENTRE, NAINITAL RD,TIKONIA "; String tel="05946-260225, 9259937438"; System.out.println(name);System.out.println(center); System.out.println(detail);System.out.println(tel); } } Question 5.b- Write a Java program to find the sum of 1+3+5+…. for 10 terms in the series. import java.io.*; class sum
  • 8. { public static void main(String arg[])throws IOException { InputStreamReader read=new InputStreamReader(System.in); BufferedReader in=new BufferedReader(read); int i,n,s=0; System.out.println(“Enter nth term=”); n=Integer.parseInt(in.readLine()); for(i=0;i<=n;i++) { if(i%2!=0) { s=s+i; } } System.out.println(“Sum of series=”+s); } } Question 6- Write a program to copy one file to another file? import java.io.*; public class Main { public static void main(String[] args) throws Exception { BufferedWriter out1 = new BufferedWriter (new FileWriter("srcfile")); out1.write("string to be copiedn"); out1.close(); InputStream in = new FileInputStream (new File("srcfile")); OutputStream out = new FileOutputStream (new File("destnfile")); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); BufferedReader in1 = new BufferedReader (new FileReader("destnfile")); String str; while ((str = in1.readLine()) != null) { System.out.println(str); } in.close(); } }