Java Unit 1 Spectrum
Java Unit 1 Spectrum
Java Unit 1 Spectrum
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.
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
class'Derivedclass
extends Baseclass
class subclass extends Single
void display()
subclass()
System.out.printnC°Derivedelass"):
fr str.coneai"World");
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
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.
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.
Current System
--
Execution Native
cngme ethod |-Undetly mg
nterface
Figure: Architecturo of JVM
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.
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;
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
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);
Syntax
boolean variable_name;
Example
boolean a;
a true,
of
a false
Progam
clase BooleanExample
boolean n,
int x, y, 7
10
y2 20,
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
int a;
a - 20;
ifa==20)
int c= 30;
System.out.println("The values of a and c are:" +a+""+c);
a=cta,
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
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);
Example
Consider an example program of converting long to double which can be performed automatically.
class TypeCastExample
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
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;
2. Two-dimensional array
3 Multi-dimensional array.
STUDENTS
ECIRUM ALIN-ONE JOURNAL FOR ENGINEERING SIA GROUP
JAVA PROGRAMMING JNTU-HYDERAb
.22 ABADI
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
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].. .
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
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
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.
int a. b,e:
a S:
b 6;
c a+b;
System.out.println("Addition ofa, b:" +
c);
sa-b;
System.out.println("Subtraction of a, b:" + c);
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);
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
nt
oulean as
System.out printin( * %
ifx )
System.outprinttni"x less than or aqual to 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
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
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
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
>>>
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.
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
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
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
StatcIment-nex
ifcondition-1) int a, b, C
a=7
b 8:
ifcondition-2) c 9;
if(a> b)
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;
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.
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)
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)
Body of Loop
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
True System.out.println(x):
Body of Loop
I 10;
for(a = 0; a<x; a +)
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)
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
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[ })
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.
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 )
md area(Square sq)
ob2-ob2.incv );
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
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)
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()
innerObject.innerMethod( ):
Example
class Outer
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( );
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 "
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.
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'.
General Form
boolean startsWith(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
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:"
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
display)
class Demo
s.display:
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( )%
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
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";
double weight;
class Multilevel B(double ,
double h, double d, double m)
m.display):
class FirstUse
void show()
width w,
height h method
System.out.println("This is Superclass'
depth d:
xb; Ix in B
class Derivedclass cxtcnds Basçclass /crror
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" +
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
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
double res x *
y
System.out.println(*Sum:"
void display()
+ res);:
System.out.println( Baseclass
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
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,