Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Packages,: Stream Based

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

UNIT PACKAGES, INTERFACES AND

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;

name. The interface header defines scope


An interface is defined using the kcyword "interface" followed by the interíace
are included in the interface body.
dthe mterfaces that are extended. All the member declarations
Example

public interface student

final int id 20,


final string name John;
void display )

2What in creating/using a package?


is the significance of the CLASSPATH environment variable
Answer Nov Dec.-1T(R16). Q1{4)
or ol the class which is being currently uscd When
LASSPATH' defined as a statement which gives path location
Can be
by u progremmer and if the programmer 1s uing
to execcute one ot he classes tn it, then it is important to
o created
whre the Java run4ime sy stem looks for the packagc.
dez to olve this problem, Iwo concepts are being implemented uhich are as fallows,
FAcute in Same Package
St the Approqmiste (las Poth
CTRUM
LAHONE JOURNAL FOR ENGINEERIHO STUDEMTS SA GROUP
JAVA PROGRAMMING |JNTU-HYDERAD
BADI
2.2
NovJJDec.-16R13).
Q3. What is an interface? Give example. Q1e

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

code for thesc methods.


Example
Interface shape

public final static double pi = 3.14;


public abstract double computer (double x, double y);

class circle implements shape

public double computer (double x, double y)

retum (pi * x * y);

Q4 Define stream. Q11)


Model Paper-,
Answer :
scren
as hle on hard disk, keyboard etc..) and destination (such as computer
Stream is a flow of data between source (such froma
from the source to a program it is called input stream. If the data flows
file or socket) through a program. If the data flows pack
java.io
program to destination, it is caled output stream. 1hey can be handied using the classes and interfaces provided by

a5. What are the methods available in the character streams?


Nov./Dec.17(R16), Q1C
Answer
inlo two classes namely reader and writer.
The methods of character streams are categorized
Methods of Reader Class
1. int readO: This method is used to read the characters from input stream.
array e
This method is used to read a set of characters from the input stream and them in char
2. int read(char| |c): store
3 close( ): This method is used to close the output stream and release the resources connected toi.

Methods ofWriter Class witen


Abstract void flush():This method is used to flush the output stream by pumping out the buffered bytes that arc to be
arelo be

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)

Q6. List the class of reader.


Answer
Class Description
BufferedRcader used lor reading the text from the character input strcam and
then burerng
Is
them for eflicient reading.
keep track of the line numbeS.
LineNumberRcader
1s a bullered character input strcam used to used as characler
2. CharArrayRcader used lor implementing the character buffer which is
is
input stream.
using a charsel.
3. InputStreamRcader t is used to read bytes and decode them to characters by
FileRcader It is used to read the character files.

4. FilterReader It is used to read the Ailtercd charactor streams,


characters to be pushed
PushbackReader character stream reader that is used to allow the
a
is
back to the stream.
5. PipedReader It is a piped character input stream.
StringReader |lt is a character stream extracted from a string.

Q7. What is Console class? What is its use in java??


Nov./Doc.-18(R16), a1(¢)
Answer
a string from console and to write a string to the
console. The
The java.io.console class provides the methods 1o read
Therefore it is known as the convenience class. It
functionality of the console is provided through the system.in and system.out.
is also used to implement the flushable interface. It uses simple
methods to read the strings from console. The console objects are
obtained/accessed by calling systlem console( ) instead of supplying constructors.

Static console console()


Otherwise it will qutomatically return a null value.
The reference of the console will be returned if available.

Incase of input errors one of the console method


readlLine() throws IOError. 1OEror is the subclass of Error and specifies
an 1OError. Since it 1s a type ol lailure that makes many users to suller.
the VO errors of a program. It is not easy to catch
Q8. What is serializable interface?
Answer:
can only be storcd and retrieved i.e., a class that implements this
Objects ofa class that implements Serializable interlace
interface is a serializable class. This interface does not deline any metiods. It 1s used to indicate thnt the objccts of this class
are serializable. Subclasses of a class that implements serializatble interlace are nlso serializable. Serialization does not store the
variables that are declared as transient and static.
Q9. Define enumerated data type.
Answer Modol Papor-il, a1(c)
Enumerated Data Type

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

ValueI, valuc2, .., Valuen

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

Now, the way of declaring reference


to generic class is,
classname<datatype arg 1, datatype arg
2..datatype arg n> variable name =
new classname<datatype arg
a12. How a generic method is datatype arg 2.datatype
arg n>(cons arg 1, cons arg
created?
Answer :
Creating Generic Method
Method that is declared inside
a generic class can be use
"generic method". This method the type parameters
this, it is also possible
can be declared with at least one of the class, thereby making themnethods
type parameter
method is that, the method
to create a generic method
which is defined within a of the respective method itself. In auu
ensures type safety. non-generic class. The gene
primary advanlageu
Syntax for Declaring
Generic Method
list_of_type parameters> return_type
namee_of method (list_of
The list of type parameters are parameters)
separated by commaand are
013. List out the placed beforethe return
type.
benefits of Stream oriented /O.
Answer :
The various benefits IR16)a1
of stream oriented 1/O are as (Model Paper-il,
Q1(d) | ApriuMay-18r
1. It provides a clean abstraction follows,
for complicated asks.
2. User can also create
the custom streaming interface
of filtered stream classes. that is fit to the
data transfer
3. The working of Reader, requirements with thehelp
Writer, InputStream
classes are introduced
further.
and OutputStream
classes will
not be effected/changed when
a
the
Bed even
Look for the SlA GROUP
LOGO on th TITI E
2.5
NIT-2 Packages, Intertaces and Stream Based 1/O (java.io)

PART-B
ESSAY QUESTIONS WITH sOLUTIONS
2.1 PACKAGES
2.1.1 Dofining a Package, CLASSPATH

14. Define a package. How can you create a package?


OR
Explain the proces of defining and creating a package with suitable examples. Nov./Dec.-17(R16), Q4[a)

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

public static void main(String args))

System.out.println("Welcome to package program");

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

Tere, the fite should be cxecuted as,


java packagename.classname

RUM ALLAN-ONE JOuRMAL


FOR ENGINEERING
STUDENTS
S1GROUP
Set the Appropriate
Class Path without any hicrarch
archy
program could be run indcpendently of lap
then the
In this concept, once the
class path is set l
packages. class is available.
location of the package in which the
Here, clasS path is the exact
program could be run as,
When the class path is set, the
java classname
Example
package cP:
import java.io."
class Test

void display)
AND DISTRIBUTORS");
System.out.println("WELCOME TO SIA PUBLISHERS

class TesteP

})
public static void main(String args[

Testt= new Test( );

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

2.1.2 Access Protection, Importing Packages


016. Discuss the different level of access protection available in Java.
Answer: (AprilMay-18(R16), ApriuMay-18(R16, 0
a2(b) |

Java provides many levels of protections to the variables and classs


methods to be visible which are present inside tne
subclasses and packuges. The classes and packages both
encapsulates the name space, scope of variables and
consist of data and code whereas package consist of related
classes and sub packages. Because of the interaction betwe metnols
and packages, Java offers the following
four categories of visibility for accessing class
membets.
1. Subclasses in the same package
Non-sub classes in the same package
3. Sub classes in different
packages
. Classes that are neither in the same
package nor in the subclass.

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

public static void main(String args[ })

Student s=new Student( ):


System.out.println("Student ID:" +s.sid)

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

final int id- 20;


final string name = John:
voiddisplay):

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

final int id = 20;

final string name = John;

void display%

class DisplayDetails implements Student

void display()

System.out.println("id" +id+"Name" + name);

class Demo

public static void main(String args[ )

);
Displaydetails d = new Displaydetails(
d.display(

PE ALIN-ONE JOURNAL FOR ENGINEERING STUDENTS


RM SIAGROUP
2.10 JAVA PROGRAMMING U-HYDERABA

What is an interface? What are similarities between interfaces


tne and classes?
Q20.
(Model Papor-l, Q4(b)| April/May-18(R16)
Answer
Interface
an Interface.
For answer refer Unit-Il. Q19, 1opie: Delining
Sinilarities between Interface and Cass
cean be inherited. Interface can be inherited by using "implements" keyword and class
be inho.
nheritled
by "extends" keyword.
any delault constructors.
Inerface and class do not have
3 Dvnamic polymorphism
can be possible with both inter faces and classes.

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 :

Generally. object references are of class type. It is also possible


to create object references of interface
is used as ohject reference. This variable
refers to the instance of a class which implements the type. A variable
used to call a method, the exact version to be called depends interface. When this reference is
upon the instance of the interface that is referred.
must be executed is identified dynamically al runtime. This The method that
will delay the creation
on this class is executed first. of classes. The code which calls the methods

The caller does not need to have any


knowledge about call. This process is similar to that of a superclass
subclass object through reference. accessing a

Example

eriace student

void display ):

class Details implements


student

publie void display( )

System.out.println("Hello"):

pubhc class
Demo

pahlic static void


main(String args[ })

student s new Details(


):
s display ):

A ook you buy


for
ho SIA GROUP LOGO on the TITLE COVER before
NIT-2 Packages, Interfaces and Stream Based 1/O (Java.io) 2.11
2 Describe the varlous forms of Implomonting Interfacos.
Q22. Givo oxarnplo s of Java code for o ach case.
Nov ec.16(R13), Q44b)
OR
Give an example whore Intorface can bo usod to support multiplo in! 1oritanco.
TRefer Onty Toplc: Example (Ful mplementatton)
(Nov,/C oc.18(R10), 04(b)| N ov./Doc.17(R16), Q4{b))
Answer :
Interface Implementations
In Java, an interlace can be implemented cither fully or partially.
Full Implementation
the methods of an interface. Thus, full
When an interface is fully implemented, the implementing class defines all
implementation is nothing but the implementation of an interface.
implement that interface. To implement an interface
'implements
Afer defining an interface any number of classes can
defined in an i ntcrface
keyword is used by a class which provides implementation to methods
General Form
access-specifier class classname [extends superclass] [implements interface, [
interface ..
Il body of class
one interface and their names are
public or not uscd. A class can implement n nore than
Here, access spccifier is cither
from an interfac: shi ould be declared
as public so that they can be
methods that are implemented interface definition.
separated with a comma. All the with thiose : methods specified in the
return types should match
accessed by any other class and their names and inheritance.
interfaces. By interfaces Java supipo rs multiple
An interface can extend any number of
public class Demo implements A, B, C implements all these interfaces supporting
and cach extends the other and thc class IDe mo
Where A, B, C are the 3 interfaces
multiple inheritance.
Example
interface Shape

= 3.14;
public final static double pi y)%
computefdouble x,double
public abstract double

class Circle implements Shape

x, double y)
public double compute(double

return(pix*y);

class Testlnterfaces2

J)
public static void main(String argsl

Circle c new Circle();


double value=c.compute(20.5,1
0.0)
System.out.println(value);

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

When ani eriace is partially ieg vieeamei te pmerig


mgimeats
cius áries Ír
cr emmnE mThois
o none of he nehads of .
e
class deciares eit s 2bsuact s L Is caldE

ample
interface Shar e

public stanc doubie pi = 3.14


pubic absna drbie cormpuned dioubie z dutie yt
public abstract voii shout k

abstract ciass Circie impiements Sh *

public doubie compuns doubie a .doužie


}

retupr"i'y

ITbe class does act ipiemm i ct

ciass CircieDispiay eatends Czzie

public void shout )

System.cutprintinthis is the sio pM


)céd ciass of Cie"

class Testimplementation

public static void main Sring ie i D

CircleDispay c = nez Circie Displayt k


doub le vale =ccogue (215, 10
Systen1outprintinívalek
cshow

23. ta emplcyee has name and id number. Write manager


a super classitarfacaciass and labour de
em ployee class.
Man ager datahas member qualificaton
funcion and and manager al*
an rank. Labour classt has mem ber data day wage, overtime and grade
Answer:
inter. ace Employee

Sering came = "

T id 0,
p ablic abstract void getDetaiis( )

clans Mi nagur implements Emplayee

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;

public void getDetails()

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);

public void getPayment() an


System.out.println("Payment Rs." +allowance):

class Labour implements Employee

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

System.out.print' in("\nLabour Particulars:");


System.out.print In("Name:" +myname );
System.out.print In(°ID:"+ myid);
System.out.print in("Daily Wage Rs.:" + daily_wage);
System.out.print t (Grade:" +grade):

public void getPaym er it( )

* overtime);
System.out.prii tl n("Payment Rs." + daily_wage

public class Info

public static void mai n(String args[ ])

*Accountant", 9999.99, "Managerial");


Manager ac countant = new Manager("S N Rao", 3519,
accountant getDetails( ):
accountant -getPayment( );
Labour he lper = new Labour(""Sridhar", 5678, 56.50, 4, 3);
helper.get Details():
helper.ge tPayment( )x

2.2.2 Nested Interfaces, Applylng Interfaces


a24. How interfaces are nested and applied? Exxplain.
Answer :
be aeea
as nested interface. It will
An interface whei emlbedded within any other interface ora class will be declared as.
for grouping the related interfaces so that they can be maintained
inside a class or an inter face. 'These interfaces are used
be accessed.
They require to be reler red to be referenced by the outer class or interface. Without this they cannot
When the neste I interface is declared inside an interface they should be
public. When it is declared inside a class
interface is used outsi f tu
have any modifñer. The outer interface can be either public or default access level. If the nested the na of
qualified with
that is out of the nestii ag inter face or class then its name should be fully qualified. It should be
interface or class that 2mbeds it.
Example
importjava.io.;
import java.u il."
interface Dis play

interf ace Msg

void msg):

lass nes ted interface implements


Display.Msg

Lok for the SlA GROUP LOGO you


on the TITLE COVER betore
iNIT 2 Packages, Interfaces and Stream Based 2.15
/O (java.io)

public void msg()

System.out.println("Hello")

public static void main(String[ Jargs)

Display.Msg dm = new nestedinterfacc( ):


:dm.msg(O:

2.2.3 Variables in Interfaces and Extending Intorfaces

Q25. Explain the scope of variables in interfaces. Modol Paper-l1, Q4(a)

Answer public, static and final by


delault. The pubic
the interfaces are also known as constants. They are for a variable indicates tiat tne
The variables dehined in
variable. The use of static and final
declaration of interface use ol cliss iane
is only one which is allowed in the program. This variable can be accessed by making because, both the
value of he variable cannot be
changed through out the as static and final. This
is

that, the variables need not be explicitly declared


An imporant point to note
here is
keywords are default in declaration of interface variables.
a simple program,
above concept can be illustrated with the help of
The
import java.io.";
interface details

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

int id- 200:

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

public static void main(Stringl


] urgs)

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

ferences befween Interface and Class


Class Interlace
the methods that are
The definition of class include the methods, along The definition of interface include
not contain any
with their code, despite the method is cither abstract abstract in nature. So, the methods docs
class while implemen
or non-absiract. code and it can be written by the
ting the interface.
be constant. he
T
The class members can either be constant or variable.| 2. The interlace members can only
constant values are declared as final.

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

class class_name access_specilier interface interface_name

declaration of variables; variables declaration;

declaration of functions methods declaration;

declaration and definition of functions;

Example
Implementation).
For answer refer Unit-11, Q22, Topic: Example (Partial

2.3 STREAM BASED VO Java.io)

2.3.1 The Stream Classes Eyte Streams and Character Streams


Q28
40. Explain the concept of streams and about stream classes and classification.
OR

Distinguish between Byte Stream Classes and Character Stream Classes.


Refer Only Topics: Byte Streams, Characier Streams)
Answer
Nov/Dec.18(R16), a5(b)
Stream

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.

It is connected to pipedOutputStream. It is used to provide the data pipes


3. PipedlnputStream
that are to be written to the output stream.

It contains and makes use of other input stream as the basic


source of data.
4. FilterlnputStream
It provides additional functionality or transforms the data
in its way.

(a) LineNumberlnputStream It is used to keep track of the current line number.

(b) DatalnputStream used to allow an application to read the Java primltive data types from
It is

underlying input stream.

(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.

(d) PushbacklnputStream It is used to add


functionality such as push back or unread one byte to
some other input stream.
5 SequencelnputStream It is used to represent the logical concatenation
of some other input strean
6. ObjectlnputStream It is used to deserialize the primitive
data and the objects that have been
already written by object output
stream.
7.
StringBufferlnputStream It is used by an
application to create an input
stream which contains the
bytes supplied by string contents.
(i) OutputStream
It is the base class
of all the outpul streams of
java 1/0 API.
OutputStream

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

BufieredReade CharA Rader InpurSreamRras FilterReader PipedReader StringReader

LineNumberReader FiüeReader PushbackRader


Figure: Classification of Reader Class

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

FilterWriter PipedWriter StringWriter


BufferedWriter CharArray OutputStream
Writer 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.

CharArray Writer It is used to implement a character buffer that is used as an writer.

3. OutputStream Writer It is used to encode the characters into bytes usign a charset.

FileWriter It is used for writing character files.


4. FilterWriter It is used for writing filter character streams.6
PipedWriter It is used as a piped character output stream.
String Writer It is a character stream that extracts the output into a string buffer that is used
for building a string.

Methods in Character Streams


The methods of character streams are categorized into
two classes namely reader and writer.
Methods of Reader Class
1. int read()
This method is used to read the characters from
input stream.
2. int read(char| lc)

This method is used to read a set of characters


from the input stream
and store them in char
3. close() array c.

This method is used to close the output


stream and relcase the resources
Methods of Writer Class connected to it.

1. Abstract void ffush()


This method is used to flush the output
stream by pumping
out the buffered
2. void write(int c) bytes that.are to
be written.
This method is used to write the characters
to the output stream.
3. void write(char|| arr)
This method is used to write a complete
char array to the output stream.
4. Abstract void close()
This method is used to close the output
stream and release the
resources connected
Look for the SIA GROUP to it.
LOGO
2
on the TITLE COVER
before you buy
UNIT-2 Packagos, Intorfacos and 2.21
Stroam Bnsod 1/O (java.lo)

2.3.2 Roading Console Input and Wrltng Connole Output


a30. Explain tho procoss of roading consolo Input using byto stronms.
Answer
The objectl which can be uscd to rend console input usingg byte strenma in nystem.in. Ana malter
of luct, an iu
C

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
)

(a) int read() throws 1OException


int read(byte[ ] buffer) throws 10Exception
IOException.
(c) int read(byte[ ] bufler, int offset, int numBytcs) throws

While performing read operation using sysiem.in, if


enter button is pressed, then it generntes an end-of-stream. If an
CxCeption generated, this read( ) method can throw 10Exccption.

Example Program
import java.io.;
class ConsolelnputExample

public statie void main(String[


]
args) throws 10Exception

bytel linfo new byte|50];


System.out.println("Enter a string");
int val System.in.read(info);
System.out.println("The String is");
int x
0; x< val; x
for(x +4)
System.out.print(char) infofx]);

PECTRUM AL-IN-oNE JOURNAL FOR


ENGINEERING STUDENTS

SA sPOL
JAVA PROGRAMMING IJNTU-HYDERA.
BAD)

2.22 writing console output in byte streams.


the concept of
Q31. Describe about However, System.out
console
can also write con. outpu
system.out. prinStream
Answer: written using byte stream, println(O which can be defined in m cla
T
output can be as print() and various thods.
methods
The console two methods such OutputStream class consists Or They ate
output commonly uses OutputStream. The
The console from another class
called as o
class can be derived to wrile dala, this method generates
performcd
further attempts are
as follows,
method closcs the output stream and if
(i) void close(): This bufler.
an 1OException. delete data from the output stream.
fiush or
This method can be used to from bufler to output
(ii) void fush(): method writes an array of bytes
] buffer): This ou
write(bytel stream.
(ii) void method writes one character into output array of numBytes bytes from bufler to output
void write(int b):
This writes an
(iv) offset, int numBytes): This method
] buffer, int
(v) void write(byte[ buffer[ofset). console output. T his method can be define
at to write
stream by starting method
methods, the OutputStream class uses the write()
Among these
are as follows,
in three wvays. They
(a) void write(int x)
] buffer)
(b) void write(byte[
int numBytes)
(c)void write(byte[ ] buffer, int offset,
Example Program
class consoleOutputExample

main(String[ ] args)
public static void

int
x= 'N:
System.out.print("n):
System.out.println(x):

2.3.3 FIle Class

Q32. Explain about file class. Q5ta)


Model Paper-,
Answer :

File Class of fle


The file class interact directly with files and the file
system, unlike other classes that operate on streams. An objc palh.
directory
file such as type of file, permissions, created data, modified data, full
class contains the information about disk
a

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 name:" +f1.getName( ));

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

public static void main(String[


] args)

nt
FilelnputSteam objfis = null;
ifargs.lengh! = 1)

System.out.printin(
The file is ");
retun:

try

File f new File"Cerample'siatxt"):


objtis new FieinpuStream(f:
do

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)

System.out.println"File does not exist');

ow catch(IOException ex)

System.out.printin("/OException raised"):
e,
te finally

try

fin.close(O:

eted.tu
catch(1OException ex)
with

System.out.println("Error while closing file");

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 .

FileOutputStream objfos = null;

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");

catch(I/OException ex) 70T t

ex.printStackTrace(

finally

try

objfos.close( );

catch(1OException ex)

System.out.println("File cannot be closed"); t


ex.printStackTrace( D

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

w: This mode can be used only to urite data into it.


updatod changes of read and unte
rws: This mode can perform both : ad and wTite operations. It also writes all the
operations of both metadata and data synchronously to the device.
alsowrites all the updates of data into the dvir syehooesy
() rwd: This mode can often perform both read and write operations and
Constructors of random AccesFile are as follows,
RandomAcessFile (File fo, String access) throws FileNotFoundException
FileNotFoundException
RandomAccessFile(String fn, String access) throws
Operations
Some of them are as follows
File, various operations can be performed using different methods.
On Random Access
random-access-file.
used to perform close operations on
(a) void close ): This method can be
is used to return the file channel
corresponding to random access file.
method
(b) filechannel getlsChannel( ): This
object on to the random acoess files
): This method is used to returm the file descriptor
(c filedescriptor getFD(
curtent position of file pointer.
This method is used to return the
(d) long getFilePointer):
is used to get the
size of the rahdom access file.
(e) long length( ): This method
access file.
is used to perform read operations on random
int read( ): This method on tnic. During operations an array of bytes with size
method is used 1o periorm read opcraton
int read(bvtel Ib): This file.
length can be rcad from the to read an array of bytes with spocificd length by starting
offset, int leagth): This method can De used
int read(bytel 1. int
t the position offsct.
from random access file.
This method can read the nexi line
trieg readLine( ): ncd can D scu to set the position of file pointer using pos variable
1a
veid scekrloeg pos) Throws IOEiceptoa:
write operations.
td perfoms next read ar of randonm
newlength) throws iOEICEpthon: This method can be used to set the length
vaid stLenyth(long
Tg ew sength variatic
Jb): This method wTites an array ot bytes tnto ile specified length and by starting at file pointer.
veid writelbytel
int lengthj: i hs netod write an array ot bytes with specifiod length by starting at offset
) vokd writedbmel | b, knt offset,
ike the fie
class
) method is conmonly sed in Random Access File
Ameng all daese methods, scck{

iTRUM RLANONE JoaRNAL FOR EHGINEERINO STUDENTS SA GROUP


JAVA PROGRAMMING TJNTU-HYDERAr
ABAD
2.28
2.3.6 Tho Consolo Class
Q36. Discuss about the console class in java.
OR

Discuss about Console class. Nov./Doc.-17(R13),


QA

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

String readlLinet) |lt reads and returns the text from


input stream. Upon lail
null will be returncd at the end of the coisole
ure an 1OError is thrown.
It shows the prompting fornutled string specified
by the lintstring and
String readLine(String.Fmtstring.object args) be returned a
args. It reads from and returns to the console null will
the end of thestring.
format mentionc
Console printf{String fimtstring. object args) Ttwrites the args to the console output by using the
by fmtstring.
the specne
Console format(String fntstring, object...args) Iwriles he formatted args/string to the console by using
format, say fmtstrin
It wriles the bullered output to thhe console.
void flush( ) A null w
ill be
char[ ] readP'assword() I readsa string but does not display on the console.
returned at the end of the string.
iringand
chari iea "asprd sirine fmtstrine. objcct..args)I1 shows the prompting formatted string specilicd by the lnn
I reacs the string that it does not display on the consoC:
will be returnea at the end of thestring.
A sample program lo illustrate the cousole class is as follows,
lconsole class
import java.io.console*:
class consoleEx

public static void main(String args[ })

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,

2.3.7 Sorialization, Enumerations


a37. What is sorialization? Doscribo the intorfacos and classos that support serialization.
Answer:
Serialization
variabie.
state is nothing but the values ofthe instance
Serialization is the process of'storing object's state. Where an object's Serializing an object
The objects may have referenees to some other objects or to
tlhemselves lorming a directed object graph.
the object's stalc.
serializes all the other referenced objects in object grnph
reeursively. Deserialization is the process of retricving
Deserializing an object restores all of these objects and their relerences
correctly.
your program in a lile and thn restore at later lime
il a using
Serialization is important if you want to store the state of class on one
Invocation (RMI). In RMI the object of one
deserialization. Serialization is extensively used in Remote Method
machine invokes the method ofanother class on a dillerent
machine. Tlere two sending machine serializes the object and transmits
in the same stlate as it was existing belore on the original machine.
Thee
L So that it could be reconstructed on a diferent machine
its state.
weiving machine deserializes the object to restore
laterfaces and Classes that Support Serinlization
are described below.
The interlaces and classes that support serializalion
(a) Serializnble Interface
can oniy be storcd and relrieved i.e., a class that implements this
Objects ofa class that implements Serializable inlerlice
a
iterfaceis serializable class. This interfacc docs, not deline any methods,. lt is used to indicate that the objects of this class
re serializable. Subclasses ofa cluss that implements serializable nterlace are aso seralizable. Serialization docs not store the
anables that are declared as transicnt and statie.
b) Externaliznable Interface
Extemalizable interlace gives the programmer control over saving and restoring the state of
an
object. This interface defines
ad methods.

void readExternal(Objectlnput in)


void writcExternal(ObjectOutput out)
Here 'in' endd the object lroni it 'out' is an
an object
is byre suof The object ol byte stieam to write the object
wo methods throws an 1OException. The readExternal()
readexierni) method
menod may also throw
miy also to it.
ClassNotloundEveer
ClassNotFoundException.
DataOutput Interlace
The DataOutput
bytes a interface defines several ncthods to convert datu Irom any of
the Java's primitive
And write these bytes to a binary output streanm. Il also delines the
methods tat convert a lypes to a series of
and write these bytes to a binary oulput strea.. Tne aaOput string into a Java
interlnce defines the followino modified
ur a byte or for a byte array it delines the overloaded meth UT-8
versions of write) method
For unicode strings, writcloolean(O, wrileisyet
it defines ).writclByles( ), writeChar(
dsplay modilied ) write
and writeChars()
AtiteUTF) text for unieode, it defines writelDouble( ), writel
methods. loat().writeln methods.
),. wiitelLong
SPECT
A AL-IN-ONE JouRNAL FOR ENGINEERING
). writeShort(
STuDENTS ) an
JAVA PROGRAMMING (JNTU-HYDERAD
ABAD
2.30
(d) ObjectOutput Interface
This intertace defines following methode
thods to suppon
ObjectOutput interface is derived Irom DataOutput interlace.
The error.
throws an 1OException on any
ohject serialization. These methods
Methods
stream.
void close()-Closes the
- stream.
void flush() Flushes the stream.
Writes
bufM )- the contents byte array buff to the invoking
void write(byte to the invoking stream.
int nBytes) - Writes the portion of byte array buff
void write(byte buf1, int index,

void writc(int b)- Writes a


single byte.
method writes
method used to serialize an object. This
an obie
- This is an important
void writeObject(Object object)
"object" to the invoking stream.
(e) ObjectOutputStream Class
class and ObjectOutput
interface. This class is used fr
class is derived from the OutputStream
The ObjectOutputStream
constructor.
Writing objects to a stream. It has the following
ObjectOutputStream(OutputStream out). e
defines the following methods. All of the methods throws an 1OException on any
This constructor throws an 1OException. It
void close()- Closcs the stream.
void lush()- Flushes the stream.
void write(int b)- Writer a single byte.
void writeBoolean(boolean bool) Writes - a boolean.

void writeChar(int ch) - Writes a single character.

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

void closc()- Closes the stream.


This method rcads and returns the integer representation of the next available byte from input stream.
int read()-
int read(byte buf ) This method reads buf.length bytes from the input stream into byte array bufl ]. On
-
success it r
the number of bytes uctually read.
On
int read(byte buf int index, int nBytes) This method reads nBytes bytes into byte array
}, buff from the input stre
success it returns the number of bytes actually read.
The read( ) method returns
I
if the end of file is reached.
Object readObject()-1his is an important method used to deserialize an object. This method reads an object from the input s

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

rendChar( ) - single churucter.


Reads n
char
fnal Object
readObjectO-Reads un objeet.
an oxampl0.
038. Define onumeration. Also, Oxplaln onumoratod/onum data typo with
Answer
Enumeration corresponds o a ab" "
an ordercd list of named constants, In Java, enumeration also
An cnumeralion is basically
its own constructors, methods
and instance varinbles.
having

Enumerated Data Type values


the user to crealc own
data type and also deline
data type wlhich allows keWord "ernum
Enumerated data type can be delined using
ns a a
can be crealed by
is a user-delincd data type. An cnunernted data lype
tothe variables of this type.dala type is us lollows,
It

The syntax of enumerated

Syntax
enum dalatype_name

valuel, valuc2, .., Valuen


requirement and valucl, valuc2,
of the data type depcnding on user
keyword, dau 1ype_name is the name
as enuneralors or
enumcration constants.
Here, enum is a valuCs arc called
this data 1ypc. These
value n are the possiblc valucs of
Example

public enum montlh


OCTOBER
AUGUST, SEPTEMIBER,
APRIL, MAY, JUNI, JULY,
MARCH,
JANUARY, FEBRUARY,
NOVEMBER, DECEMBER

JANUARY, FEI5KUARY, ...


er tors.
DECEMBER arc called enumerator
cnumerated dnta lype and
Here month is name of primilive lypes, as shown below
varinbles of cnum_ ype Is 5ime us har Oi nC
Jhe procedurc for declaring a
Syotax

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

chun var enum lypc.vnluc,


Liample

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,

public class EnumExample

Month mnth;
public EnumExample(Month mnth)

this.mnth = mnth;

public void Season()

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"):

public static void main(String[ ] args)

EnumExample firstmonth = new EnumExample(Month.January)


firstmonth.Scason( );
A
EnumExample fifthmonth = new EnumExample(Month.May);
fifthmonth.Season( );
EnumExample eighthmonth = new EnumExample(Month.A ugust)
eighthmonth.Season():

2.3.8 Autoboxing, Generics


expressions.
and auto unboxing. Explain how they occur in methods and
a39. Define autoboxing
Model Paper-, Q5(b)
Answer

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

IAutounboxing integer to int


int ip itw;

Instead of.

int ip itw.int Value();//Unboxing integer to int

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

static int meth(Integer m)

return ,
type wrapper reference 'm' is autounboxed to int

public static void main(String args[ ])

Integer itw = meth(300);


System.out.println(itw);

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

public static void


nain(String args[ })

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

public static void main(String args[


])

):
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( )

String st= objl:next( ):


System.out.println(st+"is"+st.length( )+"chars long");

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

System.out.println("The datatype of type


parameter T is" +01-getClass( ).getName( ));
System.out.printin("The datatype of type
parameter X is" +02.getClass.getName( ));

T get01()

return 01; l/return 01

X get02()

return 02; l/return 02

Demonstration of GenericTwo class


class DemoGenericTwo

public static void main(String argsl )

Wcreating a 'GenericTwo' reference for double


lland strings
GenericTwo<Double, String> dsobj
dsobj = new GenericTwo<Double,
String(80.6, "Generies Example")»
dsobj.displayTypes( );
Displaying the types
double i dsobj. get01(O;
storing and displaying the values
System.out.printin("The value is" +1)
String str dsobj.get02():
Sysem.out.println("The value is"+ slr)

ETROM

E J0URMAL FOR ENGINEERING


STUDENMS S GROUP
2.38 JAVA PROGRAMMING UNTU-HYDERA
RABA
Output
The datatype of type paranmeter T is java.lang.Double
The datatype of type paramcter N is java.lang. Suing
The value is 80.o
The value is Gieneries Exannplo
Iuitially. class *Generie Ivo' witlh twe type [xuameters T'and A Is declareu. AS it contans two type nar.
a gencrie
is substituted fr T
two type arguments must Ie passed at the tiune of object crvativn i.c., the first praneter Double'
so unneressan
sccond araneter "Strlng X. Ilowever, sanne type of argunnents can alse be SsCd out doiny Is
or
Q42. Givo tho gonoral torm of a gonorlc class. Also, discuss tho wildcard arguments.
Answcr i

Syntax of a Generic Class


classname_ot class<list_of type paraneters>

//Statements

Syntax for Declarlug n Reference to n Generle Cluss


argument>(list_of_consta
name_ol_classclist_ol_tyy* argument name_of variable new nanne_ol_class<list_ot_type
nrguments)
WildCard Arguments
method that checks the spevi
WildCard argument is a feature ofjava generic using which it is possible to ereate a generic
an unknown type and is denotrd using "
condition irrespective of the type of data every objeet holds. This argument represents
symbol.
Exnmple
The following example demonstrates the usage of WildCard argunments.
class Avg_class< X extends number>

X) nun_arr:
Avg cluss(X[ ]v)

num_arTV

double computeavg)

double sum- 0.0;


i
for (int 0; icnun_urr.length; it+)
sum sum +
num_urrli].doublevalue( ): e
return sum/num_ ur.length;

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)

claso WildArg_ Demo

prublic etatic void mainf String arys )


|

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
+

Float 1{2.05, 3.123, 4.01, 5.723;


Avg classloat-)
Avg class Flost>w2new
double di w2.computeaverage )
(

System.out.println"The average of w2 is" dl):


+

Systcm.out.printin(*"The average of wI and w2");


ifwI.same_Avg(w2))
System.out.println("The averages are samc );
clse
different")
System.out.printin("The averages are
are same
two different data types class
verifies whether the averages ofaverages of two different Av.
same vel)
A
enabling comparison of
program the generic method object, thercby
In the above matches any Avg class
Avg_classc?>
The statenent
objects. a generic mothod. Model Paper-11, O/b)
of creating
Q43. Describe the process
thercby naking the nethod
a
AnsweT: the class,
Method type parameters of In addition to
Creating a Generic class can be use ihe parameter of the respcctive meihod itself
inside a generic one type advanitage of generic
Method that is declared declarcd with at least
can be a non-geneTie
clasy The primary
method detincd within
geneTic method". This
1s
a generic
method which
possible to create satcty.
this, it is also
ensures type
ethod is that, the method
Generic Method method (list_ of parameters)
Synta for Declaring type name of
returI_ the return Iype.
list_of type parameters separaled by comma and are placcd betore
type parameters are
The list of
Gieneric nethod
Etample
demonstrates the creation of
example
The following
class Gen_method
isMember(x a, y[ J b)
y extends
x boolean
static x,

b.length: i t+)
forint i 0;i<
ifla.cquals(b[i}))
return true
return salse;

FOR ENGINEERING STUDTHTS SIA GROUP


ESTRUH ALLAN-OME JOURMAL
public static void main(String args[ ])

"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

= {2, 4,6, 8, 10}:


Intcgernurm_arr| ]
ifisMember(6, num_ar))
System.out.println("6 is member of number array");

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.

if (isMember ("Bob", str_arr))


In this statement, the type of first argument is
"string" due to which the type of"X' becomes
argument is also "string", thereby substituting string. The base type of secou
string as a type for "y". Since there is
and Y are equal), the statement is exccuted no type mismatch (i.e., both the types ol
successfully and the statement"Bob is a
member of str_arr" is printed.
However, if the same statement
was declared in the following manner,
if (isMember("Bob", num_arr))
Tben atype-mismatch error is generated at compile
time becausethetype of "x*" is
Q44. Explain about
goneric different from type oly
interface.
Answer
Creating Generie Interfaces
Generic interfaces are
declared in a way similar
to generic class.
Syntnx for Declaring Generic Interfaces
intcrface name_01 jnlerface
list_of_ype parameters)
In the above syntix,
1 O1 1Ype
parameters is separated
by comma.
.
Syntax for Declaring Type Arguments
vetr a generic interlace is
implemented,
the týpe arguments
class name_of_class <ist_ol lype parameters> need to be specified
in the following man
implements name_ot_inlerlace ust_of_iype
argumcnts>
Look for the SIA GROUP LOGO
LOao
2 on tho TITLE
CoVER bofore
you buy
INIT-2PaGka u oroan Sasod i/O (ava. to)
2.41
E1ample
The following cxamplo demonstrates the Creation
of generie intcrfacen,
interfnce Max_Min X exlends Comparable X

X muximum ():
X minimum ( );

class MaxMinClass <X extcnds Comparable«X>> implements


MaxMinX>

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

12, 18, 24, 30):


Integernum_arr [ ]- f6,
'Y');
Character ch_arr [ 1 {'M', 'S',R',
MaxMinclasw<integerocl = necw MuxMinCInss <integer> (nun_urr):

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( )):

MaxMinClass<character>c2 new MaxMinClass<character-(ch arr);


Sy'stem.out.println("The maximum value in ch _arr:" +tc2.maximum( ));

System.out.println("The minimum valuc in ch_arr:" tc2.minimum( ):

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,

Look for tho SIA


GROUP LOGO on the TITLE
COVER beforo you.buy
IT-2 Packages, Interfaces and Stream
Based l/O (java.io) 2.43
T getobj(
))

return obj;

class Generic <T, V> extends Generic <T

Vobj2;
Gencric 2(T x, V y)

super (x);

obj2 y;

V getobj()

return y

class GCHH

main (String args[ })


public static void

<String, Integer > ("


Result=" 99):
Inteper> 1 -new Genericl
Generic1 <String,
System.out.print(a.getobj( %
System.out.println(a.getobj1( )

Generic. The subclass will pass the type parameter


subclass that extends the superclass
Genericl is the Dut adds ts own
parameters (i.c., ) ifrequired
equ
In the above example, type paraneer
use the
does not
Tto superclass. Genericl
non generic superclass. Consider the
Generic Subclass below
ol any gencnc Or
can be child
A gencric subclass

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

public static void main (string args[ })

Generic <string> g= new Generic <String> ("Hello",


20);
Sysiem.out.print(g-getobi( ) +");
System.out.printin(g. get( ):

In the above program Generic is the inheriting


Subclass oI NonGieneric. Type
is not Generic. arguments are not specified because onGen
To avoid compatibility issues in generic
hierarchy the instance ol operator
whether a particular object is an instance is used. The
purpose of this object is to
ofthe class. t 1S applied to the objects
belongs to particular type or when it can of generic classes.
be cast to particular type. An It returns true
both of them are compatible and contain instance of one generic class
same type arguments. Generic can be cast to ano
overriding to be applied to their methods. class hierarchies concept
even allow the

Look for the SIA GROUP LOGO


2 on the TTLE COVER before you
buy

You might also like