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

Java Unit 1 Spectrum

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

Mervesd by

UNIT OBJECT ORIENTED


THINKING AND
INHERITANCE SIA GROUP

PART-A
SHORT QUESTIONS WITH SOLUTIONS
1. Dofino tho basic charactorlstics of objoct orlented programming.
NovJDec.-18(R16), Q1(b)
nawer
Following are the object-oricnted concepts,
Everything in an object
To perform a computation, objects communicate with cach other and request other objects to
carry out the required actions.
for a
Communication betwecn objects is achicvcd by sending and receiving messages. A message contains the request
particular action to be performed along with the associated arguments that are required to complete the task.
own memories that store other objects.
Fachand every objcct manage their
2. Dofino clans.
Model Paper-il, Q1(a)
Answer
A clas can be defined as a template that proups data and its associated functions. The class contains two parts
namely.

(a) Declaration of data varíables


(b) Declaration of member functions,
the state of the class and the member function explains about the behavioür
The dnta members of a class cxplains about
of the class. There are three typcs of variables available
for a class. They are.

(i) Local variables


(ii) Instance variables

(ii) Clasi variables.


How doos a class nccomplish data hlding?
NovJDec.-16(R13), a1(b)
Answer
ne
A class can be defincd as skeleton lor
an object or blueprint for an object or template for an object. A class defines ait
VATiables end methods, an object should havc. An object is an instance of a class.
is responsible for binding
he
atahidirig is accomiplished witlh he help of encapsulation mechanism. This mechanism extcrnal coue.
maripauluted code and data This binding will keep the code and data safe from arbitrary uccesses to it by the
method is declared as private
Classcs accomplish dataiiding# with the help of public and private access specifien. Ifa access the privnle
methods of the class can
hen, nly Ha class membenn can scces this method. In addition to that only the public contain
program. When a class has an interface which is declared as public it will
hembers of thal class frorn anywitre within the
data thas Cen he known by external userd as well.

SPECTRUM AUAMOnE JOuRMAL FOR ENGINEERIMO STUDENTS


SiA GROUP
ERABAD
1.2
an object and a Q8. Define variable.
4. What is the difference between
Answer
class? Nov/Dec.-16(R13), a1(o)
A variable is the name given to a uni/memory
Answer:
that stores data value of the variable. The name give
vento
Class
Classes are user defined data types and
behaves like the built variable is known as Identifier. t
language. When we define a class, we The variable value may change several times duri.
in types ofa programming
by specifying the data execution ofprogram. Each variable is associated with it
declare its exact form and nature, we do this
it contains and the code that
operates on data. While very simple that depicts thelife time and visibility of thevariables
es.
most real world classes
classes may contain only code or only data, Q9. Define type casting.
interface to its data.
contain both. A class code defines the
Answer :
Object
Type casting' is an explicit conversion ofa value of
Once you define a class it becomes template for
a an
can create any number of type into another type. And simply, the data type is stated
object. By using this template we
are the parenthesis before the value. Type casting in Java must fol
objects, so object is an instance of a class. Objects
the given rules,
basic runtime entities in an object-oriented system, they may
represent a person, a place, a bank account, a table of data that
. Type casting cannot be performed on Boolean variable
(i.e., boolean variables can be cast into other data type
theprogram may handle.
Q5. What is an inner class? 2. Type casting of integer data type into any other dt
Answer: May-19(R16), a1(0) type is possible. But, if the casting into smaller type i
A class which is defined inside amother class is known
performed, it results in loss of data.
as the inner class. Inner class are used inorder to hide itself from 3. Type casting of floating point types into other float typas
other classes of same package. An inner class object can access the or integer type is possible, but with loss of data.
implementation ofthe object from which it is created. Inner classes
Type casting of char type into integer types is possibe
are capable of inheriting the class members of the outer class. It
But, this also results in loss of data, since char hold
manipulates the objects of outer class as ifit is created in the inner
16-bits the casting of it into byte results in loss of dati
class itself. In addition to this it can also implement interfaces. It
or mixup characters.
does not care if the object inheriting is used or implemented by the
outer class. It can also implement from multiple sources. Q10. Define one-dimensional array.
Q6. Define method overriding. Answer: Nov./Dec.-17(R13), 01

OR One-dimensional Array
What is the necessity of overridden methods? Aone-dimensional array is an ordered list of homogen:
Answer: Nov./Dec.-17(R13), Q1(d) data items with one subscript.
Method overiding is a phenomenon in which a method Example
in subclass is similar to the method in
superclass. The return
type and signature of a subclass Subject[S];
method matches with the
Teturn type and signature of superclass Creation of One-dimensional Arrays
method. The advantage
of this method is that, it provides processeu
an implementation which is Creation of an array needs three steps to be
already provided by its superclass.
This method can be used for They are,
runtime polymorphism. When
the method of subclass is called
the superclass's method is not referred (i) Declaration of the array
and it is hidden.
Q7. List the features
of Java. ci) Allocation of memory locations for the array
Answer:
The following are the various
Cii) Initializing the memory location.
features of Java, a11. Define an expression.
Object-oriented
2. Compiled and interpreted Answer
Platform-independent and Expression
4 Distributed
portable
An can be defined as a combination
expression
no
5. Robust and secure operators, variables and constants. These are reier
constituents of an expression.
6. Familiar, simple and small
. Multithreaded and interactive Example
8. Dynamic and extensible
C a+b;
9. a 5;
High performance.
b= a *
c;
1.3
UNIT-1 Object Oriented Thinking and Inheritance
Explain the use of 'for'
statement in Java with
a12. Differentiate between print() and printin() meth- | Q14.
ods is Java. an example.
I April/May-18(R16), a1(b))
Answer (Model Paper-, Qfa)
Answer: Nov./Dec. 17(R16), a1()

The print() statement places the cursor on the same line for Statement
condition and iterator
after printing the output text. Where as the println( ) statement The for loop defines initializer, a specific
Sections. It performs iteration
through a loop and tests
Moreover, a for
places the cursor on the next line after printing the output text. ofa loop.
condition before executing the body it terminates.
Example for print( ) condition is true, else
loop executes only if the
System.out.print("SIA") Syntax
iterator)
System.out.print("Group"); for(initialization; condition;
Output Code statement.
Where,
SIA Group
initial value.
initialization expression specifies the
Example for println()
to be tested at each pass.
System.out.println("SIA") condition specifies the condition
for each execution of
iterator specifies the step taken
System.out.prinln("Group");
loop body
Output Example
SIA The following example
illustrates the use of for loop,
that prints integers from 0 to 49.
Group
Explain with for(int i-0; i<50; i-i+1)
Q13. What are symbolic constants?
examples.
Nov /Dec.17(R16), 01(b) System.out.println("The value of i is :"+ i);
Answer:
Symbolic Constants
In the above code, initially an integer i' is declared
constants which can be and
Symbolic constants are unique the same Then, the for loop checks whether integer "i'
number of places within initialized to *0".
appear very frequently in a is less than 50. If this condition holds true, then the code within
program. the loop gets executed displaying the value 0. Now, the counter
those programs in
very useful in is incremented by one and the process of lteration continues
Symbolic constants are diflerent places.
mean different things
in until i' reaches 50.
which the same value mean the total number of
101 may Q15. Describe finalize() method with example.
For example, the number Number" at another place
"Bus
passengers in the Bus and the clear Answer Nov./Dec.-17(R13), 01(b)
This results in confusion as it is not
program.
ofthe same 101 mean. Then issue is resolved with the help finalize()
what actually a particular constant
whic
constants by giving An object makes.use of many non-Java resources such
of symbolic throughout the program. For
as file handle or window character font, etc. These resources
its meaning
will never change PASSENGERS to represent the number should be freed before an object is destroyed. Finalization is a
example, use the name the
NUMBER to represent mechanism that frees all the resources used by an object. With
passengers in the Bus and BUS beginning the help of finalization, one can define specific action that should
of the constant values at
the
by assigning be taken when an object is about to be destroyed by the garbage
Bus number
collector.
of the program.
There is a finalize( ) method that performs the finalization.
Syntax
a Symbolic constant
is, This method is called by the Java run time whenever it is about
Syntax for declaring to destroy an object of that çlass. Inside the finalize( ) method
final type
Symbolic_name= value; one can include all those functionalists that must be performed
before an object is destroyed. The garbage collector checks
Example dynamically for each object that is not used by any class directly
PASSENGERS
- 101;
or indireetly and just before freeing an asset the Java run time
final int
BUS_NUMBER = 101; calls the finalize( ) method on the object.
final int
ENGINEERING STUDENTS
SPECTRUM ALLAN-ONE JOURNAL FOR SIA GROUP
JAVA PROGRAMMING |J TU-HYDER
I4
Types ot l'olymorphism
General twm
pet d timalioe() There are two types ot
palyinophism, thev
(i) Addoe are,
polymorpismn
oly ot tinalizatiom Pure ulynorphism.
Q18. Writo a short note on
he proteted hey wonl pevents the aceeN lu tinalizet) Java class librarioe
Auswer ries.
by
cde delinedoutnile its lasx. This nethod is only called
ainy
ModelPaper
ust Defiov an atiempt ot parbae collection The mostly used built-in C
methods are printlní
a16. What la tho purposo of lnherltanco? Glva ox- print ) nmethods. They are
containcd in System.out
Ample. Nov./De 10(R13), Qi(0) which is a class of java by ut s) st
delult
OR Java language depends upon
What Is lnherltanco? Glvo oxamplo. libraries that will in tum various built ch
contain built;in methods which insu
Answer (Model Paperll, Q1{b) Nov./Dec.18(R10), /0, string handling, networking
I

Q1(a)) and graplhies. These elasses


Inheritance support GUI. Therelore, Java a
itselt and standard clisses. is considered as a combinatione
Inheritance can be delined N a meelhunism
where in
one class inherits the leatures of another class.
The class which Theseclasses provide thefunctionality
acquires he fcatures'is called the child of Java.
class or derived class Q19. What is abstract
and the class whose fcatures are class? Give example.
acquired is called parent class
or basc clas. The
parent class contas only its own Answer: April/May-18(R16). Q1a
where as the child class contains the features,
teatures of both parent and Abstract Cluss
child classCs. Moreover, an olbject
ereated for parent class can Java delines abstract classes
access only parent class using the keyword
members. llowever, child class object
can accesN members of both child
class and as well as parent
bstract. The class that doesn't, have
class. An abstract class can body is ealled abstrat
class. The child class can acquire the abstraet nnethods. 1 the method
contain subclasses in addition to
properties of parent class
Using the keyword 'extends
does not override the methods containing in the subclasses
Eample of
considered as abstraet classes. the base class then they will e
So, all the subclass
class Single an implementation for all must provide
the base class's
Abstract classes cannot be abstract methods
instantiated.
Exnmple
String str
Singlet) abstract class Baseclass

str"lHello" abstract display( );

class'Derivedclass
extends Baseclass
class subclass extends Single

void display()
subclass()
System.out.printnC°Derivedelass"):
fr str.coneai"World");

017. Dofino polymorphism, cluss Denno


Answer
May-19(R16), a1(a)
Polymorphism public static void main(String
args[
Polymorphism is an impopiant concept in
derived rom the ireck word poly (multiple) and
OOP. U *
morphistn Derived de new Derivedclass):
(fomis) which togciher mean nultiple lorms. It is a ncthod
hrough whicli a operation/function
dedisplay(
can take neveral foms
hased on the type of objecta. An individual operator/lunction
can be uscd in muliple ways.

Look for tho SlA GROUP LOGO on tho TITLE COVER before you buy
PART-B3
ESSAY QUESTIONS WITH SOLUTIONS
1.1 OBJECT ORIENTED THINKING
1.1.1 A Way of Vlewing World Agents and Communlties
o20. Explain the need for object oriented programming paradigm and also write advantages of oOP
OR
What are the unique advantages an object oriented paradigm?
(Refer Only Topic: Advantages of OoP)
Answer Nov./Doc.-16(R13), Q2(a)
Need of OPPP

Traditionally, the struclured programming techniques were used. There were many problems because of the use of structured
programming tcchnique. The structured programming made use ofa top-down approach. To ovcreome the problems faced because
of the use of structured programming, the object oriented programming concept was created. The object oriented programming
makes use of bottom-up approach. It also manages the increasing complexity. The description of an oBject-oriented program can
be given as, a data that controls access to code. The object-oriented programming technique builds a program using the objects
along with a set of well-defined 'interlaces to that object. The object-oriented programming technique is a paradigm, as it deseribes
the way in which clements within a omputer program must be organized. It also describes how those clements should interact
with cach other.

Advantages of OOP
Advantages ofobject-oriented programming over process-oriented programming or procedural programming are as follows,
In object-oriented programming, emphasis is on data rather than procedure.
2. Object-oriented programming allows code reusability.
3. In object-oriented programming, data is secure.
Object-oriented programming allows extensibility of code.
In object-orienled programming, maintenance cost is less,
. Object-oriented programming focuses on the relationship betweer programmer and user.
7.
Object-oriented programming treats data and functions as a single entity.
In object-oriented programming, hierarchical representation of classes is possible.
9. In object-oriented programming, programs are divided into'classes and objects instead of functions or procedures.
10.
Object-oriented programming can be implemented on real-world problems.
11
Object-oriented programming is based on bottom-up approach.
12 m
object-oriented programming, exceptions or errors can be caught at run-time.
13
object-oriented programming, iodularity is achieved.
In
or
ODject-orientcd programming, complex problems can be reduced to smaller manageable problems.
Z1. Write about agents and communities.
Answer
The structure of an object-oriented program is similar to that of a community, that consists of agents interacting with each
dhese agents are also called as objects. An agent or an object plays a role ol providing n serVICe or performiog an action,
OLhCT members of this community can access these services or acti0ns.
Lofisider an example, wherc Rubin and Ruhi are good friends who live in two dillerent cities far from cach other. RubinIf
at what flowers to Ruhi, she can request her local florist, 'Meher' to send lowers to "Ruhi', by giving her all the information
da varicty and quantity of Nowers to send and Ruhi's address as wel.
ic works as an agent (or object) who performs the task of satislying Kubim's request. Meher then perfotms a set
methods to satisfy the request which is actually hidden from Rubin.
of

atorwards
Tanges the flor a message to Ruhi's local Morist, to send the requested flowers to Ruhi. That lorist has a subordinate
who
ET.AeT the lower arrangement is completed, Ruhi's orist asks a delivery person to deliver those flowers to Ruhi.
florst actually obtained those flower from a wholesaler who in turn got it from a grower who manages a team of
ECTRUM gardeners.
ALLIN-O
HL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS
SIA GROUP 2
JAVA PROGRAMMING (JNTU-HYDERA
1.6
The problem of sending fowers to a friend in a different city was solved with the help of many other individe
dividuals,
a
community and, cach of the individuals worked as agents or objects to solve the problem. fin
The community of objects or agents helping Rubin in solving the problem of sending flower to her friendriend Ruhi
P ca
shown in the figure,

Rubin Gardener
Grower
Mcher
(Flower Arranger
Whoksaer
Ruhi's florist

Delivery Person)

Ruhi
Figure: A Community of Agents Helping Rubin

1.1.2 Messages and Methods, Responsibilities, Classes and Instances


Q22. What are messages and methods? Write about information hiding with respect to message passing.
Answer :
When a message is passed to an agent (or object) that is
capable of performing an action, then that action will be initi
in object-oriented programming. The action that is requested is
encoded by the message and it is also associated with additioead
information required to process the request. An object which receives the message
sent is called a 'receiver. When a recene
accepts a message, il means that the receiver bas accepted the responsibility of
processing the requested action. It then perios
a method as a response to the message in order to fulfil the request.
The information hiding with respect to message passing corresponds to
the transparency between the client who sends e
request and the means through which the request is fulfilled. While programming,
using conventional languages, information ha
is regarded as an important feature.
Q23. What is the difference between a message passing and a procedure
call?
Answer :
There are two impoftant differences between a message passing and a procedure call.
defined steps that are initiated when a request is placed, Though, they have a set of w
1. Designated Receiver
A message contains a designated receiver, as the receiver is an object that receives the message
not contain a designated receiver. sent. A procedure call
2. Interpretation
The method selected for execution in response to a message is different for
different receivers. At run time, the rece
for the given message will be known, only then, the method to be invoked is lound
out. This will lead to late binding between
fragment of the code i.e.,.method and the message.
In conventional procedure calls, there is an early binding of name to the
fragment of code, as the binding is carric
during compile time.
a24. Write about the concepts of Responsibility, classes and instances in object-oriented programming
Answer
Responsibility
in object-oriented programming actions are describea in rerms Tesponsibilities. enos
the
oI
desired result. An object can use any technique that helps in obtaining the desired
A request to perform an action
result and this process will not ha
intcrference from other object. The abstraction level will be increased when a problem is evaluated
objects will thus become independent trom each other which will helpP in solving in terms of responsibilrtie
complex problems. obiect coll
of responsibilities reclated with it which is termed as 'protocol' An has a

1ook for ihe SlA GROUP LOGo 2 on the TiTLE COVER before you buy
T.1 Objoct Orlantod Thinking nnd 1.7
Inhorltanco
o
a
Theoperation of Iradiiomal progran depends
on how Method Hnding
on dala stniclures i.c., in chaniging holda witliin
it acts
or a
rrcord. Whereas an cct-oriented program
an aray
operates by whCn more than two
subclasses of a class has a metlhod
sstnuctu is ovcrridden
requcsting data to perlom a service, willh lhe sume name then that method
the reference
Classes and Instances program will find out a class 1o which
He
A receiver's class determines which mcthod
is to hein actually pointing and thuat clas mcthod w
objecti in response to a mewnage,
ohed by the When nimila Lxample
agCs are requcstea then nll ihec olbjects of a class will invoke
method. clans Parent
the same
All the objccts are said to be the instances of a class.
For cxample, il "Tlower is a class then "Rose' is itsN void print(O
instancc.

1.1.3 Class Hlerarchles Inheritanco, System.out.println("Hi ! "):


Mothod Binding
a25. Writo about class hlorarchlos/inhoritanco and
mothod binding.
class Child
Answer Model Papor-1, 02(a)

Class
IHierarchles/Inheritnnce
void print(0
I is possible to organize classes in the form of a structure
that corresponds to hierarchical inheritance. All the child classes
System.out.println("Hello ! ");
can inherit the properties of thcir parent classes.
A patcnt class
is called an abstract class.
that docs not have any dircct instances
It is uscd in the creation of subclasscs.
Exemple
class Bind
'Mehcr' be a florist, but a lorist is a more"specific
Let,
a shopkceper is a human and
form of shopkecper. Additioally,
is an animal
human is delinitely a mammal. But, mammal
a ]
args)
a public static void main(String[
and animal is a material object.
All categories along with their relationships can be
these
figure. ach Child ob = new Child( );
represented using u graphical technique as shown in
category is regarded as class. The
n classes at thic top of the tree ob.print( );
and, the classes at the bottom
are said to be more abstract classes
of the trec are said to be more specific classes.
to which
Inheritance is nothing but a principle, according
knowlcdge of a cutegory or class which is more
general can also The child's object "ob" will point to Child class print()
be applied to a category or class which
is more specific. method and thus, that method will be binded.
Materul
Obpct
1.1.4 Overriding and Exceptions, Summary
of Object-orlented Concepts

Punt
Animal Q26. Write briefly about,

Mammal () Overriding
(il) Exceptións.
Answer
Jlunan Putypas
() Overridingg
For answer refer Unit-1, Q83.
Doclor Shopkreper Poltcan Exceptions
(i)
If the normal flow of the program is disrupted, during
Fhrst
the program execution, an event is occurred which called as
is
Rab
flowers Meber Patd Phyl "Exception".
Casper Sam
gure: Class Hierarchy for Diftarent Kinds of Material Objocis Exceptions are generally used to manage errors.
SPECTR
ALLAN-ONE JOURNAL FOR ENGINEERINO STUDENIS SIA GROUP
JAVA PROGRAMMING IJNTU-HYDERARAN
BADI
1.8
exception object that holds the A diseussion on cach of thenn in detail is give betu
has an object called
It
intoriation includes, the type and state 1. Objeet-orlented
eror information. This crror occurred.
when the
of the program is created
Almost everything in Java is in terms of an
obiees
To throw an exception, an exCeption object Complete program code mal data reside within obieea
systcm.
and is then handed over to the runtime and classes. Java is said to be a true object-orie
tiented
Examples language. It comCs With an extenstVC set of
Insses,
Mcmory cITOT, Stnck overtlow ete. arranged in packages, which we can use in tlhe
progtans
Q27. Explain the fundamental charactoristics of OOPs. by inheritance. In Java, the object model is not only ye
OR simple but also very easy to extend.
What are object-oriented concepts? Compiled nnd Interpreted
Answer Generally a computer langunge will be eitlher compiled
Following are the object-oriented concepts, or interprcted but Java combines botlh tlhese approaches
Everything is an object. In the first stage, Java compiler translates source code
2. To perform a computation, objects communicate with into byte code instruetions. But byte code instructions are
each other and request other objects to carry out the not machine instructions and therefore Java interpreter
required actions. Communication between objccts is generates mmclhine code in the second stage which can
achieved by sending and receiving messages. A mes- be directly execuled by the machine whiclh is ruming the
sage contains the request for a particular action to be
Java program. In this way Java is not only a compilcd but
performed along with the associated argunients that are
required to complete the task. also an interpreted language.
3. Each and every object manage their own memories that 3. Platform-independent and Portable
store other objects. Java supports portability i.c., Java programs can be
4. All the objects are instances of a class. Whereas, a class moved from one system to another, anywhere and
is a collection of similar objects (i.e., integers or lists). anytime easily. Changes and upgrades in processors,
5. A class stores within it, the behavior of an object. Thus, operating systems etc., will not foree any changes in Java
identical actions will be performed by those objects that programs. Java programs can be run on any platform.
are instances of a particular class.
4. Distributed
6. A tree structure with a single root in which the classes are
arranged is called an inheritance hierarchy. The oflsprings Java is a distributed langunge. It not only hus the ability
of a class in the tree structure can automatically inherit to share data but also programs. Java applications can
the memory and behavior of all the instances of a class. open and access remote objects on internet very easily.
This enables many programmers residing at diflerent
1.1.5 Java Buzzwords locations to work on a single project.
Q28. Write down the properties of Java language. 5. Robust nd Secure
OR Java provides many safeguards in order to ensure reliable
Write about any six distinct features in Java code. Java has strict compile time and run time checkimg
programming. for data types and it also incorporates the concept o
Answer exception handling. that captures errors and eliminales
the risk of system crash. Because of this, Java is said to
The people who invented Java wanted to
design a be robust language.
language which can provide solution to the problems
faced in
modern programming. The following are For a language which is used for programming
the various features
of Java, internet, security is a very important one to consider, Juv
. Object-oriented not only verilies the memory access but also ensures tnat
2. Compiled and interpreted no viruses communicate with an applet.

3 Platform-independent and portable Familinr, Simple and Small


4 Distributed Java is n familiar language. lt is modelled ou
C+ langunges. Java uses several
5. Robust and secure costructs ot
C++ and therefore Java code looks
6. Familiar, simple and small like a C** Co
In lact, Java is a sinmplified version of C++. Java 1s
7 Multithreaded and interactive only small but also a simple language. Many leat
8. Dynamic and extensible of C and C++ are not included in Java because they
9 High performance. redundant. Java does not use pointer, goto stale
operator overloading, multiple inheritance etc.
Look for the SIA GROUP LOGO on the TITLE COVER before you buy
.9
UNIT-1Object Oriented Thinking and Inheritance
in a class arc called as
7. Multithreaded and Interactive The data and functions available
members ofa class. The data defined in the elass are called as
Java supports mulitlhreading i.e., il is not necessury for Sunctions delincd
member variables or data members and the
an application to finish one task before starting another.
are called as member functions.
In this way we can handle several usks simultaneously.
is to
The Java runtime comes with tools which support The main idea behind the concept of encapsulation
code.
multiprocessor synchronization and construet interactive obtain high maintenance and to handle the application's
systems running smoothly. by providing
Java support encapsulation mechanism
permission
8. Dynamic and Extensible access specilier that delines the scope nd the access
of a class member or method. The access
specilicrs includes:
Java is a dynamic language, which is capable of or method
public, private and protected. A class data member
dynamically linking in new class libraries, methods be iaccessed within its own
and objects. lt can also find the type of class if declared ns private then they can
protected then they can
class only. But if they are declared as
througha query. thus making it possible to
either
be accessed within its own class, sub-classes and
in all the other
dynamically link or abort the program. Java also
classes residing in the same package. However privale data
a
Supports extensibility. Iu support functions writlen
member of a cluss can be nnade to accessible Irom any
other
in other languages like C and C++. This makes the
class by declaring it as 'public'. The public access specilier
programmers to use ihe ellicient functions available
in these languages. These functions are called native makes the data member to be available out-side the class.
methods which can be linked dynamically at runtime. Inheritance
9. High Performanee Inheritance can be defined as a mechanism of acquiring
Because of using intermediate byte code, Java features from one class called parent class to another class
performance is excellent for an interpreted language. called child class. Parent class is also known as basa class or
In order to reduce overhead during runtime, Java super class and child class is known as derived class or sub
architecture is designed carefully. Multithreading class. The parent class contains only its own features whereas
improved the overall execution speedof Java programs. the child class contains the features of both parent as well as the
child classes. Moreover, an object crented for parent class can
1.1.6 An Overview of Java access only parent class members. Ilowever, child class object
can access members of both clhild class as well as parent class.
Q29. Explain the basic concepts of object oriented The child class can acquire the properties of parent class using
programming. the keyword 'extends'.
Answer: Polymorphism
Object oriented programming is a tecchnique that builds Polymorplhism is one of the OOPs concept. lt can be
the program using the objects along with a set of well defined used td design andimplement systems that can be extensible
It describes the way in, wlhich elements
interfaces to that object. more easily. 'poly' means many and 'morplh' mean
and how forms i.c.,
Within a computer program must be organized is tne ability to take more than one fars
these elements can interact with each other. Object oriented Psm
are two types of polymorphism supported by Java.
and also manages the They are
programming uses bottom-up approach static polymorphism ancd dynarmic polymorphism.
increasing complexily.
Q30. What is meant by byte
Data Abstraction
code? Briefly explain
how Java is platform independent.
Abstraction is one of the important element of OOPS
a that hides theAnswer
lor managing complexities. Il is mechanism Nov./Doc.-17(R16), Q2(a)
implemcntation dctails and shows only the lunctionality. For Byte Code
Cxamplc, while performing transaction on ATM, the end user A Bytecode is an
just type the password and accepts the services provided to him.
intermedinte representation of java
processing. Thus, an source code. It is also called as
compiled fornmat of java souree
But the user is unaware of the internal
on the object does code. It eonsist of optimized set
abstraction is one that mainly focuses what ofinstnictions which are usually
executed by Java rnun time system on a
but not how il docs. special nmachine called
Java Virtual Machine (JVM). AJVM is
a bytecode
Encapsulatlon It perforns line by line
execution of bytecode. interprcter.
Encapsulation is a mechanism of binding data members A Bytecode can be
and corresponding methods into a single module called class
transterred across any
then can be executed by Java Virtual network and
inorder to protect them from being accessed by the outside code. Machine (UVM). They
An instance of a class can be called as an object and it is uscd
ctny ave cluss extension.
to access the members of a class. In encapsulation, objects are A bytecode usunlly
comprises of one or two
trcated as "block boxes' since cach object perlorms specific tusk. represent the instructions. bytes that
SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS
SIA GROUP
L10 JAVA PROGRAMMING JNTU-HYDERAR
Iaa s Piatform Idependent ABAD)

va is piattorm independent, meaning that a Java program can run on any


The busic sset for Java to be plattorin independent is byte code. opcrating system and on any machine
Basically archi
presety using, it runs on a machine called Java a Java progranm does not run on
virtual Machine (JVM). This the compuler
we arr usng by means of a program. JVM is emulated i.e., embedded
inside the co
compuia
The following figure shows how byte
code makes Java platform independent.

Source Java Java


code Compier Bytecode

Current System
--

Java Vrtual Machme


Java nterpreter
**

Computer Operatng System


Figure
Generally any language compiler
translates source code of a program directly
language programs can run only on to machine code, this is
the reason why other
specified operating systems. Consider
intermedare code called byte code. A the figure, the Java source
code is translated into an
we re rning
vtual machine called Java virtual machine
by means of a program. is already embedded in
The JVM consists of an interpreter the computer system
curput of Java cormpiler is deciphered called Java Interpreter. The byte
by the Java interpreter and finally code, which is the
byte code instead of machine program is executed. As the
code it is not effected by differences in Java program we run is in
interpreted Java code runs slowly when the hardware architecture of
compared to an equivalent native different computer systems. An
machine instructions.
Java does not support pointers
because, pointers are unsafe. They
eaecurion enviroament. Moreover, corrupt the firewall between
when the Java programmers are the host computer and Java
pointers and will never get benefited confined to the execution
environment, they will never require
ypes the firewall cannot be corrupted, using them. Java supports reference types instead of pointers.
in
since the references cannot be
manipulated as that of pointers. Because, with referenee
Q31. Write the
significance of Java Virtual Machine.
Answer
Java Virtual Machine Nov/Dec.18(R16), a2
Java Virtual Machine
(JVM)
platform for all Java programs run: is the most important part of Java technology.
to JM and Java APl is also known The JVM and Java API together,
Basically, JVM acts like as Java runtime system.
tot
veriffes thc byte code, an interpreter for Java byte code,
which is an intermediate
The figure shows the interprets and executes it. Additionally, it provide functions code. The JVM loads the Java c ses,
internal architecture of like security
JVM. management and garbage colc
Chss
fies-Cass loader Java AlPI

Byte codec verifier

Runtime data areas

Execution Native
cngme ethod |-Undetly mg
nterface
Figure: Architecturo of JVM

Look for the SlA GROUP LOGO on the TITLE COVER


bofore you buy
IAIT1 Object Oriented Thinking and Inheritanco 1.11
. Class Londer Q32. Doscrlbo tho structuro of a typlcal Java progra
Nov/Doc.-18(R16), 02(a)
It is amechanism that pertorm loading of classes and with an oxamplo.
interfaces into JVM. When a pogrm attempts to invoke OR
a method of certain elass, then JVM checks whether that
class is already loaded, if not, the JVM uses class loader Explaln difforont parts of a Java program with
to load the binary representation of that class.
an approprlato oxamplo.
Nov./Doc.-17(R16), Q3(»)
Byte Code Verifier Auswer
2.

After loading the class, the byte code veritier, checks Java Program
one
whether the loaded representation is well-formed. program consists of one or more classes. Only
A Java
A class consists of
whether it follows the semantic requirennents of Java of these classes delfines the main( method.
)
class. The general
programming language and JVM. Also checks whether data and methods that operate on the data ofa
the code contains proper symbol table. If a problem syntax of a Java progrum is shown below.
occurs during verification then an error is thrown. Documentation
3. Runtime Data Arens
These are special memory areas which JVM maintains Package Statement
to temporarily store byte codes and other information
ike loaded class files, objects, parameters to methods,
return values, local variables and results ete. Import Statements
4. Execution Engine
It is a mechanism which is responsible for exccuting
Interface Statements
instructions contained in the methods of loaded classes.
5. Native Method Interface
method or Class Definitions
If any Java program calls a non-Java API
platform-specific native method then, the code of these
through
native methods is obtained from underlying OS Main Method class definition
the use of native method interface.
Example
The given fraction of progràm contains
several errors, main() method definition
thecorected program,
Line 1: int[la = 10, 20, 30, 40, S0; Figure: Goneral Syntax of a Java Program
Line2: int i = 4; Parts of Java Program
Line 3 System.out.println(a[i] =i=2); The diflerent parts ofjava program are given as follows,
In line 1, the array 'a' is initialized
to five integer values
I. Documentation
10, 20, 30, 40 and 50.
This section consists of a set of comments about the
1.C.,
program including the name of the program. This section
4 i.e.,
In line 2, variable is initialized to
i
is suggestcd as it helps in understanding the program.

a[0 a[1] a[2] al3] a[4] 2. Package Statement


10 20 30 40 s0 This is the first statement in every Java program, if
needed. This statements tells the compiler that the classes
is executed.
In line 3, at first, the chain of assignnents defined here belongs to this package. This statement is
, value of i - 2 is 2, which is then assigned
to ali] i.e.,
optional.
-2 Buti2. Thus, the value of al2]=2 is 2.
Example: package myPack;
L.e., ali]=i-2
3. Import Statement
afi-2
The import statement tells the interpreter to include
a[2]-2 the classes from the package defined. This is the next
progrum 1S 2
Dus, the output of the given fraction of statement afler the package decclaration but should be
d the updated array
'a' is, writtcn before defining a class. There may be a number
alO] af [2] a[3] al4) of import statements. This statement is optional.
10 20 » 40 s0 Example: import java.io.*;
JAVA PROGRAMMING IJNTU-HYDERA
DERABAD
1.12
Interface Statements Q33. Discuss about using blocks of code.
The interface statement defines method declaration Answer:
without body for the subelasses to provide implementation In Java, two or more statcments can
be groune
for them. This is optional, it is used only if we want to blocks of code. It is also called as code blocks. Statecm
implement'mulüple inheritance feature in our programs. ements
be grouped by using opening and closing curly braces. At
Class Definition code blocks are created, they can be used anywhere ltertbe
5 logical)
as single statement. Consider the below.code,
This section consists of a number of class definitions
ifa-b)
where each class consists of data members and methods.
The number of classes required are based on the
complexity of the problem. a b
6. Main Method Class b 0;

This is an cessential section of a Java program. Every Java


program must have a class definition that defines the In the above code, all the stalements in il block becom
main ) method. This is essential because main() is the the logical unit. All those statements are interrelated.
starting point for running Java stand-alone programs. The
Example
main ) method instantiates the objects of various classes
and establishes the communication between them. The class Block
program teminates on reaching the end of the main()
method.
public static void main(String args[ ]}D

Example
I A first Java program int i, a,
/File name : Simple.java a-10
class Simple for(i-0; i<5; it+)

System.oul.println("i value:"+i).
public static void main(String args[ })
System.out.printin("a value:"+a),
aa 2;
System.out.println("A simple Java program");

The above is a simple Java program. In the above program, for loop contains the block of cod"
These statements get executed for every iteration of loop.
s
Now, let sce the process of compiling and running this purpose of it is to ereate inseparable units of code logically,
program. In order to compile this program, we should even has additional properties and uses.
execute
the compiler javac, specifying the name of the
source file on Q34. List and explain the lexical issues of java.
the command line as shown below.
Answer:
c:javac Simple.java
The lexical issues of java are defined as follows,
The javac compiler creates a file known
as Simple. 1. Whitespace
class which contains the bytecode version ules
of the program. The
output of javac is not the code which Java does not require any special indentation
can be executed directly. Spa
Therefore, to actually run the program, because it is a free form language. Whitespace is
we should use the Java
interpreter, called Java. We should tab are new line in Java. For example, a progral
pass the class name Simple
as command-line argument writlen in one line completely until there is a whie
c: Java Simple
as shown below.
ee character among the tokens.
Identifiers
After running the above program
we get the following Identifiers are the names assigned to classes,
output,
and methods. The names can contain uppercar
Output lower case letters, numbers and underscore or ue
Buf they must not begin with number.
A simple Java program.
Examples: Count, test, x2
Look for the SlA GROUP LoGO on the TITLE COVER before you buy
UNIT-1 Object Oriented Thinking and Inheritance 1.13
. Literals primitive data typcs which
Java supporis cight types of
A literal means the representation of constant value in are grouped into four types as shown below,
Java. (i) Integer data type
Example: 50, 32.8, A', "SIAGROUP Publications". (i) Floating-point data type 2
4. Comments (ii) Character data type und
Comments in Java are of three types. They are single- (iv) Boolean data type.
line, multiline and documentation comment. The third () Integer Data Type
type of comment is used to generate HTML file which The integer lype can represet the signed integer valucs
contain documents ol your program. It starts with/ and not allow unsigned
That may be positive or negative. Java does
ends with required. This data type itsclr
integer values since, they arc not
ns lollows,
5. Separators consists of four diflerent types. They urc
The separators are the characters that are used for (a) bytec
separating. Mostly used separator is :(semicolon) in Java. (b) short
Other separators include ( (parenthesis), { }(braces), [
(c) int
J(brackets), (comma), (period) and: :(colons).
(d) long.
6. Java Keywords
(a) byte
Keywords are reserved words that have special meaning. integer values that
The byte data type is used to maintain
They defines specific functionality of the language. They have a size of byte i.c., 8 bits. The range of
I byte data
are written in lower case letters and cannot be used as
ype -128 to 127.
is from
variable name, class name and method name. Java has
S0 keywords. Some of them are listed below, Syntax: byte variablc_name;

Abstract . Assert Example

3. Boolean 4. Byte byte x3;, iront uh f pa 9


(b) short
5. Break 6. Case
The short data type represents the signed integer values
7. Catch 8. Char and the size of this data type is 2 bytes i.c., 16 bits. The
range of this data type is from -32, 768 to 32, 767.
.
9. Class
Continue
10.
12.
14.
Const
Default
Double
Syntax: short variable_name;
Example
13. Do t1L 1
15. Enum 16. Extends short a, b;
17. Final 18. Finally a - 2376;

19. Float 20. For (c) int


21. 22. If The int data type is most preferable among all the integer
Goto
data types. Since, it can control index of arrays and loops.
23. Implements 24. Instance of
The size of this data type is 4 bytes i.e., 32 bits and the
25. Interface range is from-2,147,483,648 to 2,147,483,647.
separators,
keywords of java are combined with
The Syntax: int variable_ namc;
*Ttors and form the foundation of Java. They must used
be
as Example
ucntufiers. In addition to this, they should not be used
nes for variables, methods or clsses. int a, b;
a 2376789;
7Data Types, Variablos and Arrays (d) long
035.
Ist the primitive data types available in Java The long data type is a signed 8 byte (64 bit) which lans
a
and explalin. range from-9,223,372,036,854,775.808 to 9,223,372,
Answer 036,854,775,807. Generally, this data type is
AprlUMay-18(R16), 03(a) used to
manage the integer values that have a range
than int.
greater
Data strongly
it is a
ed Ypes are mainly used in Java since, type of Syntnx: long variable_name;
ge. In java, compiler cvaluates all the
ble type
its, valucs and cxptessions in order to
patibility.
imaintain Example
and reliabillty is
Meanwhile, crrors are reduced long x, y;
data type is one of the simplest data type
imitive
sist of a single value. x-12345678910L;
PECTRUM
STUDENTS
HN-ONE JoURMAL FOR ENGINEERING
ALLAN
SIA GROUP
JAVA PROGRAMMING [JNTU-HYDERA
YDERABC
1.14
Program
class IntegcrËxample

publicstatic void main(String[] args)

byte
short y:
int 2

long p

2
y- 23456;
2 117438;
p 732227363054L;
System.out.printin("The
value of byte data
System.out.println("The type is:" + x);
value of short data
System.out.println("The type is:" + y)%
value of int data type
System.outL.println("The is:" + z);
value of long data
type is:" + p)

Floating-point
Data Type
Floating-point
pes are as follows, type can be defined as a data
type which indicates
the fractional values.
(a) float and The two types of floating-point
daa
(6double.
a) foat
The float data
type
maximum value is used to represent single-precision
of float literal is approximately numbers and the
Syntax 3.4 x 10 size of this data type
is 4 bytes i.e.,
float variable_name: 52 DIs.
Example
float x
3.14F;
) double
Double data
type
is used to represent
agest value of double double-precision
functions literal is approximately numbers and the
in Java class 1.8 x 308. size of this data type
library uses is o The
data type is frequently used oy
Syntax The double bits.
double values.
double variable_name; in Javu sethe math
Example
double x,
Program
class FloatExample

public static
and main(String
[ ] args)
float x
double y:
x 3.14F:
UNIT-1 Otject Oriented Thinking
and Inheritance 1.15
y Mathaqrt{x),
Systerm.cna.prirtr("The fat valuc x
of is"+ x),
Siyer.n.rirtr "Thedatie vale of y i"+y%

() Character DataType
The character (ie., char) data type represents characters and the sie of this data type is 16-bits (2 bytes), nva
s 2 brytes jnce t tupports unicode characters. Unicode characters can be defined as a set of characters tha ndicaeharcier naa
characters uf hurman languages. The character data type stores unsigned 16-bit characters with a range of O to 63,)506, 1he
value must be ercloned in single quotes.
Sytar
char variahle_name,
Eumple
chat x

Programn
claas characterExample

public static void mainStringl ] args)

char y
y- "N°;
System.out.pritln("The value of y is:"+ y)
y- iThe char value is decremented
System.out.println("The new value of y is:"+ Y);

y 82; The char data type can be assigned with integer


System.out.println("The another value of y is:"+ y);

Gv) Boolean Data Type


an cxpression is either true or false. Therefore, a variable or expression
The boolean data typc indicates whether the valuc of
whrich is declared as boolcan type can use these two
keywords.

Syntax
boolean variable_name;
Example
boolean a;
a true,
of
a false
Progam
clase BooleanExample

public static void main(String[ args)

boolean n,
int x, y, 7
10
y2 20,

RUM ALLAN-ONE JOURMAL FOR


EMGIMEERINQ STUDENTS
SIA GROUP
JAVA PROGRAMMING JNTU-HYDERA
DERABAD)
1.16
2. Floatlng-polut Llteral
a false 1he number that contains a decimal value folo
a traction component is called tloating-point literal.
ifa) cane
eapiessed in two notations,
System.out.printlna is:" a) + () Standard notation
System.outprinthn("x is not grater thany ")% (ii) Scientific notation.
( Standard Notntion
2yN Standard notation represents the floating-point|literal
the form of whole number cormponent and'a fractiona
a
a tnie al
component seyarated by a decimal point.
ifa)
Example
System.out.println("a is "+a): 3264 73245
System.out.printla("y is greater than »")x

Whok numler Decimal Fractimal


connent nt conponeint
(11) Sclentific Notntion
The above program can print the boolean values true/
false on to the standand output device using println( ). Next, Scicntific notation consists of a standard floating- point
the control statement "if can be managcd by using the boolean number followed by a suftik. Suflix specifies a power
variable 'a' directly. However, there is no nccd to use the of 10' by which a number should be multiplied.
statement, which is shown below, The exponent is denoted cither by "E' or e' followod by
ifla tnue) a negative or positive decimal number.
Example
/Statements 7.324E32
Se+1000
Q36. Discuss about literals in
Java.
Answer In Java the default float literal is double. A double literal
can also be explicitly specified by appending a D or d to te
In Java, the different types
of literals are, constant.
Integer literal
3. Boolean Literal
2 Floating-point literal
a 3.Boolean literal i oit
Boolean literals can only take two logical values "
and 'Talse'. Both of them cannot be converted to numen
4. Character literal representation.
6.
1.
String literal.
Integer Literal
In Java, boolean values (i.c., true and false) ean
be assigned to boolean variables and they can be us
o
An integer literal is expressions involving the boolean operators.
a whole number value. That can
any decimal, octal be
and hexadecimal value. Decimal 4.
have base 10 and they numbers Character Literals
do not have a leading zero.
1, 54, 196
are said to For exaniple, In Java, character literals are indices into the Un
be the decimal numbers.
Octal values have character set. These literals are represented within single
They are denoted
base 8 and they range from 0
to 7. They are 16-bit values which can easily be etato
net
by a leading zero. Example
octal values. It is important 00,06 and 07 are cod
to note that 09 is not into integers and can be manipulated using integer o*
Hexadecimal values an octal valye.
have the base 16 and such as addition, subtraction etc.
lo I5. The hexadecimal they range lrom 0 ract
alphabets A to F numbers 10 to 15 are They use the '' (Slash) for entering the ASCIl ea
respectively. represented by aracter
They are denoted by which eannot be entered directly such as new line char
a leading zero-x, and tab character '\t".
An integer literal (0x or 0X).
to a byte, short, creatcs an int value
long or char. that can be assigned They allow us to cnter the value of charactc a in
octal and hexadecinmal notation.
A long literal
is denoted by
the literal. For appending n I or L to Example
cxample, Ox7Mm
$4775807L is said ML or 9223720368-
to be the largest long
literal. For 'a, an octal notation is '\141' and hes
notation is "\u0061
IT-1 Object Oriented Thinking and Inheritance 1.17
Strlng Literals
Dynamic Initialization of n Variable
String literal consiSts ot a sequcnce of characters
Dynamic initialization of a variable can be defined as
cnclosed within double quotes,
proces of initializing the variable at run-time i.e., during
Forexample, "Giood Day, is a string literal. String literalexecution of the program. This can be perlormed by nssigl5
on aa:single ine becausc no line-continuation
must e wilten
tten
cscape scquence Is
provided by Java. The working of octal
a valid expression to required variable.
escupe sequences in string Program
ion, hexndecimal notatiorn and
literals.
literalis sanie as that o! character class VariablelExample
Q37. What is a variabl and explain the declaration
and Initialization of variable? public static void main(Stringl args)
Answcr:
Variable
A variable is the nanie given toa uni/memory location int x= 10, y = 20;
stores data value ol the variable. The naime given to the int z
that
variable is known as ldentifier.
The variable value may change several times during the
zSystem.out.println("Addition ofx,
=
Nty:
y = "+ z);
eecution ofl program. IEach variable is associated with its scope
that depicts the lite time and visibility bf' the variables. z=x-y:
Declaration of a Variable Systeni.ot.println("Difference between
variable can be declared inorder to avoid the confusion
A X, y ="+ z);
to the compiler. The declaration ofa variable is preceded by its
data type so that it can accept data values of its associated type.

Syntax
datatype variable_name; In the above program, two variables x, y are declared
variable
type of variable such as int, double,
Here datatype is the and initialized with 10 and 20 respectively. Another
dynamically. After the
char and variable_name indicates the name of the variable. is declared and can be initialized
computation of addition operation, z is initialized with 30 and
Example that the
after subtraction, : is initialized with -10. This depicts
int x, a may vary during exccution of the program.
value of variable
double y:
Q38. Explain the scope and lifetime of a variable with
When a variable is declared, an instance is created for example.
Ts data type which identifies the capability of variable. This
is
Model Paper-, Q2(b)
Decauseof means that when a varinble is declared as int then itAnswer
cnnot store the values of boolcan data type. This, strong type Scope of a Variable
checking is supported
by Java. The scopc of a variable can be delined as a process
Taitialization
of a Variable of localizing the variable and preventing it from undesired
initialization of a variable can be defined as a process modifications. The scope of' a variable is limited to the block
be done directly
gning value to the variable.
a This can
of
of code. A block of code can be defined as a set of statements
declaration enclosed within opening and closing curly braces ({...}). The
tne declaration of a variable or after the
able. The syntax for initializing a variable is as lollows variables that are declared inside a block are not visible fronm
Synta
outside of the block. This means, the scope of these variables
is only within the block. The scope of variable begins with
a
uatype variable_name = value;
datatype variable_namne; opening braces of method and
a il the method itself contain
parameters, their scope is uscd only within the method. Scope
Variable_name= value;
nested. Tl a variable is declared insidea
Liample
of a variable can beis delined in another block. Then the scope
block which itself
intx10; to the inner block. However, inner
of outer variable visible
is
loat y 1.5F;
block variable can be invisible to outer block.
char ch,
A variable can be declared at any point and they are
ch-"N
valid only aller the declaration. Therefore, a variable which
ple variables that are declared with similar ype in the beginning of method can be accessible
can be declared
a /ed
opctalo.
Aample
simultaneously. This can be done by using throughout the block.
at the end of block
is
Whereas, a variable wvhich can be declared
not used since the block of code cannot
access it. A varinble Is destroyed when scope of the variable is
tntx,y, z 8, pm 9, compleled.
IRUM
ALIN-ONE JouRNAL FOR ENGINEERING STUDENTS SIA GROUP
ram
class ScopeExample

public static void main(String[


] args)

int a;
a - 20;

ifa==20)
int c= 30;
System.out.println("The values of a and c are:" +a+""+c);
a=cta,

c 80;//Here, an error(c not declared) is raised, since the scope of c is completed.


System.out.println("a =8" +a);

The variable 'a' can be uscd in main() method and as well as in if block, since it is declared in outside the block. Howeve
e value of 'c' can be accessed only within if block since, it is declared in inner scope.

ifetime of a Variable
The lifetime of a variable can be defined as the time period in which the variable is present in computer memory. Te
ariables can be accessed during the execution of program and restricted to its scope. When a variable is declared in a block, t
ifetime will be started and completed at the end of the block.

lfavariable is declared and initialized with a value, then the value is re initialized every time when the declaration stiteme
is executed.
Program
class LifetimeExample

public static void main(String[ ] args)

t a,
a= 0;
while (a< 5)

int b 2;
System.out.println("The
value of b is" + b);
b 10
System.out.println("The
value ofb is" + b);

Inthe above program, the variable b is initialized with a valuc


e-inilializcd 2 and re-initialized with 10. If the loop i1Srepeated, th
with 2 and prints Tep nil
pccuied condition is not satisficd the valuc 2. Again, the variable b initialized
(i.e., a<S) and print the with 10. This process is rp
values 2 and 10 alternatively.
Look for the SIA GROUP LOGO I2 on the TITLE CoVER before you buy
UNIT-1 Object Oriented Thinking and Inheritance 1.19
039. Describe about type conversion. nversion betwe
Also explain how casting is used to perform type conve
incompatible types.
Answer
Type Conversion
"Type conversion retiers to conversion of data from one form to other. It is one of the most important aspects ot C
programming. Since programmers are prone to commit erors, care should be taken (while writing programs) that the
writen, obeys the principles of type conversion. For example, consider that there are two integer variables namely a s
co
3.
nen
In general terms one would expect that the solution obtained by performing 'bla' would yield 1.5. But, this is not the case.
the same logic is applicd in the
programs. This is because, as both the variables a and b are declared integers, hence compuc
considers the result of "bla' as integer, eventually discarding the decimal value. Hence. proper type conversion is necessy
ensure accurate results. Consider an example for type conversion which can be shown as follows,
int x;
float y:
x = 5;
y x; IHere, an integer value 5 is assigning to float
Ifcompatible types are assigned to variables, the right hand side expressio is assigned directly to left hand side expression.
However, it is not possible to convert all types since java support strict type checking. Similarly, all implicit type conversions
are
not supported. An automatic type conversion can be done only if the following conditions are satistied,
The data type of the variable and data must be compatible.
The data type of destination (left hand side) must be large in size compared to the source (right hand side) type.
The int type can hold byte, short values since it is higher than these types. Whereas, long value
cannot be assigned to int
The integer types and floating point types are compatible with each other. However, these numeric types cannot be compaible with
boolean or char. Similarly, char and boolean are also not compatible. As a matter of fact. it is possible to assign integer constant
to char type.

Example
Consider an example program of converting long to double which can be performed automatically.
class TypeCastExample

public static void main(String[ ] args)

float :
double d:
I- 1234567L;
d
System.out.println("The value of long type is"+I+ "and the value of double type is" + d):

Here, the long type can be converted automatically to double. However, double cannot be converted into long type since
this conversion is
not compatible.
Type
Cating
Tpe casting' is an explicit conversion of a value of one type into another type. And simply, the data type is stated using
rthesis before the value. Type casting in Java must follow the given rules,
1
Ype casting cannot be performed on Boolean variables. (1.e., boolean variables can be cast into other data type).
pe casting of integer data type into any other data type is possible. But, if the casting into smaller type is perfomed
results in loss of data. it

ype casting of floating point types into other float types or integer type is possible, but with loss of data.
ype casting of char type into integer types is possible. But, this also resuls in loss ol data, since char holds 16-bits
ng of 1 into byte results in loss of data or mixup characters. the
TROM ALLAM-ONE
URMAL FOR ENGIMEERINO STUDENTS
SIA GROUP
1.20 JAVA PROGRAMMING IJNTU-HYDER
AYDERABAD

The general fom o type cnsting is as lollows, 4 n8.0;

ntax n

9.0;
(targct-type) cxpression; x(int) (a +
b):
Here, taret-type the specitication to convert tlhe
is
System.oul.printin(The integer
cxpression into roquined type. value of
Example
(a+ b)is"
x 80;
foat a, b;

int e (int) (a +b); p(byte) x; I/Byte can store 80,


I/So no data loss.
The result of float type variables can be converted in to
System.out.println("The byte
integer type explicitly. The parentheses for the expression a + value is" p
bis novesSary. Othernvise, the variable ean be converted into
int but not the result ofa+ b. The casting of double to int is
p-97; I/ is the ASCII code
ofa
nevessary since, they are not compatible. C (char) b;
Furthermore, Java performs nssignment of value of System.out.println("The char value is:"+ ct
one type to a variable of another type without performing type
casting. Here the conversion is performed automatically which The ASCIl code of 97 is 'a'. It can be
is referred to as automatic type conversion. It can take place /ussigned to c.
when destination type hold sufficient preccdence to store source
value.
Example
Q40. Explain how type conversions takes place in
byte b 50:
statement
nt ab hvalid expressions.

The assignment of smaller data type to larger data type is Answer:


referred to as widening or promotion and the assignment The type
larger conversion takes place in expressions, if the
tpe value to smaller is refered to as
narowing (it results in valuc of an intermediate result excecds the range of one or lhe
data loss) olher operand. This type promotion is implicitly. Consider tie
While performing the conversion between following cxample.
two
incompatible type, the use of word cast is necessary. It
is an int result =x *y/z;
explicit type conversion.
Syntax Ifx, y and z are of byte then the intermediate result of
X *y may excced the range of cither of its byte operands. n
(target_tyTpe) value target type.
this case Java promotes the byte or short value into int
It is a desired type to convert automatically.
y
the given value.
While casting the types, it is necessary
to prevent the However, the automatic type promotions are v
narrowing conversion which causes
is converted to short
data lost. If the long value confusing and may cause compile time errors. The errors occu
then there may be a chance to loss
Similarly, when a floating-point of data. l the Java promotes the
operands to one 1ype and the resu
value 3.25 is casted to an int of another type.
value, then the value will
be converted 3
025 will be lost. It is better avoid to and remaining data For example,
to narrowing conversions to
prevent loss of data.
Program byte x = T00, y;

class CastingExample y x5;


causs
his slatement is even though logically correct but cu
compile time error since by multiplying with
public static void main(Stringl o x
byte value
] args) Cxceed the byte range and will be promotcd to int ype
while evaluating the expression. Since thhe
resultan
char c and we are storing in byte variable in
results compile time
ne
int x; In such case where the resultant type may exceed
must use explicit casting as slhown below.
double a, b;
byte p byte x 100, y;
y (byte) (x 5); *

Look for the SlA GROUP


LOGO on tho TITLE CoVER before you buy
1:21
INIT-1 Object Oriented Thinking and Inheritance
Rules for Type Promotions 1. One-dimensional Array
ofhomogencous
In evaluating expressions byte or short types are A one-dimensional array is an ordered list
promoted to 'int'. data items with one subscript.
If one of the operands of an expression is of, Example
2.
Float type then entire expression is promoted to Subject[5]:
float. Creation of One-dimensional Arrays
steps to be processed.
Creation of an array needs three
Double type then entire expression is promoted to
double. They are,
(i) Declaration of the array
Long type then entire expression is promoted to for the array
i) Allocation of memory locations
long. location.
(iii) Initializing the memory
Example
(i) Declaration of the Array
The following example illustrates the type promotion in in two ways.
An array can be declared
expressions.
1s way
class PromotionExample
datatype arraynamel J:
2nd way

public static void main(String args[ ]) datatypel] arrayname;


Examples
= 30; int subject[ ):
byte a
int[ subject;
]
char b Z Here an important point to note
is size of the array should
int c= 450; not be given during declaration.
d= 32.67f;
float (ii) Allocation of Memory Locations for the Array
with the
double e 1.260; Memory locations are dynamically allocated
aid of 'new' operator.
double expr (c*d/(b*c) + (e*a):
=
Syntax
System.out.println("Expression=" + expr);
arrayname = new datatype[size];
Example
subject= new int[S];
different types of Both declaration and memory allocation can be done in
Q41. What is an array? What are
of using arrays. a single step as follows,
array? List out the advantages
Syntax
OR
datatype arrayname = new datatype[size];
declare the array
What is an array? How do you Example
in Java? Give Examples. int subject =new int[5];
Declaration of the Array)
Refer Only Topics: Array, The first two steps are pictorially depicted below.
Nov/Doc.-18(R16), 03(b) Step 1: datatype arrayname[ ]:
Answer
Step 2: arayname new datatype[|size];
Array
homogeneous data items, Example
An array is defined as a set of
member in the array 1s
Step 1: int subject[ ]:
uobed under a single name. Every
assigned an index number or subscrip. Step 2: subjct = new int[S];
Types of Arrays Statement

The three different types of arTays are,


int subject[
. One-dimensional array
Result

2. Two-dimensional array
3 Multi-dimensional array.
STUDENTS
ECIRUM ALIN-ONE JOURNAL FOR ENGINEERING SIA GROUP
JAVA PROGRAMMING JNTU-HYDERAb
.22 ABADI

rcfercncc varinblc is creatcd.


A Column 0 Column l Colun

Row 0- a[0][o] a0][1]


Subectf0 a{02
Subject1
Subrct/21|
Subjc[3
RowI a[iJ[o] al1]all][2]
Subyect[4]|
Row 2 a2][0] al2]1] a[212]
subject new int[5}:
Initinlizntion of the Memory Locntion a[3][O]
Row 3 al3]I|a[3||2]|
Initinlization means inserting valucs into the array.
Initialization of arrays can be donc through loops or by
dircct assignment. Row 4 a[4][0] a[4][1] a[4]12]

Example
3. Multi-dimensional Array
forfi-0;i<5;i+ +) For answer refer Unit-l, Q42.
Advantages of Using Arrays
subject[i)- . Array is the simplest kind of data structure.
2. It is relatively casy to creale, understand and implement
arrays.
subject(0) . In arrays direct access to any clement is possible.
subject[1 However, modifications done to one element does not

subject[2]| cffect the other.


uhject|3 Arrays have the capability of linking data togethet.
especially with multiple dimension.
Rubject|4
Every array element can be accessed at constant time.
or subject[2] 101; O. Array variables are capable of storing more number of
values.
ubect|O]
Q42. Explain about multidimensional arrays W

examples.
mubjec1|2) 101
Answer (Model Papor-, a3(a) | Nov./Dec.-17(R13), CJe
ubject(3
Multidimensional Arrays
sutyec114
tored
These arrays consists of homogeneous data items sto
2. in more than onc dimension.
Two-dimensional Array
Exnmple
When the data is required
to be storcd in the form
matrix, two-dimensional arrays of a Subject[2]15
are used. ineering
Let us consider subject resers to subjects engin
Syntar of
Subject|2||S] as a whole means 2 semesters 5 sub
data type array-nane [row Subject[oJI0]
size] [column sizoj; I
semester 1st subject
Fiample Subject[0|[1] I
semester 2nd subject
int a[ 5]13: Subject[o]|21 I
semester 3rd subject
Above declaration
Subject[0|[3] I
semester 4th subject
represents a two-dincnsional Subject[014] I
semester 5th subject
consisting of 5 rows and 3 atray
columns. So, the total number Subject[| I[0] Il semester Ist subject
clements which can be of
stored in this array
are 53 i.c., 15. Subjcet ]U] l semester 2nd subject
The represendation Subject[I ||2]
of 1wo-dimensional II semester 3rd subject
3 in the memory array of size 55
is shown helow, Subject[1 |I3] l semester 4th subject
Subject[I ]|4] l senmester 5th subject.
Look for tho SlA GROUP LOGO on tho TITLE CoVER belfore you buY
Tentedininking and Inheritanco
Here, one more dimension called
scmester is ndded to Exnmple
the carlier single dimensional array. The number of subscripts
indicate number of dimensions. for(i 0; i<4;it)
If one more dimension called 'ycar' is to be added the
array would be as shown below. forj0 :j<2:jt+)
Subjectlyear|| semester]|subject):
Example lor(k 0 ;k<5;k+ 4)

Subject|412][51
It indicates that there are 4 years and in èach year there Subjectillil|k] 2:
are 2 semesters and cach semester has 5 subjects.
This can be pictorially depicted us follows,
Subject YearI Sem V Subyect
1I Year I
Sem IV Sulbject
Sem I
IYcarI 1.1.8 Oporators
-IV Year I
Sem |I Subect Q43. What are the diforent types of oporators prosent
in Java? Explain.
sem- OR
Il sem-
What are the different kinds of bitwise and
Creation of Multidinmentional Arrays booloan logical oporators? Nov./Doc.-16(R13), a3(a)

(i) Declaration of Multidimensional Arrays (Refer Only Topics: Bitwise Operators, Logical
This is similar to single dimensional arruys. Operators)
Syntax OR
. [n); What are arithmetic operators? Explain.
datatype arrayname|1][2].. .

n' is required number of dimensions. (Refer Onty Thplc: Arithmetic Operators


Example Answcr : Nov./Doc.17(R13), a2(b)

int Subject[ ]L IU ]: Operator


(ii) Allocation of Memory An operutor can be delincd s a symbol which perform
specific operations such as mathematical, logical and other
Syntax manipulations using one or more operands. Java supports large
[n]:
arrayname= new datatype[ 1]12].. .

number ol operators.
Example Types of Operntors
Subject new int[4]12][5]: The operators tUat are prescnt in java are as follows,

(ii) Initialization
. Arithmetic operators

fori= 0;i<a;i + t) 2. Relational operators


Logical operators
+)
forg 0;j<b:jt 4. Assignment operalors
5.Bitwise operators
for(k =

0; k < c:k+ t) . Shit operalors


Ternary operator (?).
arrayname[iJ0]Ik]= value; Arithmetic Operntors
Ihe operators that can perform arithmetic operations
are
called ns arithmetic operators., The various arithmetic
operators
present in java are as follows,
ENGINEERING STUDENTS
"ETRUM ALL-IN-ONE JOURNAL FOR SIAGROUP
u-NYDERABAD
JAVA PROGRANMMING (JNTUHYDERA
1.24
(Addition)
tw pertoEm addhton oeratn Kmen hwv operands
Theoperatur is usd
d)
(Subtraction)
The'operatorperfurms subtraxton
opNTation ween tmv operandts
(Multiplication)
tvwooperands
The operator caleulates the pruduct of

d)(Division)
operands and yiekds the quotient as resuh.
The operator computes divisin between twv

e) %Modulus)
modulo division enveen O values ardd gives the remainder as result.
The %' operator performs
( (Increment)
adds the value I to its operand (same as a = a* 1). An increment operator cm
The+is an increment operator that
applied in two ways to the operand as follows,
Pre-increment
ncrement operator, then it is said to be pre-inerement.
If the operand is preceded by
Example
+a iipre-increment
Ifa = 5, then the value of a will be "6°.
() Post-increment
post-increment.
If the operand is succeded by inerement operator, then it is said to be
Example
a /post-increment
*7*'.
Ifa =6 then the value of'a will be
Mostly. the prefix and postix inerements are similar. However, they differ when used in larger expressions.
compared to
l an r
IS pre-incremented, then the Java compiler evaluates this operator first, since it has higher precedence

increment.
(g) -- (Decrement)
rahr
The-'is a decrement operator that
subtracts the value I from its operand (same as a = a- 1). The decrement
often applied in two ways to its operand as follows.
(i) Pre-decrement
If the operand is preceded by decrement operator then it is said to be pre-decrement.
Example
--a; pre-decrement

If a= 7 then the value of'a' will be "6'.


i) Post-decrement
If the operand is succeeded by decrement operator then it is said to be post-decrement.
Example

a- post-decrement
If a= 9 then the value of 'a' will be '8°'.
decrement.
As similar to
increment operator, pre-decrement operator has highest precedence compared to PUS
arithmetic operators can be applied to integer types, floating point types and as well as mixcd values ot both n
tyT er
floating point type.

5Look for the SIA GROoUP LOGO Ton the TITLE COVER before you buy
1.25
UNIT-1 Object Orionted Thinking and Inheritance
Program
puhlic class ArithmcticExample.

public static void main(String[ ) args)

int a. b,e:
a S:

b 6;
c a+b;
System.out.println("Addition ofa, b:" +
c);

System.out.println("The value of c afler postincrement is:" + c);

sa-b;
System.out.println("Subtraction of a, b:" + c);
C-

System.out.println("The value ofc after postdecrement:" + c);

C a/b;
System.out.println("Division ofa, b:" + c)
++c;
Sy'stem.out.println("The valuc ofc after preincrement:"+ c);

ca b;
System.out.println("product ofa, b:" + c);

System.out.println("The value of c after predecrement:" +c);


c a%b;
System.out.println("Modulo division of a, b:" + c);

2. Relational
Relational operators can be defined as the operators that can perlorm comparisons between two operands. The relational
operators can be shown as follows,
Operator Description
Less than
Less than or equal to
Greater than
Greater than or equal to
Equal to
Not equal to
Table: Rolational Oporators

SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS


SA GnG
JAVA PROGRAMMING JNTU-HYDER
1.26
The reatinal onerans yiold Aadean vakpes resad. R can ayslid a all muanri bp*s and aly tohachartb
Troram
class Relational

puhlic stabc void mainŠtringd } ay

nt

oulean as

System.out printin( * %
ifx )
System.outprinttni"x less than or aqual to y

System.out.println("is x aqual to y"%


ix>y)
System.out println("a is grester than y"*

ifx=)
System.outprintln("xis greater than or cqual to y"):
ifx=y)
System.outprintin("x is equal to y")

3. Logiceal Operators
ogia
Logical operators can be defined as the operators that can perform logical operations between two operands. The log
operators can be shown as follows,

Operator Description
AND
OR
XOR (Exclusive OR)
Logical OR (OR) Short-circuit OR
&& Logical AND (or) short-circuit AND
Logical NOT

Table: Logical Operators


De logical operators yield boolean values as result.
ogn
operators perform operations based lt compare only boolean type values. As a matter r
on the following truth table.

7Look for the SlA GROUP LoGO on the TITLE COVER before you buy
UNIT-1 Object Oriented Thinking
and Inheritance
1.27

A
BA &
B ABAB A
T
F
TT F
T F

F T T
F
F F
gcal operators which can produce efficient code can be called as short-circuit logical operators. Because, shorl
circuit logical operatorS i.e., Logical AND(&&)
and Logical OR( ) evaluates the first operand and as well as second operun
I1

necessary. li Logical AND (&&) operator


is evaluating., it checks the first operand and it is true, then it checkS Sccond o
otherwise t teminates. Ihe logical OR ( ||) evaluates
if it is Talse then evaluates second
operand. However, logical operators such as &, 1,
Therefore, short-circuit logical operators
are eficient compared, to logical operators.
! ,
the first operand and if it is true it does not evaluatc second opeiu
evaluates both opcrands CVCiy e
Program
class ShortCircuitExample

public static void main(String[ ]


args)

int a, b, c, d;
=
a 10;
b 20;
c 30;
ifc> a &&c>b)
System.out.println("c is greater "):
ifa<b| a <c)
System.out.println("a is smaller than b or c");

4. Assignment Operators
Assignment operator can be defined as an
operator which assigns a
2551gnment operator is as follows, value to the variable
or operand. The general
Syntax forn of
variable_name = expression;
Here, variable name is name
This expression of the variable and the expression
is valid only if the both type is required expression
java is "chain ol variable and
expression are same. that has to be assigned
of assignment" which assigns a single The other to the variable,
Program right hand value to all feature of assignment
the variables in operator in
the chain.
public class AssignmentExample

public static void main(String[ ]


args)

int a, b, c, d;
a-b c= 10; Ilchain of assignment
d- 10;
la
System.out.printin"The
valucs ol a, b, C and d are:" +a
+** "
+b +" "
+ c+ "
+ d:
PESTn
1.28 JAVA PROGRAMMING IJNTU-HYDERA
In assiguneutoperutor, Java auporta another fenture | .
Shl Operntors
ADAD

callod nlort
on had aunignnot opeatou, This lonturo makes
e eodin! of aigment opeinlor caay. Tho jgoneral lorm of Shin operators can le dclincd ns tho operator
i
ulhort hand nsigunent operator in an follows, sbiln the bit position value to the led or to the right d hat
cpendinq
Syntax on the required position. The shin opcrators present nt in Java
VArinblo nnme oerator Oxpresuion; nw follow, a
Exmple Operator Descrlption
x12; /whlch Iainilar to x x 12
Le shin
5 /which is ninnilar to x x5
Tho arithmetio anud logical nlorthand nuaignmenta nre Right shin
an Sollows, Unsigncd riglht shin
Arlhnetle Loglenl
Tho general form of shill operutors is follows,
Value «<
number of bits
Valuo>number of bits
Vuluc nmber of bits
>>>

The value is the one which huve to be shifled depending


on pecificd bit positions. The le slhit operator is used to shin
the vulue on lel depcnding on spccilicd bit positions and brings
the sign bit value 0 on to right position. The riglht shit is usod
Biwise Operators
to shil the value on right and assigns 0 on left.
Bitwinc operators can manipulate tho sot of bits The>>> (Unsigned right shit) operator always assigns
Ociated with the operunda. Thexe operntora can bo ngpplicd to it as
0on lel. Thus, is called zero-fill right shil.
integer typoc and charactler lype valucx und cannot le npplicd to
7 Ternnry Operator (7)
floating-point and boolen type valucs sinco bitwise opernlors
can lest, set or shift the individual bits to build another value. The genernl forn of ternary operateor is as follows,
These operatorn are eusential lor ditlerent progranning Iusks condition'? exprl: expr 2;
Java supports various bitwise operntors. These operators IIere, condition is the required condition and exprl, cxpr2
are ns follows, are required expressions of uny type excluding void dala typ*
Exnnple
Operator Descriptlon
a>b7 "a is big": "b is big"
Ditwise AND
Ifthe condition a > b is trnue, then the first expression"a5
Bilwise OR e big" will be the result ofentire cxpression. Wherens if condtin
is fulse, sccond expression "b is big" is the result. The terman
Bitwise exclusive OR
operator is nlso called us conditional operator.
Onc's complement P'rogram
Shin len clnss Ternarylixample

Shil right
public static void main(Stringl ] args)
Shin right with zero ill (or) unsigned
shin right int x, n-3
Table: Ditwlso Uporntora wlhile(nS5)
Tho result of bitwine opcrntorn cnn be shown in the
following table, X
nlO7 100/a: 0; //it prevenls ine
Wexpression 100
A & A| AD -A
ifqnl-0)
0
System.out.println"11hc output is l00 **

Look for tho SIA GROUP LOGo on tho TiTLE COVER beforo you buy
1.29
UNIT-1 Object Oriented Thinking and Inheritance
precedence ot al
The symbols( ). and. have highest
[ ]
Q44. Discuss the order of precedence of various
operators. the operators and thcy arc evaluated first.

Modol Paper-il, a2(a) Example


Answer
8+4*(8-2)
Operator Precedence
In Java, every operator is assigned a precedence =8
+

4*6
which determine when it must be evaluated once is used in
it
- 8+ 24
an expression. The operator with
higher precedence will be
evaluated first and the operator with the lower precedence will1 2
next. Q45. Wite a short note on making use
of parenthesis.
be evaluated

The below table depicts the precedence of the operators Answer


in the order from higher to lower. the operations is raised
The qucstion of precedence of
operators. This is very much
Operator Description by the parenthesis holding those
result. Consider the below
+ Post increment important is obtaining the desired
expression.
Post decrement
x>>yt 5
Pre increment 5 and then shifts 'x'
The above expression will first add
Pre decrement by the obtained result. So, it can be
written as follows,
Tilde x>(+ 5)
y and then add
Logical Not If the user needs to first shift x right by
5 to the result then the above expression can be
parenthesized
Unary increment
as follows,
Unary decrement
x>>y) +5
Multiplication
Rather than changing the precedence of an operator,
Division parenthesis can even be used to clarily the expression meaning.
Modulo division Certain complex expressions might be difficult to understand.
%
Such confusions can be cleared using parenthesis. Thereforc,
Addition parenthesis added to reduce the ambiguity will not at all affect1
Subtraction the program in anyway.

>> Right shift 1.1.9 Expressions


>>> Unsigned right shift Q46. Define an expression. Discuss how an expres-
Left shift sion is evaluated with an example.

Greater than Answer:

Greater than or cqual to Expression


Less than An expression can be defined as a combination of
Less than or equal to operators, variables and constants. These are referred as
equal to constituents of an expression.

Not equal to Example

& Bitwise AND c =at b;


ODR
Bitwise exclusive
a5
Bitwise OR
b a* c;
&& Logical AND
Expression Evaluation
Logical OR
Exprossions in Java are evaluated
: Conditional through the use of
assignment stateinent, which is of the form as,
Equal
variable expression;
SPE
ROM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS
SIAGROUP
JAVA AYDERABA
ViMING lJNTU-HYDER
130
the varable indicates the name
ln the avDVe Statenent,
cdepicts a complete expression
the variable. The epressiom
of
opcratos. The capression will be Expression
ase
ontaininw opefands and result ot it will be assigned to
evaluated initially and then the condition
hand siule. Even it tlhe variable
the variahle which is on the let
be eplaced with the evaluated
holds any other value it will Tnue
esult. Consider the elow statements, LStatement-block

a
L Statement-next
-()+ Np:
In the abvVC statements, the values are lirst assigned to Figure: Flowchart of Simple if Statement
is then evaiuated and
the nespetive vanables. The expiession
leti hand side. (b) if-else Stntement
the result is assigned to the varnable on the
This statement is an cxtension of simple if slalcme
1.1.10 Control Statoments
Syntax
Q47. What are conditional statements? Discuss
various typos with examples. if (condition)
Answer
statement-1;
Conditional Statements
Conditional statements can be defined as the statements
that are exCCuted depending on the specilied condition. If the else
condition is true, block of statements are executed. Othervvise
control flow comes out of the block.
statement-2;
Types of Conditional Statements
The various conditional statements available in java are
as follows, statement-next;
(a) if statement In the above syntax, statement-1 will be executed followed
(b) if-clse statement by statement-next when the condition is true. Othenvit
(c) nested if-else statements statement-2 will be éxecuted followed by statement-next
(d) if-clse-if ladder
(c) switch statement
() nested switch statements. Condit ion False
(a) if Statement

i statement (or simple if statement) is used for decision Iie


making. It allows the computer to first
evaluate the condition Statement-1 Statement-2
and depending on its resultant value it
transfers the control to a
particular statement in the program.
This statenment performs an Statement-next
action if thecondition is true,
otherwise it skips that
action and executes other statement.
Figure: Flowchart of if-else Statement
Syntax
Program
if (condition)
class IfExample

statement-block;
public static void main(Stringl] args)
statement-next,
HeTe, if the int a, b;
condition is satisfied,
is executed followed thenstatement-block
block is by statement-next. Otherwise. a = 5;
skipped and only statement
statement-next is
executed. b=6
Look for the SIA
GROUP LOGO I on the TITLE cOVER before you buy
UNIT-1 Object Oriented Thinking and Inheritance 1.31

if (a>b)
Fase
System.out.println"a is greater than b"): True Condit ikon-

clse Fake
Condd kn-2

System.out.println("b is greater than a"):


Statement-3
Statement-1 Statement-2J

StatcIment-nex

(c) Nested if-clse Statements


Figure: Flowchart for Nosting of if-elso
Statement
Anested if-clse statcment is an if statement which is
defined in another if statement. The nested if's are essential Program
public class NestedExample
in programming since they yiclds a follow-up selection

depending on the result of previous selection.


public static void main(String[] args)
Syntax

ifcondition-1) int a, b, C
a=7
b 8:
ifcondition-2) c 9;
if(a> b)

statement-1; if(a > c)

System.out.println("a is big");
else

else

statement-2;
System.out.println("c is big");

else

clse if(b> c)

System.out.println("b is big"
statement-3;

else
statement-next;

If Condition-1 is true, then condition-2 is execulea System.out.println("c is big");


otherv
wise, statement-3 will be executed followed by statement
icondition-2 is evaluated then statement-1 is cxccuted
COndition is true) or statement-2 is executed (if condition is
false)
tollowed by statement-next in botlh cases.
JAVA PROGRAMMING [JNTU-HYDERABA
l.32 AD
if-else-if Ladder clse if(x = = 1)
(d)
if-clsc-if ladder can be delined as a sequence of if-else System.out.println°The one
value of x is one"),
staternents. The general form ol il-else-if
ladder is as follows, clse ifx= -2)
System.out.printin(°The value ofx is two'
Syntax
ifcondition-1) clse
statement-1;
System.out.println(°The value of x is
greater than two");
else ifcondition-2)
statement-2;
else ifcondition-3) (e) switch Statement
statement-3; switch statement can be called as multi-way branching
statement. The statenment provides multiple alternatives and
the user can select the required option.
clse ifcondition-k)
Syntax
statement-k;
Switch(expression)
else
statement-kt1; case constantl: statement-1;
statement-next; break;
The conditions are evaluated sequentially (i.e., from case constant2: statement-2;
top to bottom). If a particular condition is false then the next break;
following conditions are evaluated. If a condition is satisfied,
then its corresponding statement is executed. case conslanin: statement-n;
break;
default: desault-statement;
Condition-1
break;

Condton-2 False
Statemyt-1]
statement next;
Here, the expression is a valid "C expression and
Truc Condtion-3 False constant is the result of the expression. When the constan
Statement-2 value is a character, it has to be enclosed within single quotes.
Defaut
The value ofthe expression is evaluated and it is compared
Statementi-3] statement with constant case values. When match is found, the corresponding
statement block associated with the case is executed.

Case I) Case action break


false

unue
Figure: Flowchart of else-if Ladder Case action break
Progran
false
class LadderExample
true Case acion
public static void main(String[ ]
args)
break
False
default Case oction breakJ
int x 2;

if(x 0)
System.out.println"The value ofx is negative");
else ifx 0)
System.out.println("The value of x is zero"): Figure: Flowchart of Switch Statement

Look for the SIA GROUP LOGO Z2 on the TITLE COVER before you buy
JNIT-1 Object Orientod Thinking and 1Inhoritanco 1.33

Program Syntnx
class SwitchExample wwitch(cxpression1)

public static void main(Stringl ] args) Ibody


Switch(cxpression 2)

int x;
Ibody
for(x 0; x < 7; x++)

switch(x) d

Exnmple
case 0:
switch(opl)
System.out.println("Sunday");
System.out.println("outer Switch block");
brcak; case :
case 1: break;
System.out.println("Monday"): switch(opt 1)

break; System.oul.println("lnner Switch block:"):


case 1:
case 2:
break;
System.out.println(""Tuesday"):
I/body
break;
case 3: break;
System.out.println("Wednesday'"):
case 2:
break; =
case 4
System.out.println("Thursday");
Q48. Explain the different types of loops with
examples.
break;
Answer:
case 5:
System.out.println("Friday"): Loop
Loop is a process of executing action or series of
break; actions defined in the blocks of code infinitely. It is necessary
to terminate the loop as soon as the required task is completed.
case 6:
System.out.println("Saturday"): Hence, a condition is used to control the loop before or after
the cxecution of every block of code. The looping mechanism
break; must include the following steps,
System.out.printlnf"No weck days"); Step 1: Declaration and initialization of counter.
default:
Step 2: The executable stalements in the loop.
Step 3: The condition to execute the loop.
Step 4: Incrementation/decrementation of the loop.
It Types of Loop
statement is not mandatory.
Genetally, the break particular
after cxecution of The dillerent loops that present in Java are as follows,
inates the switch block successive cases
prevents the execulion ol (a) while loop
.Thereby, case it
ncluding default (b) do-while loop
Nested switch Statements (c) for loop
can be defined us the switch
Nested switch statcments (d) for-cach loop.
block.
ament with in another switch STUDENTS
FOR EMGINEERING SIA GROUP
ECTRUM ALLHN-ONE JOURNAL 2
-
1.34 JAVA PROGRAMMING IJNTU-HYDERADA
ABADI
(a) while Loop remainder = val%10;
The 'while' statement will be cxecuted repeatedly as val= val/10;
long as the expression remains true. res = res *10+ remainder;
Syntax while(x > 0);
while (expression) return res;

body of the loop;


(b) do-while Loop
When the 'whilc' is reached, the computer cvaluates It is similar to that ol "while loop except that
expression. If it is found to be false, body of loop will not be Cxecuted at least once. The test ol expression for
it
repeating i
executed and the loop terminates. Otherwise, the body of loop done alter each time body of loop is executed.
will be exccuted, till the expression becomes false.
Syntax
do
Fase
Expressim
True body of loop;

Body of the Loop while (expression);

Body of Loop

Next statement True


Expresson
Figure: Flowchart of while Statement False
Program Next statement
import java.util.Scanner
Figure: Flowchart of do-vwhile Statement
public class WhileExample
Here, Java compiler executes the body of the do-while
loop first without evaluating any condition. A fter this execution
public statíc void main(String[ ] args) the condition can be checked and ifit is true the loop is executed
otherwise terminated. The do-while statement 'can be called as
exit-controlled loop since it checks the condition at the end o
Scanner sc =new Scanner(System.in); loop.
Scanner class for reading input Program
Systern.outprintln("Enter the input number); import java.util.Scanner;
ind ip sc.nertlnt( ); class DoWhileExample
int res reverseMethod(ip);
System.out.println(The reversed number is" public static void main(String[] args)
+res);

Scanner new Scanner(System.in


sC =
pblic static int reverseMethod(int val)
System.out.printin("Enter the number");
int ip =
sc.nextlnt();
ind res-
int res reverseMethod(ip);
int remainder, versing
System.out.println(The result after reves
wtiledval 0)
the number is" t res)

Look for the SiA GROUP LOGO on the TITLE CoVER before you buy
ObjectOriented Thinking and trhertance 1.35
UNIT
public static nt reverseMehcd i)
Sora - 5; a< 10; a*-)
int res = 0, remainde
+a);
System.out println("The a value is"
do

remainder =x%l0,
x =/10,
(d) for-each Loop
res = res" 10 + remainder, enhanced for loop
Tbe for-cach loop can be callod as an
while(x> 0); collection of clements. The
whh traverses aray elements or progTamming erTors and
return res; forcach oop is cssentially to reduce readable format.
can be usi to build the code in high
Syntar
clements)
array-name collection of
ton data-Dpe variable:
(c) for Loop
looping staterment
for' statement is another type of
Syntax
A variable can be
for (initializing expression; testing
expression: updatingS Here, data-type is the variable type.
of an array and
aray-name is the
expression) reated to access the elements
name of the aray.
the variable one after
The array elements are assigned to in
is executed until the clements
statements; the other and the loop body
not require any condition and
an array are completed. does
It

incTement or decrement statement to


execute body of the loop.
specifies the initial
Here the initialization expression
value. The testing expression isa
condition that is tested at Program
each pass. The program is executed till
this condition remains public class ForEachExample
expression that is either
true. Updating expression is an unary
the initial value. The
ncremented or decremented to change ] angs)
the beginning public static void main(String[
conditional expression is evaluated and tested at
while unary expression is evaluated at the
end of cach pass.

Init ia lizing intal = {1, 2, 3, 4, 5;


expressx Fase forintx: a)
Updating
Cxpression Testing
expressxon System.outprintln("The element of aray is ");

True System.out.println(x):

Body of Loop

Q49. What are tho differont types of Jump statements?


Next stateent Explaln each of them with an examplo.
Figure: Flowchart of for Statement
Prograam Answer:
Jump statements can be used to skip over the loop by
public class ForExample terminating a set of statements. The various types of jump
statements in java are as follows,
]
(a) Break
public static void main(Stringl args)
(b) Continue.

TRUM ALAN-ONE JOURMAL


FOR ENGINEERING
STuDENTS SI\GROUP
1.36 JAVA PROGRAMMING JNTU-HYDER
HYDERABAD

(2) Break (b) Continue Statement

The "break' statement performs unconditional jump Continuce statement is a unconditional


jump
that terminstes or euists the iterathon or suitch statement. It tells the interpreter to continue the next iterationofstate
the
terminstes the loop as soon as the control encounters it. And is a keywvnd usad tor continung the neNt iteration of th
then the coatrol is transferred to the statement that ovcus after In contrast to the break statement, the continue statenhe
the ineration or saitch sutement. Therefone, it coses the smallest not exit from the loop but transters the control to the
enciosing da, for, switch, while statements. Ii is written as, capression (while, do-whilc) and to the updating
(for). While and do-while loops can logically act as a
esN
break:
statement that transter the control to the end of the loon
This is because both these statements transter their cont
two difterent positions.
Test
Tre Conditina Program
Breal
public class ContinucExample

LFase public static void main(Stringl ] args)


Figure
Program int x= 0;
class BreakExample while(x< 15)

public static void main(String[ ] args) if(x%2)! = 0)


continue;
int x a, b; System.out.println(x);

I 10;

for(a = 0; a<x; a +)

b aa; Here, the even number is printed


iftb x) whenever x'o2 *
and gets iterated using continue statement when *°o2 =u.
break; This loop iterates until the x value
reaches 15. When continu
statement is used in inner loop of
System.out.print("b=" nested loops then the contro
+b+ *):
*
goes to the condition of outer
loop but not inner loop. If contnas
statement is used in while and
do-while loops, the control go
to the loop condition immediately.
System.out.println("Completion However, if continue is u
of loop"); in for loop, it evaluates
the iteration expression
next loop condition is of loop
executed and finally the loop bouy
executed. The continue statement setol
is mainly used in
loop statements that used in
Here,
the for loop is frequent applications. Due to
reason, java supports
O1a exceeds 10. Afterthe terminated when the square value continue statement.
statement loop termination, the control goes to next
which prints "Completion 1.1.11 Introducing
of loop. Classes
When the break
oops, then the statement is used in inner loop Q50. What is a class?
control comes of nested Write of
the next statement
after inner
out of the inner loop
and goes to class with an example. the general form
not terminates
the outer loop. loop. The break statement does
is a need to remember While using break statement, Answer: e ts
two points. there ct Model Paper-l, a70
() In a loop multiple Class
break statements
(i) If break is can be used Aclass can and
used in switch, be defined as a template that group>
its associated functions. ups data
terminated but then the switch block
not the loop is The class contains two parts amely
defined. in which switch
block is (a) Declaration t
of data variables
(b) Declaration of member
Look for the functions.
SIA GROUP
LOGO on the TITLE GOYiR E
1,37
NIT-1 Object Oriente
UNT Thinking and Inheritanco
Also
The data members of u class cxplains about he state of1 a61. Glvo a bri1 dsstription stsu dstlaf6d
d and
and
and the member function cxplains about the behavinut 0xplain ho an otbjact can be
rethelass There are three types of variables available for a
o lass.
They arc,
inltializod.
class. Answer
Local variables
Objeet onss wich
matande uf n
(i) Instance variables An object can te defined as an
n claos
(ii) Class variables. is used to accEes the mernters tf
Local Variables Declaratinn of An jees
varinthle declarstim
Local variables are the variables that are declared inside An tubject is sinilat to hat of
the methods. Synta
Instance Variables name of fthe classohject_piatne,
(i)
Instance variables are the variables that are declarcd Example
inside the class but outside of the methods Student objStudent, thjAuderd
the claoa arel
Class Variables Here, Student ia the name of sepresert he thijec1. A
(i) can
Class variables are the variables that are declared inside isthe relerence vatiable wich declared fot ni oject Jur
with static modifierand they resideoutside
ofreference variable objStudent is
class
themethod. hold the address of the object.
the mll
StudentohyStudent
General Form of a Class
obyStudert
A class can be declared with the help of 'class'keyword
Initializathon of Object
followed by the name of the class. The syntax of a class is as
When a rcference variable is
declared, it lo necessary
This can be
t
follows,
physical copy of the object to that variable.
class name_of_the_class
assign allxcates tnemny
operatun. his operattn
done by using 'new' agumicril
iables using a single
dynamically to storre instance var allcatium, eu
declaration of Instance variables After the memry
called as constructor call. the class.
nernory locationn to
ype data_variablel; operatot rcturns the address of variable vwhich is
This address can be stored in the reference
type data_variable2;
crcatcd.
/declaration of functions
Syntax
type function_namel(arg_list) nanel ),
class _name object narne new class
Example
body of function Student objStudnet new Studentl),
created and
Here, an object nramed as objStudeit is
variahles are assigncd
type function_name2(arg_list) memory is allocated Mcanwhile, instance
with various valucs. Ilowever, it is requircd
to start with initial
valucs are
body of function valucs. If initial values arc not specilied, delault
assigned to these instance variables depcnding on its data type.
The initial valucs are assigncd using the following
mechanisms,

one logical entity (a) Instance variable initíaliver


Itis better to maintain information of (b) Constructor
in a class.
(a) Instance Variable Initializer
Definition of a Class
The instancc variable initializer assigna values directly
class Student to any instance variable which is declared outside the
Sunction/nethod but inside the class.
int stdld; (b) Constructor
int stdName Constructor is oten ucd to initialive the objects.
void getStdld( ): When an objcct is creatcd, constructr in automatically
invoked. If constructor in not created manually, a default
int setStdld(int sid);
constructor with no arguments and hody will be created
by java compiler. This default constructor is invoked
Student. In this class,
he above definition creates a class ), afler the cxecution of below statcment.
and stdName are the instance variables and gctStdld(
d
eS1dldt ) are the member functions of the class. new Studet( )

In Java, main( ) method often defincd in the class itscls. The name of both constructor and class is always tame.
SPECT
RUM ALLHN-ONE JOURNAL FOR ENGINEERING STUDENTS SIA GROUP
1.38 JAVA PROGRAMMING IJNTU-HYDERARA.
ABAD)

Accessing Clnss MMembers Q53. Explain in detail about "this' keyword


rd andgar
bage collection.
a
An object can access the members of class using dot(.)
OR
operator.
Demonstrate the use of 'this' keyword.
Syntax
(Refer Only Topics: "this' Keword, Erample)
objectnane.membename; Answer May-19(R16).
Q

Example his' Keyword


The keyword "this IS used lo create a reierence to
objStudent.stdld- 10r:
object. It will be passed implicitly when method is cal!d Ths
objStudent.getStdld( ): wil be done automatically. Any member function can fid
address of the object and access its dala (to which it belonsi
llere, objStudent is the name of the object, '. 'is the by using this keyword.
operator used to aceess member functions and stdld is an Exanmple
instance varialble. Finally getStdld( ) is the function which is
class Exp
to be invoked.

Q52. Discuss in brief about assigning object reference


double x:
variables.
int ex;
Answer:
double y:
The behavior of the object relerence variables is dillerent
Exp(double base, int e)
than the assignment of it. For example consider two objects
defined below.
this.x = base; 2
Square sl new Square( ):
this.ex e;
Squares2= sl;
this.y= 1:
In the above code Iragment, it is not that s2 is assigned a
ife== 0)
copy of the object that sl refers to. The sl and s2 does not reser
to separate objects. Rather they both refer to same object. The
return
assignment statement will not allocale any memory or copy of for(e 10; e> 0; e -)
the original object. The s2 will refer to the object to which sl this.value this.value * base:
refers to. Thc changes done to s2 will also affect the object to
which even sl is referring.
double get()

return this.value:
Square object

class Demo
In the above figure sl and s2 refer to same
object.
Thereforeif any other assignment is done to sl then it will
unhook from square objcect without allecting s2. public static void main(String| 1
args)

Square
sl new Square():
Exp a = new Exp(2.3, 4)
Square s2 = sl;
System.out.println(a.x + "is raised to
sl null; a.ex+"powe
S"+a.gel( )
Here sl will be set to null but s2
will remaun p0inling to
original object.

Look for the SIA GROUP TITLE coVER before you buy.
LOGO oh the
1.39
JNIT-1 Object Oriented Thinking and Inheritance
Garbage Collection Q55. Discuss about tho stack class.
Dynamic allocation of objects is done using new Answer:
keyword in java. Some limes allocation of new objects fail Stack Clnss classes. Ilr
insullicient memory. ln such eases memory space achicved through
due to n Java, cncapsulation is naturce ol the di
consumed by unused objects is de-allocated and made available to deline the
COnsidercd as a new data lype n consistcnt
This is done manually in languages such as C methods tend to deline
for reallocation. and routines of it. The The class can he
the class data. implementalion.
interlace for
and C++ using delete keyword. In java a new concept ealled well as controlled of their
garbage collection is introduced for this purpose. It is a trouble- methhods irrespective The intemit
uscd through its as "data enginc".
assumcd
internal working can
ba
free approach which reclaims the objects automatically. This is In other word's class is
cxposcd so the
done without the interierence of the
programmer. The objects Tcalures of it are not exaple of tlh»
practical and archctypal form of lirst-
required. A
which are not used ior long lime and which does not have
any Changed as the
contains the data in perlormed on il such
is de-allocated. This would be the stack. It be
references are identihed and their space last-oul order. allows
IM two operations to nn ilem t
other objects. operation is used to insert
recycled space can now be used by
as push and pop. The push remove an iten
The pop operation is used to encapsulaled,
Garbage collection is only performed during program the top of the stack. casily
stack. A stack can be
therefore it is Irom the top of the
execution. It is a ume consuming process
performed only at relevant instance. Example

Q54. What is the use of finalize( method?


) What is class Stack
its disadvantage?
main(String argsl )
public static void
Answer );
Stack stk = new Stack(
finalize()Method Stack stk2 = new StackO:
An object makes use of
many non-Java resources such
resources for(int i =0; i<5; it+)
as file handle or window
character font, etc. These
is destroyed. Finalization is a stkl.push(i)
should be freed before an object With
used by an object. 10; it)
mechanism that frees all the resources should for(int i= S; i<
define specific action that
thehelp of finalization, one can by the garbage stk.pushi)
be taken when an object is
about to be destroyed System.out.println("stkl contents"):
collector. <5; itt)
that performs the finalization. for(i-0; i

There is a finalize() method it is about System.out.printin(stk I.pop( )%


the Java run time whenever
This method is called by ) method
that class. Inside the finalize( System.out.println("stk2 contents");
to destroy an object of performed
functionalists that must be i
<10; it+)
one can include all those collector checks fori 0;
destroyed. The garbage
etore an object is any class directly System.out.println(stk2.pop( ));
object that is not used by
dyTamically for each Java run time
freeing an asset the
or indirectly and just before
object.
callsthe finalize( ) method on thc
In the above program two stacks will contain the item
General Form
separately.
)
protected void finalizel
1.1.12 Methods and Classes

/body of finalization a56. What is a mothod? How a method is used in the


class? Explain.
finnlize()
keyword prevents the access to called
Answer
The protected This method is only
its class. Method
ny Code defined outside collection.
attempt of garbage A method is used to define what an object cnn accep
Dcfore an
in java. It will be created in the clas and therefore, it remains
Disadvantage garbagen
only prior tothe ns the part of the nssociated class. A method contains a set of
finalize( ) method is called an object goes out-of- statements which define çertain actions. Each method performs
he
example, it is not
called if is executed. a particular task.

For
That is, it will be not he
known, even il it
ENGiNEERIMG STUDENTS
sPEC
ECTRUM ALLHN-ONE
JOURMAL FOR
SIA GROUP 2
1.40 JAVA PROGRAMMING IJNTU-HYDERABADI
Syntar Q57. How a method can be overloaded? Explain
return_type method_name(arg1, arg2, .-., arg n) process of overloading constructors. th
OR
method_body What meant by overloading
is methods? Explain
in detail.
In the above syntax, the return_iype indicates the type (Refer Only Topic: Method Overloading)
of value that the method returns. The method_name indicates Answer: Nov/Dec.-17(R13), Q/D
the name given to the method. It should be a valid identifier.
Argunents are enclosed in the parenthesis. They can also be Method Overloading
declared when passed to the method. The body of the method Several methods in java are allowed to have same method
contains the operations that are to be performed on the data. name with different parameters and different definitions. This
A method can be called by an object as shown below, is called method overloading. This concept is used when there
is necessity to perform similar tasks with different arguments.
object_name.method_name(arg1, arg2, ., argn)
Compiler does not get confused when calling these methods
Amethod terminates or the control returns when a closing It fatches the method name, number of arguments and their
brace or retum statement is encountered. The result obtained type. based on this it decides which method to be called. This
after the task performed by the method would be the return process is called polymorphism.
value of that method.
Every method should be provided unique parameters.
Example
This concept allows the programmer to use several methods
class Square with same name and sometimes with same definition.
Example
int side:
class Square
void getData(int x)

int side;
side x
method 1(int a)
intSarea()
side = a,
int area 4 x side;
return(area); method 2(int b)

side = b,
class Square

int area()
public static void main(String args[ })

int res =4°s;


int a, b,
return res;
Square s - new Square( ):
Square 1new Square( ):
S.side 12;
Constructor Overloading
a4s.side as
LgetData(5) Constructors can also be overloaded in the same way
methods are done. They are declared and defined as metho ds
b Larea ): But constructors does not have return type. Constructors
System.oulprintln("Area ofsquare |" +
a) Ssame name of the class but each of it provides a dilier
System.outprintln("Area ofsquare 2+ definitions and parameters of different types.
b): be
AIl the constructors and the class can only
them
differentiated with their parameters. This is because all ofte
have the same name.

4Look for the SIA GROUP LOGO on the TITLE coVER bofore yoa buy
141
UNIT-1 Objoot Orlanted Thnking and hhortamoe
Vrample elann eotl'an
elann Nquare
publle otntie voiel albu(itsbng n )

int nide,
)
Obect bnew Oeot( 1000, 2),
Squaret hjeot 100), 22)
Ohneot vly)ow
eot ol)new heot(I, )
aide 13; Nynlem.out. printne"abl- )2"I ol
qallob2);
Nynlem.out.printle"ob|* olh" ob
Scquaretint a) eqmloli);

nide
will
the equnlToc method
In the above proprum,
equnlity. It comparon tlhe invokig
int area ) compe two obfectn lor in pnanel ai nryummont.
Tho type of
ohjeot with the oljeet that
thin object will be itn clana l.e., obfect.
concept would be conatrmetom
A commmom nage of thin
int res- 4 nide; ermatodl thequently. Thin vnn
The objects might bo required to be object of it
return side; be done by delining_
the constructorn thatl receives
clana an parnnieier,
Q50. Explaln how objocts aro
paanod to a function.
an pnram- Anower i
Q58. Dlscusn In brlof about uslng objocte as an argumcnt to a
An objcet in Javn can bo anscd
otors. nny variable to a liunction.
Sunction in the name way ns paRNing
a lunetion, (hey are as
Answer There are two waya to pasn nn object to
as paraniclcra toollow.
It inpossible even to pans objectsin illustratcd in the
This
functlons rather than simple types. Pass by value
below example. 2. P'ass by referenee.

Example P'ass by Value

class Objecct In thismethod, the copy' of tlhe object is passcd ns an


argument to the fiunction. The clinnges mnde to the object inside
is used to call1
the function will not allect the ictual objeet that
the unction. The rcope of the olbjcct will be limited only upto
int x, Y
the function to which is pass el.
it It is uscd in the fmction just
Object(int p, int q) ns nny new object.
2. P'ass by Reference
In this method, the relierence of the object is passcd as
an nrgument to the unction not the object or a copy of it. Thec
y reserence ofthe object is passe« by passing thhe nddress i.c., the
locatio of the objcct. 1lhe tunction can directly work on the
boolean cquation(Object obj) object. So the ehanges imade to the object in the lunction wvill
reflect back to the actual object. This method is mostly used
nnd is an clicient mcthod. This is becausc the cflort required
Mobj.x x && obj.y y) here is to pass only the nddress of the objeet but not tlhe entire
object.
retun truc;
An objeet is allowed to be passecl even to non-mcmber
clse unctions of a class nlso. These members can then access the
Tetun fulsc; publie menmber flnctions of the class through the lnetion
objects passedd to ft. They eannot accets the private members
Aunctions of the clns8

tECT
RUM ALLAM-ONE JOURNAL FOR ENGINEERUNa
STUDENTS SIA GROUP
JAVA PROGRAMMING (JNTU-HYDERABA
ARADI
olass jlRer

mpt java.in*;
smn janaul publio alatio vol unSng apol )

ObjRetun ol new Objitetumt3)


inm s ObiRem ob2
ol2obl.iner( )
Syatem.out.printlu"obl.x" olbla)
sde S
System.oul.priitle"0m2,x"t ob2.x)

md area(Square sq)
ob2-ob2.incv );

System.out.printn"ob2,x nller next inCreme


ob2.x)
int area 4*sqs
System vutprinttn|"Arma ofsquare:"t anea),

In the above progran, a new object gets Created fo each


DemDo time the incr( ) is invoked. This Aunction will eturn n object
dass
containing 1lhe value of grealer thun the invok ing oljeo
Q61. What ls rocurslon? Explaln wltlh an example,
puhic szati: void main(Stringl ] angs)
Answer :

STuerr sq Recurslon
**
Dew Squarr(S)
Recursion is the process or techniquo by wlhiclh a
function calls itself, A recurive Aunetion contaluns a slatement
within its body, wlhich calls the same Aunction. Thus, it is alao
called as circular definition. A recursion can be clasnified into
Q52 Write short notes on retuming objects. direct reeursion and indirect recursion. In direct recurslon,the
fiunetion calls itself and in the indirect recursion, a function ()
Ansver calls another imction (2), and the ealled fimetion (12) call» lie
A mehod can even retum the data of class type created calling nction (f1)
by the use in addiion o ocher types of data. Consider the below
eXmpie, When a recursive call is made, the parametem and relun
address gets saved on the stnck. The stack gets wrapped whe
Emple the control is returmed back.
class ObyRctun Advnntages
Recusion solves the problem in the most genernl
as possible.
ObjRenurn(int a) Recursive lmction is smull, simple and more rela
than other coded versions of the program
n"
Recursion is used to solve complicated problenis
have repetitive structure

ObjRcturm incr )
Certain problems cnn bo casily be understood
ecursion.
Disadvantnges
ObjRetum ob new ObjReturn(x + S); . nique
Usage of recursion ineurs overlhead, since this te
return b is inplemented using funetion calls
ystem
Wlhenever a recursive éall is made, some of the y
memory iN consunned.

Look for tho SlA GROUP LOGO on tho TITLE COVER before you buy
UNIT-1 Otjoct Oriernted Thinking and tnheritanco 1.43
annle Fact
Preterted Acress
prree
clas The variables and methods ahen declared
s
are avessad by all the clzsses beicrging to the same acie
int facterial(int a) the cuncept ot mberitance all the subeiasss
cn ee
prenee

members of ts ase class


res Syntax
tN ) proterted ditaype variabie_name
Erample
es- lactorial(n - 1)*
class Access
telurn res

class Ree Fublc int


private int
publie static void main( String arg[ })
void setr int x)

fact f new fact( ):


**
System.out println("Factorial of 6-
f.factorial(6)):

int getrt)
Q62. Explaln In dotall about the concept of
access
reurn
control In Java.
OR
Explaln tho slgnificanco of public,
protected
inhoritance.
and privato nccess spocifiers
in
class Dermo
QZ(D)
Nov/Dec-1T(RI6),
Answer
The methods and variables belonging to a class are
Other classes are not public static void mai Sring zrsl D
Ometimes limited only to that class.
cneapsulation Such
allowcd to access them. This is called as
calling the methods of that
ariables can only be accesscd by Access object = new Accesi
class. Java provides four types of
access speciliers namely
specificr. objertp 20
public, private, protected and a default
. Publie Access objoct- 30
The variables and methods when
declared as publie can
objert.setrt200x OK
concept of inheritance
Rccessed by all the other classes. Inthe members of its buse System.outprintin"The vaes of q mdr
thesubclasses can access the publie
class.
objactp" -otjatq -*"cdat
Syntn
public datatype variable_name;
publicdatatype method_name(args) t1
2 Private Access a63. What is meant by statie field and static method?
declared as private Explain.
Thevarinbles and mcthods when
dctined. In the
only by the class in which they are Answer
tesscd nheritance, the subclasses are restricted
Irom using
private members of its base class.
Statie Field
Syntax A field is said to be static whea its declaration is
preceded with static keyword. Static fields ar also called
private datatype variable_nane;
t static variables.
pivate datatype method_ name(args)

H ALLAR-ONE JouRNAL FOR


ENGINEERING STUDENTS SIA GROUP
JAVA PROGRAMMING (JNTU-HYDt.
1.44
Static member variable allows a common valuc to be uscd for the cntirc cluss, The properties of statie vatial
(i) The initial value that is assigned (at the first object creation) to the static member varinble is 0, No
further Ral.gwmens
allowed.
(ii) Single copy of it is shared among all the objects.
(i) It is local to the class in which it is
declared and remains active till the completion
of execution of the entire
Syntax progtan
n

static datatype variable_name;


Static Method
A method is said to be
static when its declaration
or definition is preccdcd with slatic
Static Member Functions koyword.
A static member function
is declared using the
(i) A static function can
keyword static and has the sollowing
access only the static characteristics,
(ii) members of its class.
Calling a static member
includes the name
of the class as hown below.
class_name::Static
functionname|
Syntax
static datatype method
name() {
Q64. How
classes can be nested? Explain.
Answer
Nested Class
A class which
can be defined in
another class is
(a) Static nested class called as nested class.
A nested class can
(b) be classified into
Non-static nested two types. They are,
class.
(a) Static Nested Class
A nested class
which can be
(b) declared as static
Non-static Nested is called as static
Class nested class.
A nested class
which cannot
be declared as
The nested class static is called
class. Whereas, can be called as a non-static nested
inner class can member class. It is also called
access of its outer class. The as inner class.
Syntax of Nested all the members static nested class cannot access
Class of outer class including private all the members outer
class OuterClass members. of

l/members
of outer class
class InnerClass

I members of inner
class

Example
class Outer

static int
stdld- 5;
static class Inner
UNIT-1 Objoct Oriented Thinking and Inthoritance 1.46
void innerMethod()

System.out.println("The inner method in statie nested class"):


System.out.println("Student's ld is:" stdld):

public static void nmain(Stringl ] args)

Outer.Inner innerObject new Outer.lunert ):

innerObject.innerMethod( ):

Q65. Explain in detail about inner classes.


Answer
Inner Class Onet
is known as the inner class. Inner class are
used inorder to hicde iUscll ir01
A class which is defined inside another class it is crealed. Inncr clisscs ure
object access the implementation of the object from which
classes of same package. An inner class can in the nncr cluss
outer class. It manipulates the objects of outer class as if it is crented
capable of inheriting the class members of the is used or implemented by Uic
ouler
implement interfaces. It doces not care if the object inheriting
itself. In addition to this it can also
class. It can also implement from multiple
sources.
features,
important and mostly used due to thc following
Inner classes are considered to be it separately witlhout the concern
of outer-
multiple instances each holding the state information of
An inner class contains
class object.
class object.
is not at all related vith the outer
The creation of inner class objeet in a unique way.
classes each of which inherits the iterface from the outer class
multiple inner
3. An outer class can contain
any "is-a" relationship.
an independent entity without maintaining
4. An inner class is

Example
class Outer

private int stdld = 5;

class Inner

public void
innerMethod()

class");
System.out.println("The method in inner
declared as private is:" stdld):
System.out.println("Student's ld which is

main(Stringl ] args)
public static void

Outer.Inner( );
Outer.Inner innerObject nev
=

innerObject.innerMethod( );

ENGINEERING STUDENTS SIA GROUP


ETRGM ALLHN-ONE JOURNAL FOR
PE
JAVA PROGRAMDMNG NAL0TDERA

string can be expiored


cenca
88 Elain bow

Syatar

e USe vt ckasses such s STng and SngButfer. Thy Saring coenn Saing s
are rebuadie snd pr ue nden murnd o that of ocher Q67. What are command line arguments? Hiou
they usefui?
Stung stUngNme
StringName oew instring Answer
A co nd-ine rgumt s de imtio pei
Srng stringNume = new Seingstring
Nple
lang
inngvrt java "

ciass Demw etbod Ša thy can be esaly accessed migarogran inm


the scring aTay
uec stat vUd mainSring args D
Empe
The following program accepts the cemmmd-ine
Srng Sl:
gmas and isplay the sane
Sew SngSa Group
Sering S-Tmpuners class cml ineArgs
Systemm out printin(S})E
Systet cutprinti S2)k pebic static void maiŠTg p D

Methods of String Clas Sy saem.cupritnThe commnd ne


Some of the methods of string cla rsföloas
ength() for( int c = 0. crgsk
This method is usad to know the length of the
string Sysem.ounrini esi:
Syntar
untlengtht)
equals)
Thzs method is used to compare wo strings for equality Output
Syatar
The commnd line arguments a
bodean cquals( String obj)
hello
charAtint index)
This method is used to extract the character 2
fron thee
Speciied index in the string.
all
Syntai
of
char charAt( int index)
stringt )
This method is used to initialize an In the aOve program the sing aTay Ts
objert uith speciiod *
characterS characters. command line angumeni It can be any void nam
Syntai argument passed at command line are stored as s
Stringtchar{ ] data) manipulate numeric values they must be coavei
String (Strng str) ntermal torms tor erample strings must e conver
uStng static method parselnt ) of an ahstract cls i
Look for the SlA GROUP LOGO on the TITLE COVER before you buy
INIT-1 Object Oriented Thinking and Inheritance 1.47
O68, Explain about variable length arguments in
Java. 1.1.13 String Handling

Answerr: Q69. Discuss about string handling functions.


Variable Length Arguments Model Paperd, Q3(b)
Answcr:
The method that accepts the variable number of
String lHandling Methods
arguments is called varargs methods. The variable-length
by
anguments are in short calcd as varargs. Tey are not used The mostcomonly used string methods provided
frequently in Java. For example, consider a method to open
Java are discussed below,
an internet conneclion.
It ight accept argunnents ike name.
String( ): This method is uscd to create a string object.
nassword, filenanme. protocol etc. This method supplies default 1.

data if any of the arguments are not provided. Then would be


it
length(str): This method is used to returm the length of
better to pass arguments for which delault does not apply.
the given string.
Variable-length arguments can be handled in two ways is used to This nmethod
One way is overloaded versions of a method can be created for
3. charAt() (int location_inder):
specificd location.
every method call il maximum number of arguments are small return the character present at the
and known. But, this can only be applied to very less situations. This method
subStringtint startindex, int endinde):
The second way is to gather the arguments into array and then at startindex and
is uscd to retum the substring starting
pass this array to a method. ending at endindeN in a string.
Example
endswith(String string_to_mateh): This method
is

with
class VarArguments LIscd to determine if the end of the string matches
string to mateh.
InderOf(String substring):This method is used
static void Test(int ...x) to
b.
return the index of the tirst occurrence of
the substring
+x.length);
System.out. print("Arguments:" in the string.
for(int i: x) replace(char originalchar. char replacementçhar):
System.out.prin(i+* "); This method is used to replace the originalchar witlh the
replacemcntchar in the string.
System.out.println(O:
S. Coneat(Siring sir): This metod is used to append one
public static void main(String args)D string at the end of the another string.

9. tol.owerCase( : This method is used to convert the


VarArguments(5): string to lower eise.
VarArguments(6, 7. 8); 10. toUpperCuse( ): This metlod is uscd to convert the
VarArguments( ): string to uppercasc.
11. trim This method is uscd to remove the leading and
):
trailng spaces.
is operated as
an array.
ne- above progrum, x in Test) variable length arguments 12. compare'To(String string_to_mateh): This method is
Specily to compiler that tlhe used to compare the given two strings.
will
uscd. They wvill be stored in c. n
main method
)

Te arguments. he T

is called with various number of 13. append(String This metlod is used to append the
str):
method
Euinents are gathercd in x automaticaIy given string at the cnd of string buffer.
Restrictions
in Varargs 14. deletetint start, int end): This method is used to delete
be used with
a parameters are also allowed to declared at the string sturting at start and ending at end in the string.
length parameters, but it
should be
nable
last. 15. insertint ollset, Striug str): This method is
used to
to declare a normal
parameter alter varares insert the string into the string bufler.
npling
is illegal. 16. reversel ): This nt lod is used to reverse tlhe string in
varags parameter is allowed an artay string bufler
ne
y ambiguity raises in overloadin
in
a method
17.equals ): This niethod is used
accepting varargs then it tucr o use dillerent mcinou
to compare two strings
fvr equality
anes
sVEC
O ALLIN-ONE JouRNAL FOR ENGINEERING STUDENTS -SIA GROUP
oxamplos,
1.48 tunctlons wltlh Nov/De017(01)
comparison
Explaln string methodu ta dinouwwned here.
Q70. Nulbstga, Thexo
compare stpings or
to
Answer
provides seveal methods
TheString class casO-sCnnitive mcihod
thod in
i.c., upper cave
cqunlslgnoreCase() cquals( )IN 0
nethe0xd,
equnls and cqtals( )
quality' using
companvd tor
A.
Two strings are not cqual to
case letters c.g. a is
not equal to lower

General Form
equals(Object str) invoking String
object. il reliurna
true ifboth the.strings areq
boolcan
to be
compared with the
String object
Here,'str is the
1.C, l Considers A-Z lo he
false otherwise. strings by ignoring lhe cusc
and conmpares the tuwo
cqualslgnoreC'ase( ) method
The

General Form
cqualslgnoreCase(String str)
boolcan
returns falsc.
if two strings are cqual else
It returns tnie
regionMatehes()
with another region of another string.
to compare a
region of a string
This method is used
are,
this method. They
There are two forms of str2Startlndex, int niumChars)
regionMatches(int startlndex, String str2, int
boolean int numChars)
regionAMatchestboolean ignoreCase, int
Startindex, String str2, int Str2Startlndex,
boolean specifics the Strin
region for invoking objcct begins 'str2'
In both the forms
'startlndes' specifies index at which the 'numChars' specifies the
compared and the starting region lor this object is specified by 'str2Startlndex'.
objoct which is deing
length of the suhstring to be
compared.
case-scnsitive, it is specified
The first form compares two string with casc-sensitive and the second form compares without
USing ignoreCase'.

3. startsWith() and endsWith()


argumen
These two methods are used to determine whether the given string starts with or ends with the string passed as an
Both of these returns true if the string nmatches and false otherwise.

General Form
boolean startsWith(String str)

boolean starts With(String str, int startlndex)

boolean endsWith(String str)

Here, 'str'is the string being tested. The starts With() method has two forms. The second form also specifies the postl
no
the string from which to start comparing
the string.
Example
Football.endsWith 'all"):

Foothall.startsWith"Foot");
Football.startsWith"all", 5):
All of these return true.
4 compareTof)
method is uscd to determine whether the string is less than,
equal to or
greater than the invoking string
Astrng less than another string it comes
is
if before the other in alphabetical order. And a stringISis greater than anothe
grealer tna
string if it comes after the
other in alphabetical order.

**Look for the SIA GROUP LOGo on the TITLE COVER before you buy
UNIT-1 ObJect Orlonted Thinking and 1,49
Inheritanca
General Form
int compareTo(String str)

Here, 'str' Is the string being compared with another sirine. l reluns he vnlues us surwn hetnn
Value Mennlg
I,ess than zero II means invoking string is Jess than slr,
Greater than zero It means invokimg string is wear tluan str,
Zero It means both the strings are eual,

The two String objccts can ulso be conmpured using=operalor, Jl determines vmetsr the 1n striny okijota reler ni tis
same instance.

Example
Following is an example program that shows the use of these methods for slring comparis1

public class CompareStrings

public static void main(String args[ )

String = new String("hello");


String s2= new String("world");
String s3
=
new String("How Arc You'");
String s4 new String("how are you");
System.out.println("string sl =" +s);

ifs1.cquals("hello"))
System.out.println("Both are cqual");

else
System.out.println("They arc not equal")

ifs1"hcllo")
System.out.println("Both are cqual");

else
Systen.out.println"They are not cqual"):
ifls3.cqualslgnoreCasets4))
System.oul.println("s3 cquals s4");

clse
System.out.println"s3 is no equal to s4");
System.oul.printn"The returned value js"*sl cmpareTds2),
+52.comnpare Tols1)
System.out.println"The valuc is:"

ALLIN-OME JOURHAL FOR EMaiNEERIN


STUDEMT SAAGROUP
RaM
1.50 JAVA PROGRAMMING JNTU-HYDERABA

1.2 INHERITANCE
1.2.1 Inhoritanco Concopt, Inheritanco Baslcs, Member Accoas
a71. Define inheritance. Write about superclass and subclass. Model Papera,
OR
a
What is inheritance and how does it help to create new classos quickly?
Answer ApMay1R14,
Inheritance
Inheritance can be defined as a mecchanism where in one class inherits the features of another class. The clas s
acquires the fecatures is called the child class or derived class and the class whose features are acquired is calied parem ch
or base class. The parent class contains only its own fecatures, where as the child class contains the features of both parem
child classes. Morcover, an object created for parent class can access only parent class members. Howea, child clas object cæ
access members of both child class and as well as parent class. The child elass can acquire the properties of parent class ung e
keyword 'extends
User can create the new classes by using the existing classes. In a new class, the mecthods and members can be inberied
from existing classes. The user can add sone cxtra members or methods in a new class. Thus, in this way the new can be crened
quickly.
SuperClass
Superelass is a class from which another class is inherited. It is also called as 'superclass' or 'pareni class'. A bese ci
does not have knowledge about its subclasses.
Sub Class
Subclass is a class that is inherited from a base clas. It contains additional members apart from having hase class memben
It is also called 'subclass' or a 'child class.

Member 1

Member 2
Member 3 Base class

Membetn

Member
1
Membe 2
Member 3 Derived cla

Member 4

Member
The rules that are to be followed while
using super class and subclasses are as follows,
1. The subclasses are restricted to directly
access the private members of its superclass.
2. The subclasses are allowed to access only the public
membcrs of its superclass.
3. The subclasses contain either additional data or additional
members or both of them.
4 The subclasses are capable of overriding the methods
of superclass which are publicly
defined.
S. The data member defined in superclass can also be used
in subclasses.
O. The methods defined in superclass can also be used in subclasses
if they are not overridden.
Look for the SIA GROUP LOGO 2 on the TITLE COVER before you buy
UNIT-1 Objoct Orientod Thinking
and Inhoritanco
1.51
Example
class Student

String sname "John":


int sid-*20":

class studentdetails cxtends Student

display)

System.out.println("Name:" +sname + "studentid" + sid);

class Demo

public static void main(String argsl D

studentdetails s-new studentdetails( ):

s.display:

spociflers used in Java.


Q72. Discuss in brief about the different member access
Answer :
For answer refer Unit-1, Q62.
a subclass object?
Q73. How a superclass variable can reference
Answer:
can be assigned a relerence to any subclass derived from that superclass. This asnect of
A reference variable ofa superclass consider the lollowing program. In this, 'weightbox is reference t
inheritance is very useful in different situations. For example,
is reference to "Box' objects because 'Box weight' is a subclass of 'Box', it is permissible to
Box Weight' obiects, and 'plainbox' type of referenee
Weight" object. we must Keep one imporlant point in mind that is the
it
assign 'plainbox' a reference to the 'Box reference ta a cahel
can be accessed and not une type or bjecis whch il refers to. When a
variable which determines what members
reference variable, we Will have access only to those parts of the object defined h a ubclass
object is assigned to a superclass
class Refer

argsl })
public static void main(String
Box Weight(2,4,5, 7.37);
BoxWeight weightbox = new
Boxplainbox = new Box( ):
double vol;
);
vol weightbox.volume(
System.out.println("Weightbox's volume is" + vol);
weightbox.weight);
System.out.printin("Weightbox's weight is" +
System.out.println( ):
plainbox weightbox;
volplainbox.volume();
System.out.println("Plainbox's volume is" + vol);

ENGINEERIHO STUDENTS
2
RaM ALAN oNE JOURNAL FOR SIAGROUP
1.52 JAVA PROGRAMMING IJNTU-HYDERAn.
ABADI
Q75. Explain the different types of constructe
ructors
1.2.2 Constructors Java. In
a74. Explain about constructors with an example OR
program. Define constructor. Explain about
bout paramoterizeg
parametr
OR Constructors..
What is a constructor? What are its special (Refer Only Topics: Constructor. Parameter
properties? Constructor)
terized
(Refer Only Topics: Constructor, Properties) Nov/Dec.17(R13).
Answer:
Answer: Nov/Dec..16(R13), 02(b) Q2
Constructor Constructor
A constructor is a special member function that gets For answer refer Unit-1, Q74, Topic: Constructor.
executed on the object creation automatically. There are two different types ol constructors in java
Need for Constructors 1. Default constructor
A constructor is a special function that is needed to avoid 2. Parameterized constructor.
unexpected results caused by un-initialized variables. Generally, 1. Default Constructor
variables must be initialized before they are used for processing
because, uninitialized variables typically contain garbage values A constructor that does not take any argument is known
The constructor for the class gets automatically invoked every as default constructor. If no constructor is specified thena
default constructor is called automatically. It does not accept
time a new object is created.
Properties any argument.
Constructors are used to initialize objects ofits class and Example
allocate suitable memory space to objects class employee_id
They take the same name of the class to which they
belong employeeid( ) uods
They doesn't have return type and void, so it cannot taid t
retun any values.
for
4. The execution of constructor take place when an object System.out.println("Desault constructor
is declared class is crealed");
5. Even on implicit execution of constructors they can be
called explicitly. public static void main(String argsl )
They are not virtual
7. They are usually declared in the public section.
employee_id E = new employee_id( )%

Every class has constructor. It does not have any explicit


return type. Java provides a default constructor for every
class. When the proyrammer defines a constructor, the default
constructor will not be used. 2. Parameterized Constructor
Example Aconstructor that takes arguments as its param Iers
class A IS knowm as parameterized
constructor. It is used to im
ilialize

the elements that takes different values. ae


Whenever o0 in
int i declared then their initial values are passed as arguine
AO constructor function. This can be done using the followile
methods.
i2, (a) Explicit constructor calling
(b) Implicit constructor calling.
Example
class Demo
class A
public static void main(Stringl ]
args)
int i

Aa new A(): A(int x)


Ab ncw A);
System.out.printlna.i +" "
+ b.i); i
X;

6Look for the SIA GROUP LOGO on the TITLE COVER before you buy
1.53
UNIT-1 Object Oriented Thinking and Inheritance
class Demo Hierarchy, Super
1.2.3 Creating Multilevel Inheritance
Uses, Using Final with
publicstatic void main(String[] args) inheritance
Q77. Explain about multilevel

Aa = new A(20); Answer:


Ab new A(30); Multilevel Inheritance
another derived
a class from
System.out.println(a.i +** + b.i). The process of deriving inheritance,
inheritance. In this type of
class is called multilevel other derived
a derived class can act as the base class for some
class.
Q76. Is it possible to define constructors and Baseclass
destructors in base class and derived class. If
yes, illustrate it with an example. Intermcdiate
(Derived class1) clasSS
Answer: base
The base class as well as derived class can contain
constructors and destructors. Derived class2)
The constructor belonging to the base class is executed
is Figure: Multilevel Inheritance
first and then the constructor belonging to derived class
executed. But the destructors are executed in the reverse Syntax
order. The destructor of the derived class will be executed class A
means the
first followed by the base class destructor. This
executed
constructors are executed the order in which they are
and the destructors are executed in the
reverse order of their
applied even for multiple class B extends classA
20814
derivation. The same thing will be
inheritance.
Example
class X class C extends classB

XO
System.out.println("X's constructor"); Example
class Student
4
String sname=John"; |
class Y extends X
int sid = "101":

YO
class Department extends Student
System.out.println(*"Y's constructor");
String dept = "IT";

class Demo mclass Marks extends Department


J) m
(Siring argsl
public static void main intsubl, sub2, sub3;
subl = 50;
Yy new YO;
sub2 80;
sub3 40;

Output void total()


X's constructor
Y's constructor int total =
subl + sub2 + sub3
constructors gel executed in
In the above program the
the order of derivation.
ENGINEERING STUDENTS SIA GROUP
PETRUM ALL-IN-ONE JOURNAL FOR 2
JAVA PROGRAMMING IJNTU-HYDERA
ERABAD
.54
wd dispdayt) double volume()

stem.t.prntln" stuxient name:" +sname + return width *


height "
depth;
n stnadent " sid+ "Deprtment" + dept
"unarks of sudjortl"*subl"Marks
of subjart"* suh?"Marks of subject3
+suds); class B extends A

double weight;
class Multilevel B(double ,
double h, double d, double m)

pudlic static void main(Strings args[ })


super(w, h, d); // calls superclass constructor
weight = m;
Marks m = new Marks( ):
m.total( )k

m.display):
class FirstUse

public static void main(String args[)


T8. Define the variable 'super' and its uses with an
example. Nov/Dec.-16(R13). Q5(a)
OR Bb new B(20.5, 10.2, 15.1, 50.6);
Describeuses of super keyword in inheritance. System.out.println("volume is:" +b.volume( );
nswer : Nov Dec.17(R13), Q4(b)
per"
super is a keyword used by subclass to refer to its Output
amediste superclass. volume is: 3157.41
Ses
Here, class B calls super() with w, h andd parameter
There are two uses of 'super' keyword This causes the class A constructor to be called where the valu
It is used to call the superclass constructor. ofwidth, height and depth are initialized using these values,
(u) it is used to access a member of a superclass. makes the class A to declare its variables private if desired
super Keyword to Call Superclass Constructor (i) 'super' to Access Members
mbers
A subclass can call the constructor of superclass by using The 'super' keyword can be used to access the m
an
oe
following form of "super". of a superclass, where members can either be a men or
llowing
instance variable. To access the
supertparameter-list): members it has the 10
general form,
Here, parameter-list are parameters needed by the
perclass constructot. super.member
exCeP
The call to the 'superclass" constructor is made inside This 'super usage is some what similar to 'this',
he "subclass' constructor and hence the super( ) must always be that it always refers to the superclass.
e
eiow
first statement inside a 'subclass' constructor. The program
Llstrates the useof super() to call 'superclass' constructor.
This second usage is useful in
situationrClass
*
member names of subclass hides
Eiample the members ol Sup
Example
class A
class A
private double width, height, depth
ldouble w, double h, double d) int x

void show()
width w,
height h method
System.out.println("This is Superclass'
depth d:

Look for tho SIA GROUP LOGO 2 on the TITLE


COVER before you buy
UNIT-1 Objoat Orlontod Thinking and Inhoritanco 1.55
cluss B cxtcnds A
Exnmple
linal class Bascclass
int x; /hides x in A
B(int a, int b)
System.out.printn("Bascclass");
super.x x in A

xb; Ix in B
class Derivedclass cxtcnds Basçclass /crror

void show() bides show( ) in A


System.out.println("Derivedclass");

super.show( );

change in
System.out.println("This is subclass'method"); F'inal classes are used to present the
implementation resulted by subclassing. Since overriding
ol
System.out.printin("x in superclass " super.x)
is greatly
Systcm.out.println("x in subcluss" +

x); methods is not donc, performance of final classes


increased.

Final Method
is called final
class SecondUse The method which cannot be overridden
method. A final method can be created by proceeding the
is done
public static void main(String args[ ) method name with final keyword in its definition. This
to prevent it from being overridden. If these methods are tried
to be overridden the compiler generates an error.
Bb new B(10, 20);:
b.show ); "a Example
class Baseclass

Output 3 final void display()


This is superclass' nethod
This is subclass' method
x in superclass: 10 System.out.printin("Hello");
x in subclass: 20
the
n theabove program, B's constructor inilializes
keyword, where
ance variable x of superclass using super
upcr relers to superclass' instance variable. An object b of class class Derivedclass extends Baseclass
Dcalls its show( ) method, where a call to superclass show
hcthod is made using the super keyword as follows,

super.show) void display() /error


79. Explain about final class and mothods.
OR
System.out.println("Welcome");
Explain usago of flnal with Inhorltance.
Answer Nov./Doc.-17(R13), Q5(a)
Final Class

The
finale s which cannot be inheritcd or extended is called
class. A final class
can be created by procccding the cluss
Exccution of final method is ellicient
execution of non-final methods. This is because the
compared to the
th inal keyword in its definition. This is done to prevent compiler is
the being inherited. If these classes arc tried to be inherited already aware of thhe fact that a call to final method
then the will not be
compiler generates ecrTors, Declaring a cluss as final overridden by any other method. Moreover,
will the methods which
aulonatically declare its methods as linal. are private are considered to be final by default.
SPECTR
ALLIN-ONE oURMAL FOR ENGINEERING STUDENTS
SIA GROUP
1.56 JAVA PROGRAMMING IJNTU-HYDt
(DERABAD

(ii) Pure Polymorphism


1.2.4 Polymorphlsm Adhoc Polymorphism,
Pure Polymorphism Pure polymorphism contains only one

Q80. What is polymorphism? Explain different


different types of argumenis/paramelers. This is
typesoricnted programming. The code is flexible as it is
usen
obje
of polymorphism with examples.
one time and can be used in any situation. It supponsteno
AprilMay-18(R16), Q3(b) The flexibility can be achieved by forwarding the mlfactu
nes
OR receiver. The later messages that are received are n
with the class at higher level ol polymorphic method
How do we implement polymorphism in JAVA? deferred methods are used in lower classes.
Explain briefly.
The following is the example 1or pure polymorphism
Answer Nov./Dec.-18(R16), 03(a)
public class string
Polymorphism
Polymorphism is an important concept in OOP. It is
derived from the Greek word poly (multiple) and morphism public static string valueof(Object o)
(forms) which together mean muliple forms. It is a method
through which an operation/function can take several forms
based on the type of objects. An individual operator/function
if(o== NULL)
can be uscd in multiple ways. return "NULL";
Typeso f Polymorphism return o.toString( );
There are two types of polymorphism, they are,
(0) Adhoc polymorphism
(ii) Pure polymorphism. In the above example, the class string' is definedas tua
Adhoc Polymorphism contains the method valueOf ). It generates the output
object
textual description for an object o. Another class
is

Adhoc polymorphism is the concept in which diflerent subclasss


defined that has a method toString() used various used
in
functions have similar/same name. This is also referred as
to produce djstinct effects. For example, double
is tn

method overloading". uset


colour is
generate the textual representation of numbers
In Java several mcthods are allowed 1o be defined a in different colous
to represent the values of different strings
with same name. But they should differ in heir arguments
) willas
The method valueON
like red, yellow, green, blue. ony
and definitions. All these methods perform similar tasks with generate the different outputs, even though
it is defined
diflerent input parameters. This concept is called as method once.
overloading. When a method is called, the compiler will match witha Java progradm
the method name, number of arguments and their type. Based Q81. llustrate dynamic binding Nov./Dec.-16/R13), 0
on this it decides which method should be executed. Sometimes Answer
same definition is also allowed for different methods. The
following is the example for adhoc polymorphism. Dynamic Binding
call with is
class Method The processof connecting the function with sae
IS called binding. Ifthere
are various functions to whd
connu called
and same definition. "Then the compiler gets
void Sum int x, int y) Function to
Tunction to be called while execution.
determined only by the object. But object run
will be ee e
int res x+y;
at runtime. So, binding should be done
at
lat bindin
r dy

binding is called as runtime binding or


System.out.println("Sum:" + res);
binding.
Example
void Sum(double x, double y)
class Baseclass

double res x *
y
System.out.println(*Sum:"
void display()
+ res);:

System.out.println( Baseclass

In the above eramnple, the class method contains the


functiom sun( ) with diflerent argunents passed to i1.

Look for the SIA GROUP LOGO on the TITLE CoVER before yo
UNIT-Oe Onerned Tinking and inhertance 1.57
cinss Deedtrs
1.25 Method Overriding, Abstract Classes
Object Class
Explain.
E How a method can be overridden?
Answer:
SsaemutriinDervadless"t Mecbod Overriding
wbich a mehod
Mebod ovendng is a phenomeon in
The re
subciass is simitar to the ethod in superclass wih tbe
p ad signtre of a ubciass method matcbesadvantzge
rec e nd simtre of sperciass echod Te
is t i prowides 2n mpienentin
whch is
o1 s ehd
This method can be used 1or
tcdisgiay ead roaded by its superclass method of subclass is called
r pohmapiism. hen the n
the superelass's method is not refered znd is hidden
Roies to be foliowed for mecbod overiding re
super ciass
QE2How does polymophism promote ertensibiity? Te agmns abeissaof subclas Dehod and
nethod
w
Epiain erample. The access modifer oísubcizss mehod mut not
resurinct

the sperelass mechod


NinDec-17(R16L 03a
Static and final nethods must not be ovemóen
Constructors and methods which cannot be inherited
The se rLvoks poly ghic behvir dos ax Cannot e overndden
S. Instance echods that are inherited by the subclass can
The tjt opes dr respnd to the exitg mebod calls e overnidden
cm te inchaied n de sysaeahout the need for base systen Eample
máicin The cien caie tht iniines the Dew objects nead ciass Baseclass

The poyphim concept maks more


the progTans void display)
cumsbie f a he ethod cells are made generic. Whn any
ciass npe s adied with astTacI mechd to the hierarchy, SystemouLprintln("Hello"):
h no chngs æ required to be made to the genenic cals
Usng the polymorphism, the user can design as well as
emene he sysiems which are easily extensible. The Dew class Derivedclass extends Baseclass
ciess can be adied wichout the need of modiñcation to the
gnn portions of the program when the new classes belong
voiddisplay)
beriance biererchy so that program processes geneTically
onlhy
The pars that direct the new classes knowiodge are System.out.println(*Welcome"
dod to be modified. Consider the below exampk,
cizss floaer
class Method
class Rose
public static void main(Stringl
] args)
Derivedclass de new
Derivedclass()
dedisplay():
a the above program, if class Flower is extended to
In the above program,
acias Rese, the user need to write only onc Rose class when the displayí)
called, only the derived class's
ith the sinulation part that instantiates the Rose object.
generated is "welcome. method is called and method is
In order to call the output
The parts of progran that indicate cvery Flower to move super keyword is used superclass's method
while calling the function
cally will remain the same. The class Rose will respond shown below. in main as
the move message by crawling one nch.
super.display( ):
ROKH ALLAN-ONE JOURNAL FOR ENINEERING STUDENTS
SIA he
1.68 JAVA PROGRAMMING JNTU-HYDERAA
RABAD
a84. Explaln the unage of abstract clansos and Q85. WIhat ia an objoct clasn?
Discuss ma
mothod. its methodh
Answer
OR
Object Class
Writo a Java program to nhow tho uno of
abstract classon. Objcct class is sail to be xUCT class
for all the
classes in Java. Al the classCs are said to be the
(Refer Onb Tople: Example) suhl
obiect class. Object class can be useel to refer an obicct
Answerr Nov /Doc.10(R13), Qs(b) (ype is not known a reference variable of type
objcct
Abstract Class and Abstrnct Method ercated to efer all the objects of other classes. Amavs cclau
Javn defincs nbstract classes methods using thc be implenented as elasses. In this case a variable Can
of tpe ak a
keyword "abstract", The class that docsn't have body is called is used to refer the other arrays. It defincs the follo ino
objeca
abstract class. Whereas the method that does not have body is object clonet ): This
niethod is used to create an ob
called abstract method. An abstract class can contain subelasscs with same leatures of the objeet that is clonod yect
in addition to abstract methods. If the method containing in the
subclasses does not ovcrride the methods of the baseclass then boolcan cquals(object ob): This method is
ussd
they will be considered as abstract classes. So, all thc subclass determinc if the object cqual to some other objou
is
must provide an implementation for all the base class's abstraet 3. vold finnlize( ): This method is called before an
methods. Abstract classes cannot be instantinted. ohint
that is not uscd is recycled.
A method is declarcd abstract when it has to be class<7>getclass( ): This method is used
overridden in its subclasses. For cxample, an abstract method to acces the
"Phone( " can he defined in "Network" class as there can be object's class at runtime.
various phones with various networks. IHence, cach subclass of 5 int hashcode( ): This nethod is used to return the hash
Network class can overide and implement the abstract method code of the object being invoked.
phone). The syntax forabstract class and method is as follows,
vold notify( ): This method is used to resume he
Syntax for Abstract Class execution ofthe thread that waiting on the object that is
abstract class classname{ being invoked.
Syntax for Abstract Method 7. void notifyAll): This method is used to resume t
abstract type methodname(argl, nrg2, -, argn): execution ofall the threads that are waiting on theobje
Exemple
abstract class Baseclass
. that is being invoked.
string toString( ): This method is used to retum the|
string that defines the object.
void wait( ), void wait(long milliseconds) and
abstract display( ):
void(wait long milliseconds, int nanoseconds): Thes
methods are used to impose wait on some othet thrcaN
class Derivcdclass extends Baseclass that is being cxecuted.

1.2.6 Forms of Inheritanco - Specialization


void display()
Specification, Construction, Extension
Limitation, Combination, Benefits of
System.out.println("Derivedclass"); Inheritance, Costs of Inheritance
Q86. What are the different forms of inheritan
Explain any two of them.
class Demo Answcr :
The various forms of inheritance are,
public static void main(String args[ }) 1.Specialization
2 Specification
Derived dc new Derivedclass(): 3. Construction
dcdisplayO: 4 Extension
5. Limitation
6. Combination.
Look for the SIA GROUP LOGO on the TITLE COVER before you buy
NIT-1
N Object Orient Thinking and Inheritance 1.59
Specialization actionPerformed(ActionEventev
public vojid
Inberitance is commonly uscdfor specinlization pur-
iere, a child class or a new class is a specialized form
pressed
class and conforms to all specifications of the
il NCUOns to be perfomed whenever a button is
fthe parent
"

Thus, a subtype Is creatcd using this form and the sub-


mainlaincd explicitly.
utability is also
The subclassification example lor specializntion is an ap-
eation window class crcalcd using inhertance. The following
wEmple class 'Mineswecperiame' inherits the 'Frame' class. (b) Using Extension
using extensions, subclas
public class MincSweeperGame extends Frame When the classes are inherited
Subclasses are createa
Sthcation for specification is achicved.
'new'keyword cannot be used
using the keyword 'abstract'. The from classes, the
class. Apart
to create instances ofan 'abstract' To create instances
'abstract'.
methods can also be declared as
above class 'Mine- overridden.
his Tequired to create an instance of the these methods will have to be
ueeperGame to run thc application. As this class extends the
Example
rane class, scveral methods
arc inlherited such as setTitle, setSize, defined in Java Library
and
These methods manipulate the "Number' is an abstract class
thow
etc., and can thus be invoked.
without knowing that has the following description.
astances
of the "MineSweeperGame'class
xy are not the instances of the 'Frame'
class. public abstract class Number
The methods defincd in the
child class will be cxecuted
y overriding the methods in the parent class when
application
intValue( ):
public abstract int
pecific task is to be performed.
Value( ):
public abstract long long
Specification
Value( );
Inheritance can also be uscd to allow
the classes to public abstract float float
samc names. The parent public abstract double
double Value();
mplement those methods that have the
without implementations.
lass can define operations with or par- public byte byte Value():
Ihe operation whose
implementation is not defincd in the parent
! class will be defincd in the
child class. Such kind of
is also called
as "abstract
zlass that defines abstract methods return (byte) int Valuc( );
pecificationclass"
specification, Java language
To support inheritance of
are, public short short Value( );
provides two diflerent techniques. They

(a) Using interfaces


Value( );
(b) Using extensions. return (short) int
a) Using Interfaces
characteristics of an Ac-
A method can describe the implementation, as
onListener without describing its ways must be overridden by
implement it in
diflerent The methods declared as abstract
ierent applicationsbe used to define only the require thesubclasses of this
class.
CTLaccs can thus
Explain the charactoristics of inheritance
behavior. for
Ticnts without defining the actual Q87.
Dterface Actionl.istener the following,
(a) Construction
actionPerformed(ActionlEvent c
pubilic void (b) Extension
(c) Limitation
defined cach time
whenevea
stener class will be define a particular behavior or (d) Combination.
s ctcaled. It will application.
io toethod as requircd by the Answer i
ciaus EenpareEarth cxtends Frame
(a)
Construction
child class can inherit most of the properties from its
A
Ciass Shnothuttonl.istener
implements do not have abstract concept
a Actionlistener parent class, cven il these clases
in common.

ECTRUM ENGINEERING STUDETS


SIA GROUP
JOURNAL FOR
LLA-ONE
JAVA PROGRAMMING (JNTU-HYDED
1.60 ABAD
The Java Library describes a vector class which can
be¢ public String getProperty(String key)
used to construct a stack' class using inheritance.
class Stack extends Vector

public Object push(Object item)


public Enumeration propertyNames();
addElement(item);
retum item; public void list(PrintStream outputs)

public boolean empty()


The parer class functionality is made available
return isEmpty( ); t
child class without any modifications. Thus, such classe
also the subtypes because the subclassification for exteni
ensa
public synchronized Object pop() also supports the substitutability principle.
(c) Limitation
Object ob peck( ):
if a subclass restricts few behaviors to be used that
=

removeElementAT(size()-1); nhe cd from he parent class, then the subclassification


return ob; limitation occurs.
Example
public synchronized Object pcek()
A set class can be created from vector class. Ifonly the se
operations must be used on a set and with no vector operatia
retum ElementAT(size() -1); then this restriction leads to subclassification for limitation. To
implement this limitation, those methods should be overriden
or a message should be printed denoting that they should na
Though, the vector concept and stack concept does not be used. Alternatively, an exception can also be thrown wbe
have much similarity, the vector class is made the the undesired methods are used, but the Java compiler does oa
parent of permit to do so.
stack class as it makes the stack implementation more easier.
(b) Extension class Set extends Vector
The subclassification for extension is achieved ifa child
class adds an additional behavior to the parent
class without I Methods inherited from vector are,
modifying the attributes that are inherited from that
parent class. addElement, removeElement, isEmpty, su
Example
The "Properties' class defined in Java
public int indexOf(Object ob)
library inherits
Hashtable' class. The Hashtable class helps
in storing and retrieving
the properties class
relevant property name or value pairs. System.out.println("Do not use set indexOI)%
t also helps in property management, for example, in
froperties from a file or writing reading retum (0);
properties to a file.
class Properties extends
Hashtable
public Object ElementAT(int
index)
public synchronized
void load(InputStream ins)
return null;
throws 10Exception

public synchronized
Subclassification for limitation
must be
avoidedas itd
void savetOutputStream not obey the substitutnbility DC
avob
outs, build by it are not subtypes. principle and also
String header)
(d Combination
Java language docs inheit
not allow assubclass to
than one class. Thus,

LOok for the


solution for this problem
parent class and implement
any number of inic e.
SIA GROUP LOGO
on the TITLE cOVER
before you buy
UNIT-1 Object Oriented Thinking and Inheritance 1.61
portable than tne
Example The code at the lower-level is more
lower-levels can be uSea
class Holc extends Ball implements PinBallTarget code at higher-level. The routines at higher-level are very
n several applications but the routines at
closely tied to a specific application
that are reus-
In order to produce. igh-level components
The above example implements only one interface, but applications by changing
able and can be used with different
multiple interlaces can also be implemented. For example, |
RandomAccessFile implements two interlaces, they areprogramming languages.
iust the low-level routines, polymorphism is employea na
Datalnput and DataOutput protocols. framework is Java AWT
An example of such a large software
substitutability and inheritance
Q88. What are the benefits of inheritance? hat performs its operations based on
Answer Model Paper-il, 03(b) 7. Information Hiding
reused by a pro-
The benefits of inheritance are as follows, When a software component is being
and nature
. grammer, he needs to understand only the interface
Increased Reliability for him to know about the
of that component. There is no need used by
ifa code is frequently executed then it will have very implementation of that component or the techniques several
nature between
less amount of bugs, compared to code that is not frequently ex- that component. Thus, the interconnected
ecuted. When applications have same components within them, is reduced thereby reducing the complexity
software systems
then the code excrcised is more compared to code of a single of software.
application. It is very easy to find the bugs present in this kind Rapid Prototyping
8.
ofcode. Thus, the applications that use this component are more
When most of the components that are used
in building
costs required
error free. In addition to that the inmaintaining or interfaces then
projects. a software are inherited from the parent class
the shared components can be divided among muliple coding. Thus, the
only small amount ofsystem requires actual and
2. Software Reusability software systems are cònstructed very easily and
quickly
as Exploratory Programming
Properties of a parent class can be inherited by a child this kind of programming known
is
class. But, it does not require to rewrite the code of the inherited or Rapid Programming
property in the child class. For instance, searching of a string Q89. What are some of the costs of using inheritance
pattern, insertion ofa new element into an existing table, etc., for software development?
fromn
are used in several applications and can thus be inherited
Answer:
one single class. Thus, using object- oriented programming
Following are the costs of object oriented programming
methods can be written once but can be reused.
techniques or more particularly, the costs of inheritance.
3. Code Sharing Program Size
can
There are different levels in which code sharing If the cost of memory decreases, then the program size
Occur using object-oriented techniques. Al one
level of code
use a single class. II a does not matter. Instead of limiting the program sizes,
Sharing multiple projects or users can
that are inherited there is a need to produce code rapidly that has high
Sngie project contains more than one class quality and is also error-free
rom the same parent class, then this is also said to be one leve
ol code sharing. In this level of code sharing, there exist iew (ii) Execution Speed
This kind of
object types that share the code that is inherited. The specialized code is much faster than the inherited
COde is written once and is used in several applications. methods that manage the random subclasses.
4. Software Components The efliciency ofa system must not be considered in the
are carly stages. Instead, when that system is developed, it
PTogrammers can construct software components that
Teusable using inheritance. The goal of inheritance is allowing8 should be monitored to find out where the execution
or no time is more and then that part should be improved.
eW applications to be developed that requires very little
components
ing at all. There is a huge collection of software (iii) Program Complexity
delined in Java library that helps in application development. Complexity ofa program may be increased if inheritance
5. is overused. To understand the program's
Consistency of Interface control flow,
When multiple classes inherit the behavior of single
a the inheritance graph will have to be scanned several
all those classes will now have the same behavior. times, up and down, which will lead to a problem
Class
nus, objects that are similar have similar interfaces, as well and as yo-yo problem.
known

CT Cannot be confused as all of them have same behavior.


6
(iv) Message-Passing Overhead
Polymorphism and Frameworks Although, passing of messages is more
procedure invocation, the cost of message
costlier than
raditionally, softwares produced werc written bottom passing is very
mcchanism. That is lower abstractions were placed it the less when execution speed is considered. This
increased
Tl nCreasing gradually und the higher abstractions were cost is negligible when compared to the
benefits provided
placed at the by object-oriented programming technique.
top.
SPECTR
ALL-IN-ONE JOuRNAL FOR ENGINEERING STUDENTS
SIA GROUP
2

You might also like