Packages,: Stream Based
Packages,: Stream Based
Packages,: Stream Based
2
STREAM BASED 1/0 (java.io) SIA GROUP
PART-A
SHORT QUESTIONS WITH SOLUTIONS
a1 Define a Package? What is its use in j va? Explain.
(Model Paper-, a1(¢) |
AprilMay-18(R16). 01(C
Answer:
Package
functionality. It acts as a
Package is a mechanism that organizes classes and interfaces. It groups them based on their
user-defined packages. Java API consists
contaner 1or the classes. Packages are of two types namely Java API Package and a
of various packages which contain classes. Packages involve in access control
mechanism of Java. A class which is define in
is beyond the package.
package will be private to the package only. It cannot be accessed by a code which
Syntar
access_speccifier interface interface_name
Ivariables declaration;
l/methods declaration;
OR
Define interface.
Nov.Dec.-17(R13),
a1
Answer:
Interfaces
implement the concept ol muupie inherilance. docss no
It
Interlaces are similar to that of classes. It is specifically used to
n
name, parameters
information about and return type. Th
contain instance varinbles. Interface methods are abstract and contains variah
is also allowed to contain methods and
do not have 'implementation details and are publicly by default. An interface
are responsible 1or proVIding implementati
which are only abstract and final respectively. The class which use the interface
lation
2. void write(int c): This method is used to write the characters to the output stream.
3. void write(char| ] arr): This method is used to wrile a complete chararray to the output stream.
. Abstract void close(O: This method is used to close the output stream and release
the resources connected to
ok for the SIA GROUP LOGO 2 on the TITLE COVER
before you buy
2.3
UNIT-2 Packages, Interfaces and Stream Based l/O (java.io)
Enumerated data type can be defined as a data type which allows lhe user to creale own datu lype and also define valucs
to tthe data type Can be creatled by using a keyword 'enum
variables of this type. It is a uscr-delined data type. An enuneraleu
Yntax of enumerated data type is as follows,
Syntax
Cnum datatype_nane
SPECT
EIRUM aL11M.OM 1OOMaa rOp rMCMEEDING STIUDENTS
2.4 ru-HYDERABAD
JAVA PROGRAMMING IJNTU-HYDED.
Q10. What is the use of auto boxing in java? Explain.
Answer:
Nov/Dec.-18(R
Autoboxing
ana
The automatic process of
encapsulating or boxing a primitive type into its cquivalent type
Integer, Short, Byte, Character or wruppCT (1.e., Double,
Boolean), when its object is required is called autoboxing. In other Fla
conversion of primitive type into
objects. Instead, it allows to assign
an object. It avoids wrapping up
the value of a primitive type to
words, autoboxing an
of primitive data types ihrougn manual or explicit cons an
isan utor
cil construcin
the reference of a type wrapper.
Example
Integer itw = 100;
HAutobox int to Integer
Instead of,
Integer itw = new Integer(100);
Q11. /Wrap intointeger
Discuss in brief about generics.
Answer
Generics
Generics is a concept in Java that
That is same algorithm can enables a programmer to define and
be applied multiple times apply an algorithm irrespective
possible to create classes, interfaces on many data types without cenforcing ofthe data te
and method that can be executed in additional cflort. Using genericitis
data. Such methods/classes a type-safer manner independent
program in type-safe are referred as generic methods/classes. The major of any specific typeof
mode. Moreover, generic expands advantage of using generic is that it
the programmer ability in reusing executes the
Syntax the code.
ass className<Datatype.param 1, Datatype param 2,...Datatype param
n)
I/Statement
PART-B
ESSAY QUESTIONS WITH sOLUTIONS
2.1 PACKAGES
2.1.1 Dofining a Package, CLASSPATH
Swer
It acts as a
ackage
classes interfaces. It groups them based on their functionality.
Package is a mechanism that organizes and packages. Java APl consistsa
Packages are of two types namely Java API Package and user-defined which is define in
ntainer lor the classes. control mechanism of Java. A class
contain classes. Packages involve in access
various packages which is beyond the package.
It cannot be accessed by a code which
ckage will be private to the package only.
reating a Package proceeded with keyword
'package' keyword. The name of the package should be
A package is created or defined using
called user-defined packages.
ackage' in its declaration. These packages are
package package_name;
is included in the default package.
Package are stored in directories
the classname bee
the package statement is not used then the filc. Multiple packages can
a
If
are contained in file system. All
the classes of a file belong to the package contained in
cated as follows,
package packagel[,packagc2|.package3]}:
Iample
package mypack1;
public class Student
utput
Cyavapgm>javac mypack 1/Studentjava
Cyavapgm>java mypack1.Student
Welcome to package program
.Discuss about CLASSPATH environment variables. (Model Paper-l, Q4{a) IApriuMay-18(R16), as(a))
Answer
LASSPATI
which gives path or location ol the class which is being currently used. When
ASSPATIH' can be defined as a statement
package programmer S trying to execute one ol the classes in it, then it is important
to
icreated by a programmer and if the
two concepts are being implemented
the Juva looks for the package. In order to solve ihis problem,
eTeere
ich
run-time system
as follows,
V.Lecute in
Same Package
ot he package. he class ile also nmust be saved in the
tthisconcept, the class must be stored in the same location
a result.
cAg and now if this program is exccuted.then gives positivC
it
void display)
AND DISTRIBUTORS");
System.out.println("WELCOME TO SIA PUBLISHERS
class TesteP
})
public static void main(String args[
L.display( ):
Output
c:javapgm>javac cp/Testep.java
c:javapgm>java cp.Testcp
WELCOME TO SIA PUBLISHERS AND DISTRIBUTORS
Here, 'cp' be a package.
Test' and Testcp' are two classes of ep' package.
If you need to run Testcp class then type the following command,
java Testcp
This command line argument is correct only if class path is set. If the class path is not set, then the two classes Test
Testcp must be saved in cp package and .class file of Testep class must be saved in cp package.
Now, the program can be run as,
java cp.Testep
RUNLoo for the SIA GROUP LOGO on the TITLE COVER before you buy
wIT-2 Packages, Interfaces and Stream Based 1/o (java.io) 2.7
Many levels of access that are required by the above categories can be achieved by the following access spceifiers
1. Public
2. Private
3. Protected and
4. Default.
Classes/Access Public Private Protected Default
Specifier (No Modifier)
Same class
N Y Y
Same package
subclass
Y
Same package N
non-subclass
N N
DifTerent package
subclass
Y N N N
Different package
non-subclass
Table: Accessing Members of Class
above table,
In the
Y-It denotes Yes
N-It denotes No.
Public package and also the classes of
'Public' can be accessed or used by the classes of the same
A member when declared as
as it will not have any restrictions.
other packages. This member
can be accessed by any package
Private by the members ot that class
itself. This member will be
can only be accessed
A member whep declared as 'Private'
it is declared.
restricted to the package in which
Protected as well as to the subclasses of the
Protected' will be restricted to the current package and
A member when declared as
packages present in it.
Default (No Modifier). il can said to be have delault
access. This member will be restricted
access specifier then
A member when does not have any will have public access within the
same package and private access
declared. So, this member
to the package in which it is
to other packages.
. Explain how packages can be importea.
OR
importing and accessing a package with suitable examples.
Describe the process of Nov./Dec.-17(R16), Q5(b)
Answer
Accessing a Package
only be accessed using import
a
statenment. Ihe memberS of package such as
Packages that are defincd by the user can package name. Syntax for
proceeding the classnanme wilh import keyword and
an be accessed from some other
ccessing a class is as follows,
package by
package_name.classname
import name is the name ol the class that is to be imported
ported
the above statement, packagc name is the
name of the package and class
n import all the contents of a package then tlhe following syntax is used
articular class. In cae the user want to
if
inport package_name."; in other packages. The private and protected members
accessible
he members declarcd as public and protected are only
t
wECT
allowed to be accessed in other packages.
TRUM AL-IN-ONE JOuRMAL FOR ENGINEERING STUDENTS SIA GROUP 2
TU-HYDERAts
JAVA PR0GRAMMING LJNTU-HYDER,
2.8
Example
package mypack;
class Student
int sid-25;
import mypack."
class, Details
Q18. What is the accessibility of a public method or field inside a non-public class or intertace? Expain.
Answer: HosDer17(R15, (Z
A public method or field defined inside a non public class is only accessible to the members of the package to wtach
i
belongs. They are acessible to some other access point ie. a public interface or public superclass. The members of a chas e
interface are accessible only within the class or interface through which they are accessed. A protected or private class has
h
default package access so that the public methods of ficlds of that class are not visible out of the package.
In these two situations, the public class member has complete public access even if the class
has package access. Initia
the public interface cexposes the methods of package private class which implements the interface. Then the methods that impe
ment the interface will be visible out of the package.
Aparet class that is public containing publie methods can also expose the methods of package-private subclass. Ifrte
ence is used to access instance of subclass from the parent class then any public method of the
parent class becomes accessie
to all the classes. Through dynamic binding the actual method body that is
invoked ill belong to the package-private subcias
2.2 INTERFACES
2.2.1 Defining an Interface, Implementing Interfaces
Q19. Discuss how interfaces are defined and implemented.
OR
How to design and implement an interface in
Java? Give an example.
Answer Nov/Dec.-18/R16), C4
Defining an Interface
Interfaces ure similar to that of classes. It is specifically
contain instance variables. Interface methods are
abstract and contains information about name, parameters and return
t
used to implement the concept of multiple inheritance. does
h
do not have implementation details and
are publicly by default. An interface is also allowed i
to contain methods and v
whch are only abstract and final respectively. The class which use the
code for these methods. interface are responsible for providing impie
Syntar
access_specifier interface interface_name
variables declaration;
methods declaration
An interface is defined
using the keyword "interface"
end the interfaces that are extended. All followed by the interface name. The interface header ucfines s
the member declarations are included
in the interface body.
3 Look for the SlA GROUP LOGO on the TITLE CoVER bofore you buy
iNIT-2 Packages, Interfaces and Stream Based 1/o (java.io) 2.9
Example
public intertace student
Implementing an Interface
declaration must lncc
After an intertace is defined it can be implemented by multiple interfaces. For this purpose, the class
defined by the interiace. A Cluss
implements clause followed by interface name. Then the class can implement the methods that are
using comma's. he
T
names separated
can implement more than one intertace at a time. Its declaration should include the interface must be same
implementing method
methods implementng the interlace must be declared as public. The signature type of the
as the signature type in the intertface definition.
Syntax
class class_names implements interface_name
class body;
Example
interface student
void display%
void display()
class Demo
);
Displaydetails d = new Displaydetails(
d.display(
4 Both the interface and class can contain linal, stalic variables and static method implementation.
5. Uscr cannot create object for both interface and class.
6. The syntax of interface is similar to the class.
Interfacc and class both are used to create new reference type.
a21. Write in detail about accessing implementations through interface
references.
Answer :
Example
eriace student
void display ):
System.out.println("Hello"):
pubhc class
Demo
= 3.14;
public final static double pi y)%
computefdouble x,double
public abstract double
x, double y)
public double compute(double
return(pix*y);
class Testlnterfaces2
J)
public static void main(String argsl
Output
643.7
valuc as finnl ,nd a method compute( ). the body offthis method
h n the above exumple, Shape in un in
nt defines pi
returns l'c valuc conputed.
interlace Shape and
en by thc class Circle
that implements the
TRUM ALLAN-ONE EMGINEERING STUDENTS SIA
GROUP
JouRNAL FOR
JAVA PROGRANMING IJNTU-HYDERAR.
ABAD
12
mplementatioa
Partial L
ample
interface Shar e
retupr"i'y
class Testimplementation
T id 0,
p ablic abstract void getDetaiis( )
aS Loc for the SlA GROUP LeGO on the TITLE COVER before you buy
UNIT-2 Packages, Interfaces and Stream Based /O java.io) 2.13
String qualification;
double allowance;
String rank;
String myname;
imtmyid;
public Manager(String name1, int idl, String qualificationl, double allowance 1, String rankl)
myname = namel;
myid = id1;
qualification = qualification1;
allowance = allowance1;
rank = rank1;
System.out.println(*"Manager Particulars:");
System.out.println("Name:" + myname );:
System.out.println("ID:" + myid);
System.out.println("Qualification:" +qualification);
System.out.println("Rank:" + rank);
double daily_wage;
int overtime;
int grade;
String myname;
int myid;
double daily_wage1, int overtimel, int grade1)
CLabour(String name1, int id1,
myname =
namel
myid idl;
daily_wage = daily_wagel;
overtime = overtimel;
grade gradel;
publicvoid getDetails()
RUM ALLAN-ONE
JOURNAL FOR ENGINEERING
STUDENTS SL CIROUP
JAVA PROGRAMMING JNTU-HYDERAB
ABAD
* overtime);
System.out.prii tl n("Payment Rs." + daily_wage
void msg):
System.out.println("Hello")
name = 'Ravi':
public static final String
= 175;
public static final int id
void display( ):
class Student
implements details
)
public void display(
student is:" +name);
System.out.printin("The name of the + id);
is:"
System.out.printin("The student ld
class College
main(String argsl )
public static void
Student( );
Student s = new
s.display( ):
let .
63
Output
name of the
student is:Ravi
The
175 then the program will not be complied.
The student ld is: id is changed lo 200
student
For instance, if the
ALLHN-ONE JOURNAL FOR
ENGINEERING STUDENTS SIA GROUP
PECTRUM
-HYDERABAD
JAVA PROGRAMMING (JNTU-HYDERA
2.16
Example
class student implements details
It is
an invalid declaration.
Since, the id cannot be reassigned
as it is declared static and final.
andstatic by defnult. Hence, it can be said that interface
variables arefnd
Q26. How interfacos can
bo oxtondod? Explain.
Nov./Dec.17(R13),
How can you oxtend ono OR 05
interface by the other interface? Discuss.
Answer ?
In Java, interfaces
are extended using April/May-18(R16),
insterface that is being the "extends"keyword. The extending interface 0u
extended is called as is called as subinterface andthe
This is done by using superintcrface.The subinterface can access
extends keyword in all the members of its superinterface
the implementation for subinterface declaration.
all the methods The class which implements
Syntax of both superinterfacc and the subinterface must provide
subinterface.
interface sub_interfacc_name
extends super_interface
body of sub_interface
Example
nterface student
sct():
interface Details
cxtends student
voiddisplay():
class studentdetails
implements Details
set()
int id 20
string name- John;
void display()
System.out.println("ld" +
id +
"Name" + name);
class Demo
Details
d.set)
dnew Dctails( ):
d.displayO:
.2
UNIT- Packages, Interfaces and Stream Based 1/0 (java.io) 2.17
TWhat are the differences between an interface and class? Explain with suitable examplo.
Nov./Doc.-16(R13), Q4(a)
AnSWer
The class can be used for the declaration of objects. . The interface cannot be used for
the declaration ot
inheritance.
objects. It can be used only for
access specifier public.
4. The class can use access specifiers such as public, 4. The interlace can only use the
private or protected.
5. Syntax Syntax
Example
Implementation).
For answer refer Unit-11, Q22, Topic: Example (Partial
n,
Stream is a flow of
filc or
socket) through
data between source (such as
a program. 1f the data iiows
en
irom ne
ard aisK, Keyboard etc.,) and
sourc a o
program it
destination (such as cor
is called input stream.
tom program
a to destination, it is called output Stream. 1 ny
ea beandica using the classes If the data flows
o packa and interfaces
EC. Ihe streams are classified into byte sireams and character streams. provided by inva
Byte Streams
The byte
)
SSes
streams are used for reading and wrng une
na Dytcs
of byte stream are classified into inpulstream and outputStream. which represent the primitive data types.
All the
InputStream
1s the base class
of all the input streams of Java 10 API.
ECTRUM
ILL-AN-ONE JOURNAL
FOR ENGINEERING STUDENTS
SIA GROUP 0
JAVA PRoGRAMMING JNTU-HYDE
ERABE
InputStream
Objectlnput StringBuffer
Pipedlnput Sequencelnput InputStream
Filelnput ByteArray stream
stream stream
Stream InputStream
Filterlnput
stream
BufTeredlInput
Pushbacklnput
LincNumber Datalnput stream
stream stream
InputStream
Figure: Classification of
InputStream Class
Description
Class
file.
It is an InputStream used to read from a
1. FilelnputStream
byte arrays as streams and store them
in a
ByteAraylnputStream It is used to read the data from
2.
buffer.
(b) DatalnputStream used to allow an application to read the Java primltive data types from
It is
(c) BufferedinputStream Itis used to add the additional functionality to some other input stream.
Additional functionality includes buffering the input and supporting mark
and reset methods.
FilcOutput PipedOutput
Stream FilterOutput ByteArrayOutput
Strcam
Stream Stream
Datadutput BullercdOutput
Stueam Print Stream
Stream
Figure: Clossilicotion
of OutputStroam
Look for the Class
SiA GROUP LOGO
c n
2.19
UNIT-2 Packages, Interfaces and Stream Based UO Gava.io)
Class Description
1.FileOutputStream lt s used for writing the data to a file or to file descriptor.
PipodOutputStream It is used by an object to send data through it.
the output streams.
3.| FiherOutputStream it is the base class of the output stream classes that filter
data types to output
(a) DataOutputStream lt is used to allow an application to write the primitive
stream.
which an application
b)BufferedOutputStream used to implement a buffered output stream to
lt ts
can write bytes by calling the system only once.
types of data values)
(c) PrintStream t is used to add functionality (such as to print various
to some other output stream.
in which the data is
ByteArayOutputStream This class is used to implement an output stream
WTitten to a byteAmay
Character Streams
For answer refer Unit-II, Q29
Model Paper-lI, Q4(b)
a29. Explain character stream classes.
OR
What are the methods available in the Character Streams? Discuss.
Refer Only Topic: Methods in Charater Streas
Nov./Dec.-18(R16), Q5(a)
Answer
Character Streams
Character streams are used for performing the input and the output operations on 16-bit unicode characters. All the classes
of n are classified into reader and writer.
Reader
l1
is the base class of all the character input streams.
Reader
Class Description
BuffcredReader is used for reading the text
It
trom the character
them for efficient reading. input stream and then
butfering
LincNumberReader It is a buffered character
input stream used
CharAray Reader keep track of the
to
It is used for implementing
the character buffer
line numbers.
input stream. which is used as character
InputStreamReader It used to read bytes
is
and decode them
FileReader It is used to read to characters by
the character files. using a charset.
FilterReader It is used to read
the filtered character
PushbackRcader It is a character streams.
stream reader
hack to the stream. that is used to
allow the characters
PipedReade It is a piped character to be pushed
StringReader input stream.
It is a character
stream extracted
SPE
PECTRUM ALAN-ONE JOURNAL from a string.
FOR ENGINEERING
STUDENTS
Writer
streams.
It is the base class of all the output
Writer
FileRcader
Figure: Classification of Writer Class
Class Description
BufferedWriter It is used to write text to character output stream by butfering the characters
1. for efficient writing.
3. OutputStream Writer It is used to encode the characters into bytes usign a charset.
using both byte strenms and characler streams. Ilowever, byte sireams Can be used to manipulate nimple prouran,
deal with keybonrd input nnd sample progrnms. The various methods present in luputStrentn clann nre nn folowi,
(a) Int nvallable(): This method cnn return the count of bytes prexently avnilable for reuding
(b) vold close(): This method eloses the input nnd if hurther nttempts can be per forned to rcad input, this nethod wil one
an 1OExccption.
aned that nurk C D alid
(c) votd mark(int numBytes): This mcthod pluces n mark nt curent input value in input trcanm
until the specilied numBytes arc rend.
by calling nrC
(d) boolenn marksupportcd( This method rcturns truc ifthe methods mark( ) or reset( ) can be upportcad
):
(c) Int rend(): This method returns an integer wlhich reprosents the next inpt prescnt nnd returns-
1, il end ol
rc
encountered.
rend succeNIy
int rend(bytel | buffer): This method reads buller.length bytes into buller und returns the count of bylea
(0
If end ofstream is encountered, this method relurms- .
by initiuting
int rend(byte | | buffer, int ofiset, Int numBytex): This method reads numl3ytes number of bytes into buller
nt buller [oflsct] and returns the count of bytes rend suceessfully. If the input stream is ecompleted, this method
returns-
(h) vold reset(): This method resets the input pointer to the mark which can be set previously
and ulso returns the
(0 long skip(long numBytes): This method skips or ignores the numBytes, bytes wlhile rending inpit
count of bytes that can be ignored.
be created as an instanee of InputStream class.
These mcthods can be accessed by using the system.in object which can
The most commonly uscd method in luput Stream class rend( which
is ) can rend the bytes.
as follows,
The three ways in which read( method can be delined are
)
Example Program
import java.io.;
class ConsolelnputExample
SA sPOL
JAVA PROGRAMMING IJNTU-HYDERA.
BAD)
main(String[ ] args)
public static void
int
x= 'N:
System.out.print("n):
System.out.println(x):
Constructors
File(String path): This constructor creates the file object from the path name of the file.
File(String path, String fname): This constructor creates file object from a path and file name.
creates the file object from the given directory and file nau
File(File dirObject, String fname): This constructor
File(URI uriobject): This constructor ereates file object from the file specified by uriObject.
Methods
File class defines the following methods to manipulate file information:
String getName( ): Returns the name of the file or directory.
String getParent( ): Returns the parent directory name
Look for the SIA dROUP LOGO 2 on the TiTLE COVER before you buy
UNIT-2 Packages, Interfaces and Stream Based l/O
(java.io)
2.23
boolenn exists( ): Returns true if this file exists otherwise returns false.
boolean isFile( ): Retums true if the invoking object is a file. Otherwise retums false. It returns false if file is not a
boolenn isDirectory( ): Returns true if the file denoted by object is a directory. Otherwise returns false."
na file
boolean renameTo(File newfname): Renames the file with newfname and returns true if the file is successlully rena d
Otherwise returns falsc.
boolean delete( ): Delete the file or the directory. Directory is deleted if and only if it is empty. It returns true i he ne
deleted. Otherwise it returns falsc.
Stringl | list( ): Returns a string array consisting of a list of files and directories present in a dircctory denoted by ite
o
directory 1s creatcu.
boolcan mkdir ): Creates a dircctory with the name specificd by file object and rcturns truc if
Otherwise returns false.
String getAbsolutePath(): Relurns the absolute path of a file or directory denoted by file objcct.
file is readable. OnerwISe
boolean canRend(): Determines whether a file has read permission or not. Returns true if the
returns false.
permission or not. Returns tnue if file wrilable. Ouierwis
is
boolean Canwrite): Determines whether a file has writc
returns fnlse.
Example
import java.io.";
class UsingFile
1
public static void main(String args[]) throws 1OException
String s
File f new File("c:/mydir/text.txt");
s f.exists( )? "File exists"" : "file does not exist"
System.out.printin(s);
s f.isFile( )? "Is a normal file": "Is a special file"
System.out.println(s):
File f1 = new File("c:/mydir/subdir");
f1.mkdir( ):
iff1.isDirectory( )
System.out.println("Directory contents:");
String str[= f1.list(
if(str.length=0)
:
System.out.println("Directory is empty");
else
for(int i=0; isstr.length; it+)
System.out.println(str[i]);
else
System.out.println(*"ls not a directory");
Output
File exists
Is a normal file
Directory name:subdir
Directory contents:
Directory is empty
SPECTRUM ALL-IN-ONE JOURAL FOR ENGINEERING STUDENTS
JAVA PROGRAMMING IJNTU-HYDr.
YDERABA
2.24
2.3.4 Reading and Writing Files
Q33. Explain how an input can be read from file using byte streams.
Answer:
The file input can be read using the following steps,
Stepl
Initially, the file must be opened by creating an îmstance to FilelnputStream class. This can be done by usine the
fnlowz
constructor,
Syntax
FilelnputStream(Stream filename) throws FileNotFoundException
Here, filename is the name of required file which must' be opened. If the
specified file is not available.
FileNotFoundException can be thrown which can be called as a subclass th
of 1OException.
Step2
Next, the opened file can be read using read() method.
This method can be declared as follows,
Syntax
int read() throws 1OException
Here, the read( ) method reads a
single byte from the file and returns an integer
method returns 1. If an exception is value. If the data in file is completed, tis
generated, this method can throw an 1OException.
-
read( ) method which can be used in This read() method is similar with the
reading consele input
Step3
After the completion of reading data
from file, the file must be closed.
to declare close() method is as
follows. This can be done using close( ) method. The
syilar
void close( ) throws IOException
After closing the file, the system
resources allocated to the file
If the file cannot be closed after the can be released and allows other file
completion of task. then the to use these resors
be used by other files. resources remain allocated
to the file and these resources can0
Example Program
import java.io.";
class ReadlnputExample
nt
FilelnputSteam objfis = null;
ifargs.lengh! = 1)
System.out.printin(
The file is ");
retun:
try
objfis.read( ):
iflx - 1)
System.out.print((charx).
while x! - -
1):
Lo
*O the SIA GROUP LOGO on the TmE COVER befoe
NIT-2 Packages, Intertaces and Stream
UNI 2.25
Based 1/O (java.io)
System.out.printin("File read
successfully"
catch(FileNotFoundException ex)
ow catch(IOException ex)
System.out.printin("/OException raised"):
e,
te finally
try
fin.close(O:
eted.tu
catch(1OException ex)
with
he symu
resourcs
ces Can
Q34. Discuss the concept of writing data into file using byte streams.
Answer
can be done by satisfying the below steps,
The data can be written into file using byte streams. This
Stepl
can be done by creating an object to FileOutputStream class. The two
Initially, the file must be opened for output. This
FileOutputStream class are as follows,
Constructors that can be used to declare
Syntax
(a) FileOutputStream(String
fileName) throws FileNotFound Exception
boolean append) throws FileNotFoundException
(b) FileOutputStream(String fileName,
Here. filename file in which the data must be written. If append variable is initialized with true,
is the name of required
the new data can be written after the end of file. lf is Talse, then new data can be overwritten with existing content. If the
it
hen
name of the file similar can be deleted and a new file with specified name can be
with existing file, then the exISstmg nie created.
FileNotFound Exception can be thrown.
the file cannot be created, then
Step2
Next. the data can be written into the nic usgw ctnod. 1he declaration of write( ) method
is as follows
Syntax
1OException
void write(int x) throws
This method can write the bytes into file specified by x. Even though the variable x can be declared
file. 1f an error 1s raised while writing as integer, only the
low order 8 bits can be written into the data into file, an 1OException
can be thrown.
Step3
After the successful completion of writing data into hle, then the file must be closed.
method This can be done using following
Syntax
void close ) throws 1OFxception
Here, he closel ) method release all system resources and permits
other files to use
at the output in buffer is writle these resources. This
method ensures
SPECTRUM ALAN-ONE JOURNAL FOR ENGINEERING
STUDENTS
SIAGROUP
JAVA PROGRAMMING lJNTU-HYD
DERA
2.26
Example Program
import java.io.*;
public class WriteFilcDemo
] args)
public static void main(Stringl .
File
String data = "This is text";
try
File("e:/example/newfile.txt");
f= new
objfos = new
FilelnputStream(:
if(!f.exists( ))
f.createNewFile( );
data.getBytes( );
byte[ datal =
|
objfos.write(data);
objfos.flush():
objfos.close( );
System.out.println("Data wriften successfully");
ex.printStackTrace(
finally
try
objfos.close( );
catch(1OException ex)
Look for the SIA GROUP LOGO on the TITLE COVER before you Du
aes ana Stream Base VO Gava.io)
2.27
2.3.5 Random Access Flle
Operations
o35. Discuss the concept of Random access file. Also explain its operations.
Answer Madel Papnd O5a
Random Access
The Random Access File can be defincd as a class uhich can
access the files called as random access files. Ii ts cnapsuiatd
inRandomAcessi cas The content present in random acvess file can be aseesd in rmyuirad onder.
Flc class cannt be defined from Input Stream or Output Stream clases However Random Access Füe
The Random Access
class can implement
Datalnput and DataOutput intertaces that can perform bhasic 10 operations. 1While accessing the random aes
filk. file pounter
can be uscd to represent the content of file. When the random access file is opened. the filc pointer represents the hegmnng ntt
pum
le and location is represented as 0. If read or urite operations is perfomed on random acvess file. then the psition of hie
moves based on the number of bytes read or written. The Random Access File is defined in Java.io. Random Access pac
and this package can be inherited from Java.lang.objoct package. Random Access Filk class provides difiercent medes io as ie
the file. They are as follows,
r This mode used to read the file but not to write in the file
Answer : the co
and to wrile string a to
methods to read a strung rom console il IS knowIn as the convenicue
The java.io.comsole class provides the system.out. Therelore
the system.in and
functionality of the console is provided through ll uses simple methods to reid the strings Irom cosole. The console oli
is also used to implement
the lushable interlace.
instead ol supplying constructorS.
obtaiunedaccessed by calling system console()
Static console consolet) return a null value
console will be returned if available. Otlherwise it will automatically
The reference of the stubclass of Error and specin
) throws 1OError. 1O1:rror is the
cifles
method readlLine(
Incase of input errors one of the console it is a type ol lailure that makes many users to suller,
casy 10 cateh au lOLError. Since
the 1/O erors of a program. is not
It
il on the console arrays containing
read tle password string without displaying
The methods like readPassword( will sollware will be able to
)
be made zeroout. This will cut down tlhe chance that malicious
a
the user string and password should not
that are defined by a console are as follows,
retrieve the password. Ditlerent methods
Description/purpose
Method name
with the console.
lt returns the reference to Rader object associaled
Reader reader()
with the console.
Print Writer wrilcr() t returns thewriter object associaledthe input devices i.c., keyboard.
A
tring strng:
console c;
Look for the SIA GROUP LOGO on the TITLE COVER before you buy
2.29
NIT-2 Packagos, Intorfaçes and Sream Basod /O (java.io)
Systcm.consolc( ):
1nul) return;
ilcm
strng c.rendl ine("Enter the string:"):
c.print"The string is: "sln'", strug):
utput
Enter a string: Java console class
The string is: Java console class,
Objectloput Interfuce
to sup
The Objectlnput interface is derived from Datalnput interface. This inteiace defines the following methods
object serialization. These methods throws an 1OException on any error.
int availuble() Returns the number of bytes available for reading.
-
long skip(long nBytes) - Skips the specified number of bytes and returns actual naumber of bytes skipped.
ObjectinputStream Class
rading
The ObjectinputStrcam class is derived from the InputStream class and Objectlnput interface. This class is used for i
objects from a strean. It has the following constructor.
Constructors
ObjectlnputStream(lnputStream in)
This constructor may throw lOException and StreamCorrupted Exception.
ObjectnputSueam clas defines the following methods. All of these methods throws an 1OException on error.
Look for the SIA GROUP LOGO on tho TITLE COVER beforo you buy
2.31
NIT-2 Packages, nterfaces and Stroam Basod /O (ava.lo)
Methods
available( )- turns the number of bytes available for reading.
stream.
yoid close()-Closes the
int
-
rend() Reads and returns the inleger representation of next available byte
boolean valhue.
hoolean rendBoolenn)- Reads
a
Syntax
enum dalatype_name
Cnum_typevarinblc;
Eiample
Monthsm
s delined by the enumeration. For cxample
only oBc vines
variable of type cenum con be assigncd ue cnuim vuriables uing dot operator
he type
Mur,
... or Dec. The
vinlucs urc nsIgned io
1 m Can be cither Jun, F'eb,
Syntar
m Months.Mur
A an Cnum valuc by making all the constant valucs of un enum as casc
switch alement can be controlled using statcments
ECTRUM
EMGINEERING STUDENTS
LIN-ONE JOURNAL FOR SIA GROUP
2
JAV DERABADA
2.32
switch(mn)
case Jan:
case Feb:
case Mar
type
Dame as Months
Jana
used in the case statement necd not be qualilicd by their cnuiicral1on Jor all its case contam
The enum constants cxpression provides the cnuin iype Constarts
in the switch
Months.Feb. Because, the enum variable 'm' uscd name. That i
a println) statenent by spccilying its qualified hat is,
an enum constant can be displaycd using
The value of
enum_type.value.
Example
The statement,
System.out.println("Current Month:" + Month.Mar);
prints March
Program
public enum month
December
January, February, Márch, April, May, June, July, August, Scptember, October, Novenber,
Month mnth;
public EnumExample(Month mnth)
this.mnth = mnth;
switch(mnth
case: January:
System.out.println("Winter");
break;
case: "May':
System.oul.printin("Summer");
break;
LOOk for the SIA GROUP LOGO 2 on tho TITLE COVER bofore you buy
UNIT-2 Packages, Interfaces and Stream Based /O (java.io) 2.33
case: August":
System.out.println("Rainy");
break;
default:
System.out.println("Spring"):
Autoboxing
or boxing a primitive type into its
equivalent type wrapper (i.e., Double, Float,
The automatic process of encapsulating
autoboxing. In other words, autoboxing is
Long, Integer, Short, Byte, Character or
Boolean), when iis object is required is called
up of primitive data types through manual or explicit
an automatic conversion of primitive type
into an object. lt avoids wrapping
assign the value of a primitive
type to the reference of a type wrapper.
construction objects. Instead, it allows to
Example
= IAutobox int to Integer
Integer itw 100;
Instead of,
I/Wrap into integer
Integer itw = new Integer(100);
Auto-Unboxing
Or unboxing the value of an encapsulated or a boxed -object from
The automatic process of extracting a type wrapper,
when its object is required is called auto-unboxIng.
m Oer words, aulo-unbOxing is an automatic conversinn ofar
n object into
value from the type through wrapper intValue() or getvalue( ) methods.
a
primitive type. It avoids the extraction of Instead, the
type variable.
otye reference a
of wrapper can be assigned to a primitive
type
Example
Instead of.
SPEC
ECTRUM ALL-IN-ONE JouRNAL FOR ENdINEERING STUDENTS
SIA GROUP
JAVA PROGRAMMING UNTU-HYD.
.34 ERABAD)
Autoboring/Unboxing in Methods
When an argument is passed to or returned from a method, the autoboxingunboxing occurs. Consider the following
f
examyle
ogram,
class AutoBox_Unbox
return ,
type wrapper reference 'm' is autounboxed to int
tput
300 tesrs
in the above program, the
meth( ) method of Autobox_Unbox
iorming auto-unbox. In the main( ) method, class takes an integer value and returns
the int value 300 is passed an int value oy
to an integer and later
returns m by performing auto-unbox.
ich autoboxes the int again into
as a parameter to meth( ). This method,
The returned int value is
first autoboxES
an integer. then assigned to an object ofinteg
Autoboxing/Unboxing in
Expressions
In expressions, auto
unboxing is performed on
numeric objects. The result of
Consider the following example, an expression sometimes requires
reboxIE
class AutoBox_Unbox_Exp
int i
w
Double dtw= 33.33:
Integeritwl, itw2, 1SW,
ty twl
299;
ie ofit ta De uiRY ate
System.out.println("values of
itw1:");
Systen.out printin("Initially:", +itw1);
itwl, flAuto unbox then rebox
Sytten ut.printin("After increment", +itwl):
it2-(itw1 10) itwl;
IAuto unbox then rebox
Syatem.out.printint"Value of
itw2",+ itw2);
for the on tho TITLE COVER bofore yo
LoGk SiA GROuP buy
LOGO
UNIT-2 ckages, Interface and Stream Based /O (java.io) 2.35
i= (itwl x 10) + itw1;
/Only autounbox, no rebox
System.out.println("Value of i:", + i);
dtw = itw1 +dtw; /IAuto unbox then rebox
System.out.println("New value of dtw:", + dtw);
isw= ;
switch(isvw) IAuto unbox
case 1:
System.out.println("First year");
break;
case 2:
System.out.println("Second year");
break:
default:
System.out.println(""Not a student"):
Output
Values of itwl
Initially: 299
After increment: 3000
Valuc of itw2: 3300
Value of i: 3300
New valuc of dtw = 3333.33
unboxing it into
nteger object, itwl is performed by first auto
First ycar
the increment operation
on
he expression for
computing the value of itw2, first
In the above cxample program, it back into an
T
integer.
an int, then incrementing its value
and later reboxing later reboxes the result to an integer.
and the computation. It does not
aulD unboxes itwl, then
performs the computation auto-unboxes itwl, then performs
value
computing the of i, irst
atw involves objects of two different type wrappers
The next expression for int. The expression lor
computing reboxing it intoa
'' is already an are added and later the result is stored in dtw after one of
equires reboxing because unboxed first, then they
object. I his obJect is first unboxed and then o 'the
double and integer. They both are numeric
controlled using an integer
is
Ouble. Next, the switch statement
on its int valuc Java.
elincd cases is selected based
generics and generic collections in
40.
Explain the concept of
Answer :
an algorithm irrespective
Generics(Parameterized Type) programmer to deine and apply eforn 1e
that enables
a
ypes without enforcing additional sne
Generics is a concept in Java multiple times on many duta
ype-sater manner independent of anv evec
That be applied
Sane aligorithm caninterfaces liat can De
and method melnouscaS>es. 1 inc
cecu uor
a
advantage of using generic is
that it
o create classes, reusing the code.
d as generie
methods/classes are rcferredgeneric expands the programmer ability in
Such
ToTamD type-safe mode. Moreover,
Syntar param n)
Datatype param 2,....Datatype
CiassNane<Datatypc.param 1,
to generic
class is, new.
Now,the way l declarig
refcrence variable name
n > variable = nevw classname<datatype arg
ru 2... datatype arg n>
..dalalype
arg ,
arg 1,
clasame«datatype arg 1, datatype cons arg n);
arg n-(cons
2.datatype
sPECTRUMM
atype arg
EMGINEERINd STUDENTS SIA GROUP
RL-AN-ONE JOURNAL FOR
JAV GHA ruHYDERA
2.36
Generic Collection because of the type sef y
supporting the concept of generic. This is
Collection framework has been modified for aresla,
framework.
that generic provides to collection the reference belonging tot
collection based code were used by prograrmmer to store only o
rrothe
Earlier pre-generic object are stored in specific collection. Ifa
ensure that the reference of only ma
This required for a programmer to usage pre-gencric collection allOw the proETammer to ualy t
as an error. Morcover, the of
in this regard, than it result it inconvenient. Therefore
to overcome this issur it n
into proper type, thereby making
cast the retrieved references The two maor inproverment made
generic, which enhance the usability and safety ofcollections.
use the concept of
are,
collections over pre-generic collection
proper type in the collection.
It allows a programmer to store reference to object of
1.
a reference retrieved
from a collection. Rather, it perform te
program to manually type cast
2. It doesn't allow the
automatically.
Example Program
import java.util.";
class GenericExample
):
ArrayLlist<String>arrlist = new ArrayList<string>(
arlist.add("welcome"):
arrlist.add("to");
arrlist.add("sia"):
arrlist.add("group");
IteratorString>obj = arlist.iterator( );
while(objl.hasNext( )
va
Here, the arrlist can store the references to objects of string data
type. It is not necessary to cast the returm
automatically. In this program, Iterator and Listlterator interia
next() method into string. The casting can be perlormed
used. These interfaces can also act as generic type. Therefore,
the data type of argument must be accepted with the
auy
aa2
be required at compile time. l1
collections for which the iterator can be oblained. Mean while, type compatibility can
type errors are occurred, they can be detected at compile time rather than throwing exceptions during run-time.
Q41. How to create a generlc class with two type parameters? Explaln.
Answer:
ac
A generic class with two parameters can be created by placing comma between them i.c., the parameters
using a comma as shown beclow,
class Gen<T, X>
The following code illustrates the concept.
Declaration of a generic class with two type parameters T and X
class GenericTwo<T, X>
Look for the SIA GROUP LOGO 2 on the TITLE COVER before you buy
TO1; uavd.O)
2.37
IDeclaration of objects 01 and
02
x 02:
IGeneric constnictor with two
objects of type T and X
GenericTwo(T obj1, X obj2)
objl;
01
02 obj2;
void displayTypes()
displaying the type ofT and X
T get01()
X get02()
ETROM
//Statements
X) nun_arr:
Avg cluss(X[ ]v)
num_arTV
double computeavg)
boolean sane_Avg(Avg_class<?> s)
iffcomputeavg) *s.computcavg ))
rcturn true;
return false;
Loo for tho SIA GROUP LOGO on tho TITLE coVER before you buy
2.
UNIT-2 Packages, Iriterfoces and Stream Based i/O tjvn.io)
12, 4, 6, B, 10;
InteyerI
elassJntcyer wI ~ new Avg_class lnteper-( ),
Avg
double d wI.computeaveragel ).
,
in" d)
System.out.printin ("The average of wi
+
b.length: i t+)
forint i 0;i<
ifla.cquals(b[i}))
return true
return salse;
"John"}:
String Str.ar[ ] = {"Alice", "Bob", "Racheal",
ifisMember("Bob", s))
System.out.println("Bob is a member of string array");
iftisMember("James". s))
not a member of string
array");
System.out.printin("James is
if(lisMember(12, num_arr))
System.out.println("12 is not the member of number array")
In the above program, Gen_Method is a non-generic class in which a statit generic method isMember( ) is declared. This
method checks whether an object is present in the array or not.
Initially in the declaration statement of generic method, the list of pårameters precedes the return type. Here, it must be
ensured that the type of second argument (y) matches with the type of first argument (x) or any of its subclass. This is becaue
y
ype is upperbounded by type x. The type-matching relationship enables the generic method "isMember" to be invoked wib
any of inter-compatible arguments. This method is invoked within the main ()
without specifying the type arguments. The reason
for not specifying the type arguments is that, these arguments are automatically
recognized and types ofX and Y are modihed
inaccordance to the type argument. For instance, consider the statement.
X muximum ():
X minimum ( );
X[] valucN
MaxMin class (X [ ]
v)
Valucs V;
public X minimum ()
Xp valucs [0]:
for(int i 1; i< valucs.length;, it-)
< 0)
if (values i].compareTo (p)
p valucs [i]:
return p
public X maximum ()
Xp valucs (0};
valucs.length; it+)
for(int - 1; i<
i
(valuesli].comparcTo (p)> 0)
if
p valucs [i};
rcturn p;
class Gen_interface
args| )
public static void main (String
ENGINEERINO STUDENTS
PECTR
AN-ONE
ALLAR JouRMAL FOR
-
SIA GRoUP
JAVA PROGRAMMING JNTU-HYDERA
ABAD
System.out.println ("*The maximum value in num_arr" tcl.maximum(0):
System.out.println ("The minimum value in num_arr:+cl.minimun( )):
In the above program, the declaration of generie interface consists of type parameter 'x", which is upper boundl undedto
comparable". It is an in-built interface defined in java.lang, this interface ensures that uhe above program can be invokedwith
comparable objects. l
The statement
class MaxMinClassX extends Comparable <X>> implements MaxMin<x>
Specifies that Max_Min is implemented by MaxMin class. IHere, the type parameter X' is initially declared by MaxMinC hu
and then passed to Max Min interface. It is necessary to ensure that MaxMinC lass is also bounded to the same upperbound au
Max_ Min. After identifying the type parameter, it is passed to the interface Gienerally. it can be said that a class which implemens
a generic interface must also be
generic in order to avoid compilation errors.
For instance, the statement
class MaxMinClass implements Max_Min<X>
Generates an error because the class docsnot deelare type parameter due to which it is
not possible to pass the parameter
to Max_Min. However, this issue can be solved when the class
implement specific type of generic interface like the following
a
class MaxMinClass implements <lnteger>
Advantages of Generic Interface
Generic interface can be implemented for diflerent data types.
L
2 Generic interface enables the user to apply constraints on the
type of data for which it is possible to implement the inter
Q45. Discuss about generic class hierarchies.
Answer
ul Nov./Dec.-17(R13), QYa
Generic Class Hierarehies
A generic class can be one of the
part of class hierarchy in the same non
superclass. The 1ype arguments required by a generic classes. So, it can be either sub ass
classes.
generic superclass in generic elass
hierarchies must be passed through a e s
Generic Superclass
Consider the below example
class Generic <T>
ob
Gencric (Tx)
obj x,
return obj;
Vobj2;
Gencric 2(T x, V y)
super (x);
obj2 y;
V getobj()
return y
class GCHH
class Nongeneric
SPECTRUM
int n;
ALLHN-ONE
JOURNAL FOR
ENGINEERING STUDENTS - SIA GROUP 2
JAVA PROG DERAAO
HonGeneric(int x)
nx
int get)
retum n
NonGeneric
class Generic <T> extends
Tobj
Generic(T a, int b)
super(b):
obj = a;
T getobj()
return obj;
class Hierarchy