0 ratings0% found this document useful (0 votes) 80 views150 pagesOop in Java Note
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
OOP in Java BCA
THIRD
AYA) SEMESTER
Mechi Multiple Campus
Bhadrapur
Notes Prepared By
Cyl m aoe}
MCA, Purbanchal UniversityUni
Introduction to Java [2 Hr:
Java is an object-oriented, cross platform, multi-purpose programming language produced
by Sun Microsystems. It is 2 combination of features of C and C++ with some essential
additional concepts. Java is well suited for both standalone and web application
development and is designed to provide solutions to most of the problems faced by users of
the internet era.
It was originally designed for developing programs for set-top boxes and handheld devices,
but later became a popular choice for creating web applications.
The Java syntax is similar to C++, but is strictly an object-oriented programming language.
For example, most Java programs contain classes, which are used to define objects, and
methods, which are assigned to individual classes. Java is also known for being stricter than
C++, meaning variables and functions must be explicitly defined. This means Java source
code may produce errors or "exceptions" more easily than other languages, but it also limits
other types of errors that may be caused by undefined variables or unassigned types.
Unlike Windows executables (.EXE files) or Macintosh applications (. APP files), Java
programs are not run directly by the operating system. Instead, Java programs are
interpreted by the Java Virtual Machine, or JVM, which runs on multiple platforms. This
means all Java programs are multiplatform and can run on different platforms, including
Macintosh, Windows, and Unix computers. However, the JVM must be installed for lava
applications or applets to run at all. Fortunately, the JVM is included as part of the Java
Runtime Environment (JRE.
Oracle acquired Sun Microsystems in January, 2010. Therefore, Java is now maintained and
distributed by Oracle.
Features of Java
a) Object-Oriented - Java supports the features of object-oriented programming. Its
object model is simple and easy to expand.
b) Platform independent - C and C++ are platform dependency languages hence the
application programs written in one Operating system cannot run in any other
Operating system, but in platform independence language like Java application
programs written in one Operating system can able to run on any Operating system.
c) Simple - Java has included many features of C / C ++, which makes it easy to
understand.
d) Secure - Java provides a wide range of protection from viruses and malicious
programs. It ensures that there will be no damage and no security will be broken.
e) Portable - Java provides us the concept of portability. Running the same program
with Java on different platforms is possible.
f) Robust - During the development of the program, it helps us to find possible
mistakes as soon as possible.
) Multi-threaded - The multithreading programming feature in Java allows you to
write a program that performs several different tasks simultaneously.
Prepared by: Raju Poudel [MCA] 2h) Distributed - Java is designed for distributed Intemet environments as it manages
the TCP/IP protocol.
The most striking feature of the language is that it is a platform-neutral language. Java is the
first programming language that is not tied to any particular hardware or operating system.
Programs developed in Java can be executed anywhere on any stream. We can call Java as a
revolutionary technology because it has brought in a fundamental shift in how we develop
and use programs. Nothing like this has happened to the software industry before.
History of Java
Java is a general-purpose, object-oriented programming language developed by Sun
Microsystems of USA in 1991. Originally called Oak by James Gosling, one of the inventors
of the language, Java was designed for the development of software for consumer
electronic devices like TVs, VCRs and such other electronic machines. The goal had a strong
impact on the development team to make the language simple, portable and highly reliable.
The Java team which included Patrick Naughton discovered that the existing languages like
C and C++ had limitations in terms of both reliability and portability. However, they
modelled their new language Java on C and C++ but removed a number of features of C and
C++ that were considered as sources of problems and thus made Java a really simple,
reliable, portable and powerful language.
Java Milestones
Year Development
1990 Sun Microsystems decided to develop special software that could be used to manipulate consumer
(greater than) | Checks if the value of left operand is greater than the [(A > 6) is
value of right operand, if yes then condition becomes true. | not true.
< (less than) Checks if the value of left operand is less than the value of |(A < 6) is
right operand, if yes then condition becomes true. true.
>= (greater than | Checks if the value of left operand is greater than or equal | (A >= B) is
or equal to) to the value of right operand, if yes then condition | not true.
becomes true.
<= (less than or | Checks if the value of left operand is less than or equal to | (A <= B) is
equal to) the value of right operand, if yes then condition becomes | true.
true.
itwise Operators
Java defines several bitwise operators, which can be applied to the integer types, long, int,
short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b =
13; now in binary format they will be as follows ~
a=0011 1100
b =0000 1101
a&b = 0000 1100
a|b= 00111101
ab = 00110001
a = 11000011
The following table lists the bitwise operators.
‘Assume integer variable A holds 60 and variable B holds 13 then —
Operator Description Example
& (bitwise and) Binary AND Operator copies a bit to the result if it | (A & B) will give 12
exists in both operands. which is 0000 1100
| (bitwise or) Binary OR Operator copies a bit ifit exists in either | (A | B) will give 61
operand, which is 0011 1101
Prepared by: Raju Poudel [MCA] 12* (bitwise XOR) Binary XOR Operator copies the bit if it is set in ] (A * B) will give 49
one operand but not both: which is 0011 0001
~ (bitwise | Binary Ones Complement Operator is unary and | (~A ) will give -61
compliment) has the effect of ‘flipping’ bits. which is 1100 0011
in 2's complement
form due to a
signed binary
number.
<< (left shift) Binary Left Shift Operator. The left operands value | A << 2 will give 240
is moved left by the number of bits specified by | which is 1111 0000
the right operand.
>> (right shift) Binary Right Shift Operator. The left operands | A >> 2 will give 15
value is moved right by the number of bits | whichis 1111
specified by the right operand.
>>> (zero fill right | Shift right zero fill operator. The left operands | A >>>2 will give 15
shift) value is moved right by the number of bits | whichis 00001111
specified by the right operand and shifted values
are filled up with zeros.
Logical Operators
The following table lists the logical operators.
Assume Boolean Variables A holds true and variable B holds false, then —
Operator Description Example
&& (logicaland) | Called Logical AND operator. if both the operands | (A && B) is false
are non-zero, then the condition becomes true.
TT (logical or) Called Logical OR Operator. If any of the two | (A|| B)istrue
operands are non-zero, then the condition
becomes true.
1 (logical not) Called Logical NOT Operator. Use to reverses the | (A && B)is true
logical state of its operand. If a condition is true
then Logical NOT operator will make false.
Assignment Operators
Following are the assignment operators supported by Java language —
Operator _| Description Example
= Simple assignment operator. Assigns values from right side operands | C= A+B will
to left side operand. assign value
of A+B into
c
‘Add AND assignment operator. it adds right operand to the left|C += A is
operand and assign the result to left operand. equivalent
toC=C+A
Subtract AND assignment operator. It subtracts right operand fromthe |C -= A is
left operand and assign the result to left operand. equivalent
toC=C~A
Prepared by: Raju Poudel [MCA] 13* Multiply AND assignment operator. It multiplies right operand with the |C *= A is
left operand and assign the result to left operand. equivalent
toC=C*A
Divide AND assignment operator. It divides left operand with the right |C /= A is
operand and assign the result to left operand. equivalent
toC=C/A
Modulus AND assignment operator. It takes modulus using two |C %= A is
operands and assign the result to left operand. equivalent
toC=C%A
<= Left shift AND assignment operator. C= 2is
same as C =
cec2
>= Right shift AND assignment operator. C352 2 is
same as C =
Bitwise AND assignment operator. 2 is
same as C =
C&2
bitwise exclusive OR and assignment operator. C= 21s
same as C =
cr2
= bitwise inclusive OR and assignment operator. c i= 2 is
same as C =
c\2
Conditional Operator
Conditional operator is also known as the ternary operator. This operator consists of three
‘operands and is used to evaluate Boolean expressions. The goal of the operator is to decide,
which value should be assigned to the variable. The operator is written as —
variable x = (expression) ? value if true : value if false
Following is an example —
public class Test {
public static void main(string args[]) {
int a, bs
1) ? 20: 305
System.out.printIn( "Value of bis: "+ bs,
Output
b= (a == 18) ? 29: 30;
System.out.println( "Value of bis: "+63 Veiue of v is : 30
} Velue of b is : 20
Prepared by: Raju Poudel [MCA] 14Control Statements
A programming language uses control statements to cause the flow of execution to advance
and branch based on changes to the state of a program. Java’s program control statements
can be put into the following categories: selection, iteration, and jump.
= Selection statements allow your program to choose different paths of execution
based upon the outcome of an expression or the state of a variable.
- Iteration statements enable program execution to repeat one or more statements
(that is, iteration statements form loops).
- Jump statements allow your program to execute in a nonlinear fashion.
Java’s Selection Statements
Java supports two selection statements: if and switch. These statements allow you to
control the flow of your program's execution based upon conditions known only during run
time.
if
The if statement is Java’s conditional branch statement. it can be used to route program
execution through two different paths. Here is the general form of theif statement:
if (condition) statement1;
else statement2;
The if works like this: If the condition is true, then statement is executed. Otherwise,
statement2 (if it exists) is executed. In no case will both statements be executed. For
example, consider the following:
int a, by
Wee
ifla 100) © = a:
else a=;
)
else a= 4; this else refers to if(i == 10)
this else
Asthe comments indicate, the final else is not associated with if(<20) because itis not
in the same block (even though itis the nearest if without an else). Rather, the final else
is associated with iffi==10). The inner else refers to if(k>100) because itis the closest if
within the same block.
Prepared by: Raju Poudel [MCA] 1sThe if-else-if Ladder
‘A common programming construct that is based upon a sequence of nested ifs is the if-else-
if ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
else
statement;
Here is a program that uses an if-else-if ladder to determine which season a particular
month is in.
// demomatrats if-else-if atatenents
class IfElse (
Public static void main(String arge()
int month = 4; // April
String season;
if(month
else if (mo
else if (mo
systen.out.printin(*April is in the "+ season + ©
)
Here is the output produced by the program:
April is in the Spring.
switch
The switch statement is Java’s multiway branch statement. It provides an easy way to
dispatch execution to different parts of your code based on the value of an expression. As
such, it often provides a better alternative than a large series of if-else-if statements. Here is,
the general form of a switch statement:
Prepared by: Raju Poudel [MCA] 16switch (expression) {
case ouluel:
// statement sequence
break;
case valued
// statement sequence
break;
case value:
// statement sequence
break;
default:
// default statement sequence
,
Here is a simple example that uses a switch statement:
//-® simple example of the switch.
class Sampleswiten {
Public static void main(String args(]) (
for(int i=0; i<6; dee)
switch (i) {
case 0
System.out.printin("i is zero." ;
break;
System.out.printin("i is one.");
case 2:
System.out.printin("i is two.");
break:
case 3
Systemout printin ("i is three");
break;
System.out.printin("i is greater than 3."
)
}
‘The output produced by this program is shown here:
is two,
is three.
ie greater than 3
is greater than 3.
Iteration Statem
Java's iteration statements are for, while, and do-while. These statements create what we
commonly call loops. As you probably know, 2 loop repeatedly executes the same set of
instructions until a termination condition is met. A loop statement allows us to execute a
statement or group of statements multiple times.
Prepared by: Raju Poudel [MCA]for loop
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to be executed a specific number of times. A for loop is useful when you know how
many times a taskis to be repeated.
The syntax of a for loop is—
for(initialization; Boolean_expression; update) {
1/ Statements
Following is an example code of the for loop in Java.
public class Test {
public static void main(String args[]) {
for(int x = 105 x < 20; x =x +1) {
System.out.print("velue of x 7"
System. out .print(*\n")
+25
t
+
Output
value of x : 10
value of x: a1
value of x: 22
value of x: 13
value of x:
value of x:
value of x : 36
value of x : 37
value of x 1 28
Weiser sas
while Loop
‘A while loop statement in Java programming language repeatedly executes a target
statement as long as a given condition is true.
The syntax of a while loop is ~
nite Bootean_expression) {
1 Statements
z
Here, key point of the while loop is that the loop might not ever run. When the expression is
tested and the result is false, the loop body will be skipped and the first statement after the
while loop will be executed.
Prepared by: Raju Poudel [MCA] 18Example:
public class Test {
public static void main(String args[]) {
while( x < 20) {
system.out.print(‘value of x: * +x )s
aH
system.out print(“\n")
,
>
>
Output
value of x:
value of x:
value of x: 22
vole of x13
value of x: 14
value of x : 15
eee
value of x: 17
value of x: 18
value of x: 19
do while loop
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Following is the syntax of a do...while loop —
got
1) Statements
Ywhi1e(Boclean_expression) j
Example
public class Test {
public static void main(String arge[]) {
int x = 10;
dot
Systen.out.print(“value of xt" +x )5
Systen.out.print("\n") 3
while( xe < 20 )3
Prepared by: Raju Poudel [MCA] 19Output
value
value of x : 10
value of x: 11
value of x: 12
value of x: 13,
value of x: 14
value of x: 15
value of x: 16
value of x : 17
of
of
value
Nested Loops
Like all other programming languages, Java allows loops to be nested. That is, one loop may
be inside another. For example, here is a program that nests for loops:
J] Woops may be nested
clase Nested (
Public static void main(String arge(]) (
system out print (*.*
System. out .printin()
‘The output produced by this program is shown here:
Prepared by: Raju Poudel [MCA]
20Jump Statements
Java supports three jump statements: break, continue, and return. These statements
transfer control to another part of your program.
Using break
In Java, the break statement has three uses. First, as you have seen, it terminates a
statement sequence in a switch statement. Second, it can be used to exit a loop. Third, it
can be used asa “civilized” form of goto.
Using break to Exit a Loop
By using break, you can force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop. When a break statement is
encountered inside a loop, the loop is terminated and program control resumes at the next
statement following the loop. Here is a simple example:
110
1g break to exit a loop
Breaktoop {
public static void main(String args{]) {
for(int i=0; 1<100; i++) {
i£(i == 10) break; // ts
System.out .printin("i:
In ("Loop complete.) ;
This program generates the following output:
se Hee be be be He be
weraueunto
Loop complete.
‘As you can see, although the for loop is designed to run from 0 to 99, the break statement
causes it to terminate early, when i equals 10.
Using continue
Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop but stop processing the remainder of the code in its body for this
particular iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end.
The continue statement performs such an action.
In awhile and do-while loops, a continue statement causes control to be transferred directly
to the conditional expression that controls the loop. In a for loop, control goes first to the
Prepared by: Raju Poudel [MCA] 21iteration portion of the for statement and then to the conditional expression. For all three
loops, any intermediate code is bypassed.
Here is an example program that uses continue to cause two numbers to be printed on each
line:
// Demonstrate continue
class Continue {
public static void main(String args(]) {
for(int i=0; icl0; it+) {
system.out print (i +" ");
if (482 == 0) continue;
System.out .printIn("*);
}
}
}
This code uses the % operator to check if i is even. If it is, the loop continues without
printing a newline. Here is the output from this program:
ol
23
4s
67
89
Using return
The last control statement is return. The return statement is used to explicitly return from a
method. That is, it causes program control to transfer back to the caller of the method. As
such, itis categorized as a jump statement.
class at
int a,b, sums
public int add() {
oon
bet!
sun=atbs
return sums
+
,
class 8 {
public static void sain(string[] ergs) {
‘A objenew AC
int res=obj.add()5
Systen.out.printin("Sun of tuo numbers="sres)
+
e
Output:
Sum of two numbers=25
Prepared by: Raju Poudel [MCA] 22Unit — 3 Object Oriented Programming Concepts [9 Hrs.]
Fundamentals of a Class
A class, in the context of Java, are templates that are used to create objects, and to define
object data types and methods. Core properties include the data types and methods that
may be used by the object. All class objects should have the basic class properties. Classes
are categories, and objects are items within each category.
A dass is a user defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type. In
general, class declarations can include these components, in order:
1. Modifiers : A class can be public or has default access.
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclasslif any): The name of the class’s parent (superclass), if any, preceded by
the keyword extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if
any, preceded by the keyword implements. A class can implement more than one
interface.
5. Body: The class body surrounded by braces, { }.
General form of a class is shown below:
Access Modifier Class Name
public class Dbg {
String breed;
int age;
3 ){
Lex3
beys
ez
+
void caleulate() {
vol=1*b*hs
System.out.println("Volume of a box is "+vol);
?
+
public class Constructor {
public static void main(String[] args) {
Box obj=new Box(10,5,3.3)5
obj. calculate();
}
y
Output:
Volume of a box is 165.0
The this Keyword
Keyword this is a reference variable in Java that refers to the current object.
‘The various usages of ‘THIS’ keyword in Java are as follows:
+ It can be used to refer instance variable of current class
+ It can be used to invoke or initiate current class constructor
+ It can be passed as an argument in the method call
+ Itcan be passed as argumentin the constructor call
+ Itcan be used to return the current dass instance
Sometimes a method will need to refer to the object that invoked it. To allow this, Java
defines this keyword. this can be used inside any method to refer to the current object. That
is, this is always a reference to the object on which the method was invoked. You can use
this anywhere a reference to an object of the current class’ type is permitted.
// ® redundant use of this.
Box (double w, double h, double d) {
this.width = w
this.neight
this.depth = 4
}
Prepared by: Raju Poudel [MCA] 28//Java code for using ‘this’ keyword to
//refer current class instance variables
class Test
{
int a5
int b
// Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
}
void display()
{
//Displaying value of variables a and b
System.out.printin("a =" +#a4" b=" +0)
}
public static void main(String[] args)
t
Test object = new Test(10, 20);
object.display();
Output:
a=10 b=20
Prepared by: Raju Poudel [MCA]Four Main Features of Object Oriented Programming:
1. Abstraction
2. Encapsulation
3. Polymorphism
4. Inheritance
Abstraction
Abstraction is a process of hiding the implementation details from the user, only the
functionality will be provided to the user. In other words, the user will have the information
‘on what the object does instead of how it does it. In Java, abstraction is achieved using
Abstract classes and interfaces.
Abstract Class
‘A class which contains the abstract keyword in its declaration is known as abstract class.
* Abstract classes may or may not contain abstract methods, i.e., methods without
body (public void get();)
+ But, if a class has at least one abstract method, then the class must be declared
abstract.
+ Ifa class is declared abstract, it cannot be instantiated (We cannot create object).
* To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
+ If you inherit an abstract class, you have to provide implementations to all the
abstract methods in it.
abstract class Box{
int 1,b,h, vol;
void getdata() {
void calculate() {
=1"b"
systen.out.printIn("Volume of a tox is “+vol);
+
public class Abstraction extends Box {
public static void main(String[] args) {
Abstraction obj-new Abstraction();
obj.getdata();
obj.calculate();
,
+
Output:
Volume of a box is 100
Prepared by: Raju Poudel [MCA] 30Encapsulation
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on
the data (methods) together as a single unit. In encapsulation, the variables of a class will be
hidden from other classes, and can be accessed only through the methods of their current
class. Therefore, itis also known as data hiding.
To achieve encapsulation in Java -
+ Declare the variables of a class as private.
* Provide public setter and getter methods to modify and view the variables values.
Benefits of Encapsulation
+ The fields of a class can be made read-only or write-only.
+ Aclass can have total control over what is stored in its fields.
class Test{
private String name;
private int age;
public String getname() {
return name;
+
public int getage() {
return age;
t
public void setname(String nm) lit
+
public void setage(int ag) {
> ene
+
public class Encapsulation {
public static void main(String args) {
Test objenew Test();
obj.setnane(“Raaju Poudel”);
obj. setage(27);
System.out.printLn("Name: “tebj.getname()) 5
System.out.println("Age: "tobj.getage());
+
t
Outpu!
Name: Raaju Poudel
age: 27
Here, we cannot access private data members name and age directly. So we have created
public getter and setter methods to access private data members.
Prepared by: Raju Poudel [MCA] anPolymorphism
Polymorphism in Java is a concept by which we can perform a single action in different
ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word “poly”
means many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.
Polymorphism in Java
Compile Time Runtime
(Method Overloading)| (Method Overiding)
Method Overloading
Method Overloading is a feature that allows a class to have more than one method having
the same name, if their argument lists are different. It is similar to constructor overloading
in Java, that allows a class to have more than one constructor having different argument
lists. In order to overload a method, the argument lists of the methods must differ in either
of these:
a) Number of parameters.
add{int, int)
add(int, int, int)
b) Data type of parameters.
add{int, int)
add{int, float)
¢) Sequence of Data type of parameters.
add{int, float)
add(float, int)
Prepared by: Raju Poudel [MCA] 22Example of method overloading:
class Overload
t
void demo (int a)
{
System.out.println ("a: " + a);
+
void demo (int a, int b)
{
System.out.println ("a and b: "+a +"," +b);
}
double deno(double a) {
System.out.println("double a: " + a);
return a*a;
+
+
class Methodoverloading
{
public static void main (String args [])
{
Overload Obj = new Overload()s
double result:
Obj .demo(16);
Obj .demo(16, 2);
result = 0bj .demo(5.5)5
System.out.print1n("0/P : " + result);
+
+
Output:
a: 10
a and b: 10,20
double
o/? : 30.25
Here the method demo() is overloaded 3 times: first method has 1 int parameter, second
method has 2 int parameters and third one is having double parameter. Which method is to
be called is determined by the arguments we pass while calling methods. This happens at
compile time so this type of polymorphism is known as compile time polymorphism.
Prepared by: Raju Poudel [MCA] 33Method Overriding
Declaring a method in sub class which is already present in parent class is known as method
overriding. Overriding is done so that a child class can give its own implementation to a
method which is already provided by the parent class. In this case the method in parent
class is called overridden method and the method in child class is called overriding method
Let’s take a simple example to understand this. We have two classes: A child class Boy and a
parent class Human. The Boy class extends Human class. Both the classes have a common
method void eat (). Boy class Is giving its own implementation to the eat () method or in
other words it is overriding the eat () method.
class Hunan{
//Overridden method
public void eat()
{
systen.out.printIn("Human is eating");
}
class Boy extends Human{
//overriding method
public void eat(){
Systen.out.print1n("Boy is eating”);
+
public static void main( string args{]) {
Boy obj = new Boy();
This will call the child class version of eat()
obj.eat();
}
?
Output:
Boyis eating
Rules of method over ig in Java
1. Argument list: The argument list of overriding method (method of child class) must
match the Overridden method (the method of parent class). The data types of the
arguments and their sequence should exactly match
2. Access Modifier of the overriding method (method of subclass) cannot be more
restrictive than the overridden method of parent class. For e.g. if the Access Modifier
of parent class method is public then the overriding method (child class method)
cannot have private, protected and default Access modifier, because all of these
three access modifiers are more restrictive than public.
Prepared by: Raju Poudel [MCA] 34Another Example:
AnimaLjava
public class Animal{
public void sound(){
Systen.out.printIn(“Animal is making 2 sound"):
Horse.java
class Horse extends Aninal{
@override
public void sound(){
System.out.println(“Neigh”
+
public static void main(String args[]){
Aninal obj = new Horse();
obj.sound();
Output:
Neigh
Recursion
Java supports recursion. Recursion is the process of defining something in terms of itself. As
it relates to Java programming, recursion is the attribute that allows a method to call itself.
A method that calls itself is said to be recursive.
The classic example of recursion Is the computation of the factorial of a number. The
factorial of a number N is the product of all the whole numbers between 1 and N. For
example, 3 factorial is 1 x 2 x 3, or 6. Here is how a factorial can be computed by use of a
recursive method:
Prepared by: Raju Poudel [MCA] as// & simple example of recursion,
clase Factorial {
// this is a recursive method
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args(J) {
Factorial £ = new Factorial ();
system.out .printin("Factorial of 3 is " + £.fact (3);
System.out .printIn("Factorial of 4 is " + f.fact (4);
system.out.printIn("Factorial of 5 is " + £.fact (5);
}
}
The output from this program is shown here:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
Introducing Nested and Inner Classes
It is possible to define a class within another class; such classes are known as nested classes.
The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is
defined within class A, then B does not exist independently of A. Anested class has access to
the members, including private members, of the class in which it is nested. However, the
enclosing class does not have access to the members of the nested class. A nested class that
is declared directly within its enclosing class scope is @ member of its enclosing class. It is
also possible to declare a nested class that is local to a block.
There are two types of nested classes: static and non-static. A static nested class is one that
has the static modifier applied. Because it is static, it must access the members of its
enclosing class through an object. That is, it cannot refer to members of its enclosing dass
directly. Because of this restriction, static nested classes are seldom used.
The most important type of nested class is the inner class. An inner class is a non-static
nested class. It has access to all of the variables and methods of its outer class and may refer
to them directly in the same way that other non-static members of the outer class do.
The following program illustrates how to define and use an inner class. The class named
Outer has one instance variable named outer_x, one instance method named test{ ), and
defines one inner class called Inner.
Prepared by: Raju Poudel [MCA] 36// Demonstrate an inner class
clase Outer {
int outer_x = 100;
void test () {
Inner inner = new Tnner() ;
inner. display ();
}
// this is an inner class
class Inner {
void display() {
System. out .printIn("display: outer_x = " + outer_x);
}
}
}
clase InnerClassDemo {
public static void main(String args{]) {
Outer outer = new Outer();
outer. test(
}
}
Output from this application is shown here:
display: outer_x = 100
In the program, an inner class named Inner is defined within the scope of class Outer.
Therefore, any code in class Inner can directly access the variable outer_x. An instance
method named display( ) is defined inside Inner. This method displays outer_x on the
standard output stream. The main( ) method of InnerClassDemo creates an instance of class
Outer and invokesits test( ) method. That method creates an instance of class Inner and the
display( ) method is called.
Access Control
As you know, encapsulation links data with the code that manipulates it. However,
encapsulation provides another important attribute: access control. Through encapsulation,
you can control what parts of a program can access the members of a class. By controlling
access, you can prevent misuse. For example, allowing access to data only through a well-
defined set of methods, you can prevent the misuse of that data.
Java’s access specifiers are public, private, and protected. Java also defines a default access
level. protected applies only when inheritance is involved.
Prepared by: Raju Poudel [MCA] a7Uni
4 Inheritance & Packaging [3 Hrs.
Inheritance is an important pillar of OOP (Object Oriented Programming). It is the
mechanism in java by which one class is allow to inherit the features (fields and methods)
of another class.
The process by which one class acquires the properties (data members) and
functionalities(methods) of another class is called inheritance. The aim of inheritance is to
provide the reusability of code so that a class has to write only the unique features and rest
of the common properties and functionalities can be extended from the another class.
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of the parent class. Moreover, you can add new methods and fields in your current class
also.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship. inheritance is used in java for the following:
© For Method Overriding (so runtime polymorphism can be achieved).
© For Code Reusability.
Terms used in Inheritance
‘© Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
© Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
© Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. Itis also called a base class or a parent class.
© Reusability: As the name specifies, reusability is a mechanism which facilitates you
to reuse the fields and methods of the existing class when you create a new class.
You can use the same fields and methods already defined in the previous class.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
+
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
In the terminclogy of Java, @ class which is inherited |s called a parent or superclass, and
the new class is called child or subclass.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.
Prepared by: Raju Poudel [MCA] a8public class A{
Ns
public class B extends A {
:
‘Multi Level Inheritance
public class A {
public class B oxtonds A {
public class Cextends B
Hisrarchical inheritance
[eisss ] pi dss A.
public class B extends A (..
[ciass 8 | [cass ¢ | public class C extends A {...
‘Multiple inheritance
[cassa] [cise |
public class A }
PUDIIC CASS B (..snsnnnne}
public class C extends A.B {
}1/ Java does not support mutiple inheritance
gle Inheritance
‘Single inheritance refers to 2 child and parent class relationship where a class extends the
another class.
class Animal{
void eat(){
System.out.printin("eating
3
+
class Dog extends Animal{
void bark(){
System.out.printin("barking..
+
+
class Testinheritance{
public static void main(String args{]){
Dog d=new Dog();
d.bark();
d.eat();
Prepared by: Raju Poudel [MCA] 393
+
Output
barking
eating,
2. Multilevel Inheritance
Multilevel inheritance refers to a child and parent class relationship where a class extends
the child class. For example, class C extends class B and class B extends class A.
class Animal{
void eat(){
System.out.printin("eating...");
+
+
class Dog extends Animal{
void bark(){
System. out.printin(“barking..
+
}
class BabyDog extends Doot
void weep(){
System.out.printin("weeping.
3
+
class Testinheritance2{
public static void main(String argst1}{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
3
Output
weeping
barking
eating,
Prepared by: Raju Poudel [MCA] 403. Hierarchical Inheritance
Hierarchical inheritance refers to a child and parent class relationship where more than one
classes extends the same class. For example, classes B, C & D extends the same class A.
class Animal{
void eat(){
System.out.printin("eating
+
}
class Dog extends Animal{
void bark(){
System.out.printin("barking..
+
>
class Cat extends Animal{
void meow(){
System.out.printin("meowina.
+
+
class TestInheritance3{
public static void main(String args{]){
Cat c=new Cat();
c.meow();
c.eat();
//c.barkQ); //Etror //To access property of class Dog create object of class Doa
Dog d=new Dog();
d.bark();
3
+
Output
weeping
barking
eating,
Multiple Inheritance
When one class extends more than one classes then this is called multiple inheritance. For
example: Class C extends class A and B then this type of inheritance is known as multiple
inheritance.
Java doesn’t allow multiple inheritance. We can use interfaces instead of classes to achieve
the same purpose.
Prepared by: Raju Poudel [MCA] a1Interface in Java
Like a class, an interface can have methods and variables, but the methods dectared in
interface are by default abstract (only method signature, no body).
Interfaces specify what a class must do and not how. It is the blueprint of the class.
‘An Interface is about capabilities like 2 Player may be an interface and any class
implementing Player must be able to (or must implement] move (). So it specifies a
set of methods that the class has to implement.
‘ If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then class must be declared abstract.
‘Syntax
interface {
// declare constant fields
// declare methods that abstract
// by default.
To declare an interface, use interface keyword. It is used to provide total abstraction. That
means all the methods in interface are declared with empty body and are public and all
fields are public, static and final by default. A class that implement interface must
implement all the methods declared in the interface. To implement interface
use implements keyword.
Why do we use interface?
+ Itisused to achieve total abstraction.
* Since java does not support multiple inheritance in case of class, but by using
Interface it can achieve multiple inheritance.
// & simple interface
interface Player
final int id = 10;
int move();
Prepared by: Raju Poudel [MCA] a2Example of Interface
// Java program to demonstrate working of
// interface.
import java.io.*;
// A simple interface
interface inl
{
// public, static and final
final int a = 10;
// public and abstract
void display();
}
// A class that implements interface.
class testClass implements in1
{
// Implementing the capabilities of
// interface.
public void display()
{
3
System. out. printin(“Geek”);
// Driver Code
public static void main (String[] args)
{
testClass t = new testClass();
t.display();
System.out.print1n(a) 5
Prepared by: Raju Poudel [MCA]
a3Use of Interface to achieve multiple inheritance
Let us say we have two interfaces A & B and two classes C & D. Then we can achieve
multiple inheritance using interfaces as follows:
interface At }
interface Bf }
class C{ }
class D extends
plements A,B { }
Example Program
interface interfacel{
void display1();
t
interface interface2{]
void display2();
W
class A{
void display3() {
System.out.printIn("I am inside class");
}
}
class B extends A implements interfacel, interface2{
public void display1() {
System.out.printIn("I am inside interface1");
+
public void display2() {
System.out.print1n("I am inside interface2");
+
+
public class Multilevel {
public static void main(String[] args) {
B obj=new B();
obj.display1();
obj.display2();
obj-display3() 5
Output
I am inside interface1
I am inside interface2
I am inside class
Prepared by: Raju Poudel [MCA] a4Another Example
interface interfacel{
int o=20,b=10;
void add();
+
class Ax{|
int diff;
void subtract(int x,int y) {
diff=x-y;
System.out.print1n("Subtraction= "+diff);
}
o
class Bx extends Ax implements interfacel{
int sum;
public void add() {
sum=a+b;
System. out. print1n("Addition=
"+sum) 5
+
public class Multilevel {
public static void main(String[] args) {
Bx obj=new Bx();
obj.add();
obj.subtract(50, [1d);|
+
}
Output
Add = 30
Subtraction= 40
Prepared by: Raju Poudel [MCA]
4sDynamic Method Dispatch
Method overriding forms the basis for one of Java’s most powerful concepts: dynamic
method dispatch. Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile time. Dynamic method
dispatch is important because this is how Java implements run-time polymorphism.
Here is an example that illustrates dynamic method dispatch:
// Dynamic Nethod Dispatch
class A {
void callme() (
system.out .print1n("Inside A's callme method") ;
}
}
class B extends A {
// override calime()
void callme() {
System.out.printin("Inside B's callme method") ;
}
}
class C extends A {
// override calime()
void calime() {
System. out.printin ("Inside C's callme method") ;
}
}
class Dispatch {
public static void main(String args(}) {
new A(); // object of type A
new B(); // object of type B
new C(); // object of type C
Ar; // obtain a reference of type A
r= a; // x refers to an A object
r.callme(); // calls A's version of callme
r= b; // © refers to a B object
r.callme(); // calls B's version of callme
r= c; // x refers to a C object
r.callme(); // calls C's version of callme
)
}
The output from the program is shown here:
Inside A’s callme method
Inside B's callme method
Inside C’s callme method
Prepared by: Raju Poudel [MCA] 46This program creates one superclass called A and two subclasses of it, called B and C.
Subclasses B and C override callme( ) declared in A. Inside the main( ) method, objects of
type A,B, and C are declared. Also, a reference of type A, called r, is declared. The program
then in turn assigns a reference to each type of object to r and uses that reference to invoke
callme| ). As the output shows, the version of callme( ) executed is determined by the type
of object being referred to at the time of the call. Had it been determined by the type of the
reference variable, r, you would see three calls to A’s callme( ) method.
Super Keyword
The super keyword in java is a reference variable that is used to refer parent class
objects. The keyword “super” came into the picture with the concept of Inheritance. It is
majorly used in the following contexts:
1. Use of super with variables: This scenario occurs when a derived class and base class has
same data members. In that case there is a possibility of ambiguity for the JVM. We can
understand it more clearly using this code snippet:
/* Base class vehicle */
class Vehicle
{
+
Ant maxSpeed - 1205
/* sub class Car extending vehicle */
class Car extends Vehicle
{
int maxSpeed = 180;
void display()
t
/* print naxSpeed of base class (vehicle) */
System.out.printIn( "Maximum Speed: " + super.maxSpeed) ;
+
3
/* Driver program to test */
class Test
{
public static void main(String[] args)
t
Car small = new Car();
small. display();
}
3
Output:
Maximum Speed: 120
Prepared by: Raju Poudel [MCA] a7In the above example, both base class and subclass have a member maxSpeed. We could
access maxSpeed of base class in subclass using super keyword.
2. Use of super with methods: This is used when we want to call parent class method. So
whenever a parent and child class have same named methods then to resolve ambiguity we
use super keyword. This code snippet helps to understand the said usage of super keyword.
/* Base class Person */
class Person
t
void message()
System.out.println (This is person clase
3
/* Subclass Student */
class Student extends Person
{
void message()
System.out.printIn(“This is student class")s
+
J] Note that display() is only in Student clacs
void display()
J/ will invoke or call current class message() method
nessage();
J/ will invoke or call parent class message() method
super.message()
+
t
/* Driver program to test */
class Test
{
public static void main(String args[])
{
Student s = new Student()5
1/ calling displey() of Student
s.display();
+
t
Output
This is student class
This is person class
In the above example, we have seen that if we only call method messege () then, the current
class message () is invoked but with the use of super keyword, message () of superclass
could also be invoked.
Prepared by: Raju Poudel [MCA] 483. Use of super with constructors: super keyword can also be used to access the parent
class constructor. One more important thing is that, “‘super’ can call both parametric as well
as non-parametric constructors depending upon the situation. Following 's the code snippet,
to explain the above concept:
/* superclass Person */
class Person
t
Person()
{
System. out.printIn("Person class Constructor”
3
}
/* subclass Student extending the Person class */
class Student extends Person
C
Student()
// invoke or call parent class constructor
super()5
System.out.printIn("Student class Constructor");
}
t
/* Driver program to test*/
class Test
t
public static void main(String[] args)
{
Student s = new Student();
+
3
Outpu
Person class Constructor
Student class Constructor
In the above example we have called the superclass constructor using keyword ‘super’ via
subclass constructor.
Prepared by: Raju Poudel [MCA] 49Abstract and Final Classes
Abstract class has been discussed already in Unit-3 (Abstraction).
The keyword final has three uses. First, it can be used to create the equivalent of anamed
constant. The other two uses of final apply to inheritance.
Using final to Prevent Overriding
While method overriding is one of Java’s most powerful features, there will be times when
you will want to prevent it from occurring. To disallow a method from being overridden,
specify final as a modifier at the start of its declaration. Methods declared as final cannot be
overridden. The following fragment illustrates final:
4 meth() {
System.out .printIn("This is a final method.*);
class B extends a {
void meth() { // ERROR! Can't override
System.out .printin("I1legal!*) ;
}
Because meth () is declared as final, it cannot be overridden in B. If you attempt to do so, a
compile-time error will result.
Using final to Prevent Inheritance
Sometimes you will want to prevent a class from being inherited. To do this, precede the
class declaration with final. Declaring a class as final implicitly declares all of its methods as
final, too. As you might expect, itis illegal to declare a class as both abstract and final since
an abstract class is incomplete by itself and relies upon its subclasses to provide complete
implementations.
Here is an example of a final class:
final class A (
W-
}
// The following class is i21egal
class B extends A { // ERROR! Can't subclass A
W
}
As the comments imply, itis illegal for B to inherit A Since A is declared as final.
Prepared by: Raju Poudel [MCA] 50The Object Class
There is one special class, Object, defined by Java. All other classes are subclasses of Object.
That is, Object is a superclass of all other classes. This means that a reference variable of
type Object can refer to an object of any other class. Also, since arrays are implemented as
classes, a variable of type Object can also refer to any array.
Object defines the following methods, which means that they are available in every object.
/Metnod Purpose
object clone() Creates new object that is the same as the object being cloned.
boolean equals(Object object) [Determines whether one object is equal to another.
void finatize( ) [Called before an unused object is recycied.
[Class getCiass( ) Obtains the class of an object at run time.
int hashCode( ) Retums the hash code associated with the invoking object.
void notify) Resumes execution of a thread waiting on the invoking object.
oid notiyal ) [Resumes execution of all threads waiting on the invoking object.
String toString( ) Retums a string that describes the object.
void wait, ) \Waits on another thread of execution.
{oid wait{iong milliseconds)
ola warttong mutiseconas,
int nanoseconds)
The methods getClass{ ), notify( ), notifyAll( ), and wait( ) are declared as final. You may
override the others. However, notice two methods now: equals( ) and toString( ). The
equals( ) method compares the contents of two objects. It returns true if the objects are
equivalent, and false otherwise.
Package
‘A Java package is a group of similar types of classes, interfaces and sub-packages. Package in
java can be categorized in two form, built-in package and user-defined package. There are
many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
The package keyword is used to create 2 package in java.
//save as Simple java
package mypack;
public class Simple
public static void main(String aras[1){
System.out printin("Welcome to package");
3
}
Prepared by: Raju Poudel [MCA] 51There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.
//save by A.java
package pack;
public class At
public void msg(){System.out.printin("Hello");}
?
/Isave by B.java
package mypack;
import pack.A;
class BE
public static void main(String args[]){
A obj = new At);
obj.msq();
3
+
Output:Helle
Subpackage in java
Package inside the package is called the subpackage.
package java.util. Scanner;
class Simple{
public static void main(String aras{]){
Scanner scan=new Scanner(System.in);
System.out.printin("Enter a number");
int a = scan.nextInt();
System.out.printin(*Inputted number i
+}
"+a);
Prepared by: Raju Poudel [MCA] 52Unit — 5 Handling Error/Exceptions [2 Hr:
‘An exception is an unwanted or unexpected event, which occurs during the execution of a
program i.e. at run time, that disrupts the normal flow of the program's instructions.
Error vs Exception
Error: An Error indicates serious problem that a reasonable application should not try to
catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
‘An exception (or exceptionel event) is a problem that arises during the execution of a
program. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
‘An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
+ Auser has entered an invalid data.
+ A file that needs to be opened cannot be found.
+ Anetwork connection has been lost in the middle of communications or the JVM has
run out of memory.
‘Some of these exceptions are caused by user error, others by programmer error, and others
by physical resources that have failed in some manner.
Based on these, we have three categories of Exceptions. You need to understand them to
know how exception handling works in Java.
+ Checked exceptions - A checked exception is an exception that is checked (notified)
by the compiler at compilation-time, these are also called as compile time
exceptions. These exceptions cannot simply be ignored; the programmer should take
care of (handle) these exceptions.
* Unchecked exceptions - An unchecked exception is an exception that occurs at the
time of execution. These are also called as Runtime Exceptions. These include
programming bugs, such as logic errors or improper use of an API. Runtime
exceptions are ignored at the time of compilation.
+ Errors - These are not exceptions at all, but problems that arise beyond the control
of the user or the programmer. Errors are typically ignored in your code because you
can rarely do anything about an error. For example, if a stack overflow occurs, an
error will arise. They are also ignored at the time of compilation.
Prepared by: Raju Poudel [MCA] 53Hierarchy of Java Exception classes
The java.lang. Throwable class is the root class of Java Exception hierarchy which is inherited
by two subclasses: Exception and Error. A hierarchy of Java Exception classes are given
below:
Prepared by: Raju Poudel [MCA] saJava Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.
Keyword | Description
try The "try" keyword is used to specify a block where we should place exception
code. The try block must be followed by either catch or finally. It means, we
can't use try block alone.
catch ‘The “catch” block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by
finally block later.
finally | The “finally” block is used to execute the important code of the program. It is
executed whether an exception is handled or not.
throw | The "throw" keyword is used to throw an exception.
throws | The "throws" keyword is used to declare exceptions. It doesn't throw an
exception. It specifies that there may occur an exception in the method. It is
always used with method signature.
Java Exception Handling Example
Let's see an example of Java Exception Handling where we using a try-catch statement to
handle the exception.
public class JavaExceptionExample{
public stat
try
//code that may raise exception
it data=100/0;
}eatch(ArithmeticException e)
<
void main(String argsf]){
System.out printin(e);
+
/irest code of the program
System.out.printin("rest of the code
>
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
zest of the code...
Prepared by: Raju Poudel [MCA] 5sCommon Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They are as
follows:
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException
int a=50/0;//ArithmeticException
2)A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
System.out.printin(s.length());//NullPointerException
3) A scenario where Numberformatexception occurs
‘The wrong formatting of any value may occur NumberFormatException. Suppose | have a
string variable that has characters, converting this variable into digit will occur
NumberFormatException.
String s="abe";
int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayindexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int{5];
a[10]=50; //ArrayIndexOutOfBoundsExcention
Java finally block
Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
Java finally block is always executed whether exception is handled or not. Java finally block
follows try or catch block.
publ
publ
try{
int data=25/0;
System.out.printin(data);
;
catch(ArithmeticException e){
System.out.printin(e);
class TestFinallyBlock2{
static void main(String args[]){
>
finally{
System. out.printin("finally block is always executed");
Prepared by: Raju Poudel [MCA] 56+
System.out.printin("rest of the code.
‘on in thread main java.lang.ArithmeticExca)
finally block is always executed
rest of the code...
tion: / by zero
Java Multi-catch block
A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
o Ata time only one exception occurs and at a time only one catch block is executed.
© All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
public class MultipleCatchBiock1 {
public static void main(String{] args) {
tryf
int a{}=new int{5];
a[5]=30/0;
+
catch(ArithmeticException e)
{
System.out.printin("Arithmetic Exception occurs");
>
catch(ArrayIndexOutOfBoundsExceotion e)
{
‘System.out.printin{"ArrayIndexOutOfBounds Exception occurs");
+
catch(Exception e)
t
System.out.printin("Parent Exception occurs");
}
System.out.printin("rest of the code");
Output:
Arithmetic Exception occurs
rest of the code
Prepared by: Raju Poudel [MCA] 87public class MultipleCatchBlock2 {
public static void main(String{] args) {
tryt
int a[]=new int[5];
System.out.printin(a[10])
+
catch(ArithmeticException e)
{
System.out.printin( "Arithmetic Exception occurs");
+
catch (ArrayIndexOutOfBoundsException e)
t
‘System.out.printin("ArrayindexOutOfBounds Exception occurs");
+
catch(Exception e)
{
System.out.printin("Parent Exception occurs");
+
System.out.printin("rest of the code");
»
Output:
ArraylndexOutotBounds Exception occurs
rest of the code
Java Nested try block
The try block within a try block is known as nested try block in java. Sometimes a situation
may arise where a part of a block may cause one error and the entire block itself may cause
another error. In such cases, exception handlers have to be nested.
‘Syntax:
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
+
Prepared by: Raju Poudel [MCA] 58catch(Exception e)
+
}
catch(Exception e)
{
}
Example:
class Excep6{
public static void main(String args{])<
tryf
tryt
System.out.printin("going to divide");
int b =39/0;
}eatch(Arithmeticexception e){
System.out.printin(e);
+
try{
int af
a[S]=4;
}eatch(ArrayIndexOutOfBoundsException e){
System.out.printin(e);
}
new int[5];
System out printin("“other statement);
}eatch(Exception e){
System. out.printin("handeled");
+
‘System.out.printin("normal flow..");
>
+
Prepared by: Raju Poudel [MCA]
59Java throw keyword
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception.
The syntax of java throw keyword is given below.
throw new IOException("sorry device error);
Example:
In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise
print a message welcome to vote.
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException(“not valid”);
else
System.out.printin(""welcome to vote");
+
public static void main(String args{]){
validate(13);
System.out.printin("rest of the cod
on in thread main java.lang.ArithneticException:not valid
Java throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing checkup before the code being used.
‘Syntax of java throws
return_type method_name() throws exception_ciass_name{
//method code
+
Prepared by: Raju Poudel [MCA] 60Example of Java throws
import java.io. IOException;
class Testthrows1{
void m()throws IOException {
throw new IOException("device error");//checked exception
>
void n()throws IOException{
m0;
}
void p()
tryt
00;
}catch(Exception e){
System.out.printin( “exception handled");
x
}
public static void main(String arasf1)¢
Testthrows1 obj=new Testthrows1();
0bj.000;
System.out printin( "normal flow.
+
;
Output:
exception handled
normal flow
Difference between throw and throws in Java
No. | throw throws
1)
Java throw keyword is used to
explicitly throw an exception.
Java throws keyword is used to declare
an exception.
2)| Checked exception cannot be| Checked exception can be propagated
propagated using throw only. with throws.
3) |__ Throw is followed by an instance. Throws is followed by class.
4)] Throw is used within the method. Throws is used with the method
signature.
5)| You cannot throw ~— multiple |_ You can declare multiple exceptions e.g.
exceptions. public void method( throws:
IOException, SQLException.
Prepared by: Raju Poudel [MCA] 61Unit — 5 Handling Strings [2 Hrs.
String Creation
Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
charf] ch={'j'/a',V',2','t,'D''0'"'/'0','t 5
String s=new String(ch);
is same as:
String
‘javatpoint";
There are two ways to create String object:
1. By string literal
2. By new keyword
2) String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the
string already exists in the pool, a reference to the pooled instance is returned. If the string
doesn't exist in the pool, a new string instance is created and placed in the pool. For
example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
2) By new keyword
String s=new String("Welcome');//creates two objects and one reference variable
Java String Example
public class StringExamplet
public static void main(String arast1){
String s1="java";//creating string by java string literal
char ch{]={'s,'t'r"','0,'9's};
String s2=new String(ch);//converting char array to string
String s3=new String(“example");//creating java string by new keyword
‘System.out.printin(s1);
System.out.printin(s2);
‘System. out. printin(s3);
»
Output
java
Strings
example
Prepared by: Raju Poudel [MCA] 62String Length
The length of a string is the number of characters that it contains. To obtain this value, call
the length( ) method, shown here:
int length)
The following fragment prints “3”, since there are three characters in the string s:
char chars{] = {'a','b’, 'c’ };
String s = new String(chars);
System.out.printin(s.iength());
Concatenation of String
The following fragment concatenates three strings:
String age = "9"
String s= "He Is" + age +" years old
System.out printin(s);
This displays the string “He is 9 years old.”
‘One practical use of string concatenation is found when you are creating very long strings.
Instead of letting long strings wrap around within your source code, you can breek them
into smaller pieces, using the + to concatenate them. Here is an example:
// Using concatenation to prevent long lines.
class ConCat {
public static void main(String args{]) {
String longstr = "This could have been "+
“a very long line that would have" +
“wrapped around. But string concatenation " +
“prevents this.";
System.out printin(longstr);
}
}
String Concatenation with Other Data Types
You can concatenate strings with other types of data. For example, consider this slightly
different version of the earlier example:
intage =9;
String s= "He is" + age +" years old.”;
System.out.printin(s);
In this case, age is an int rather than another String, but the output produced is the same
as before. This is because the int value in age is automatically converted into its string
representation within a String object. This string is then concatenated as before.
Be careful when you mix other types of operations with string concatenation expressions,
however, you might get surprising results. Consider the following:
String s= "four: "+2 +2;
System.out.printin(s);
This fragment displays four: 22 rather than the four: 4
Prepared by: Raju Poudel [MCA] 63To complete the integer addition first, you must use parentheses, like this:
String s= "four: " + (2+ 2);
Now s contains the string “four: 4”.
Conversion of String
“Conversion of any type to String use,
a. String.valueOf( )
b. toString( )
+ Conversion of String to any type use,
a. any_type.parse()
Converting any type to String:
public class Conversion {
public static void main(String[] args) {
int a=10;
double b=5.5;
//Converting other types to String
String si=String.valueof(a);
String s2-String.valueOf(b);
//concatination of two strings
String s3=s1+s2;
System. out.printIn(s3) ;
t
+
Output:
105.5
Converting String to any type:
public class Conversion {
public static void main(String[] args) {
String si
String s2: 5
//converting String to Integer
int a=Integer.parseInt(s1);
//converting String to Double
double b=Double.parseDoubLe(s2) ;
double PBS-(double)a+b;
System.out.printIn("Result= "+res);
}
+
Output
Result= 21.5
Prepared by: Raju Poudel [MCA] 6aChanging case of String
The method toLowerCase( ) converts all the characters in a string from uppercase to
lowercase. The toUpperCase( ) method converts all the characters in a string from
lowercase to uppercase. Non alphabetical characters, such as digits, are unaffected.
Here isan example that uses toLowerCase| } and toUpperCasel ):
// Demonstrate toUpperCase() and toLowerCase()
class ChangeCase {
public static void main(String args{])
{
String s = "This is a test.
System. out.printin("Original:
String upper = s.touUppercase();
String lower = s.toLoverCase();
+s)5
System. out.printin(" + upper);
System. out.printin(" + lower);
}
+
Output
Original: This is a test.
Uppercase: THIS IS A TEST.
Lowercase: this is a test.
Character Extraction
The String class provides a number of ways in which characters can be extracted from a
String object. Although the characters that comprise a string within a String object cannot
be indexed as if they were a character array, many of the String methods employ an index
(or offset) into the string for their operation. Like arrays, the string indexes begin at zero.
charAt
To extract a single character from a String, you can refer directly to an individual character
via the charAt( ) method. It has this general form:
char charAt(int where)
Here, where is the index of the character that you want to obtain. The value of where must
be nonnegative and specify a location within the string. charAt{ ) returns the character at
the specified location. For example,
char ch;
ch = "abe".charat(1);
assigns the value “b” to ch.
Prepared by: Raju Poudel [MCA] 6sgetChars|
If you need to extract more than one character at a time, you can use the getChars( )
method.
It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart]
Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd
specifies an index that is one past the end of the desired substring. Thus, the substring
contains the characters from sourceStart through sourceEndl. The array that will receive
the characters — is specified by target. The index within target at which the substring will be
copied is passed in targetStart. Care must be taken to assure that the target array is large
enough to hold the number of characters in the specified substring.
class getCharsDeno {
public static void main(String args[]) {
String s = "This is a demo of the getChars method
int start = 10;
int end = 14;
char buf{] = new char[end - start];
s.getChars(start, end, buf, @);
System. out.print1n(buf);
+
Output
demo
String Comparison
There are three ways to compare string in java:
1. By equals() method
2. By=~=operator
3. By compareTo() method
1) String compare by equals() method
The String equals() method compares the original content of the string. it compares values
of string for equality. String class provides two methods:
© public boolean equals(Object another) compares this string to the specified object.
© public boolean equalsignoreCase(String another) compares this String to another
string, ignoring case.
class Teststringcomparison1{
public static void main(String args[ 1)<
String s1="Sachin";
'Sachin";
ew String("Sachin");
System.out.printin(s1.equals(s2));//true
Prepared by: Raju Poudel [MCA] 66System.out.printin(s1.equals(s3));//true
System.out.printin(s1.equals(s4)); //false
+
+
Output
true
true
false
class Teststringcomparison2{
public static void main(String args[]}{
String s1="Sachin";
String s2="SACHIN";
‘System.out.printin(s1.equals(s2)};//false
‘System.out.printin(s1.equalsIgnoreCase(s2));//true
2) String compare by compareTo() method
The java string compareTo() method compares the given string with current string
lexicographically. It returns positive number, negative number or 0.
It compares strings on the basis of Unicode value of each character in the strings.
if si > 52, it returns positive number
if s1 < s2, it returns negative number
if s1 == 2, itreturns 0
public class CompareToExample{
public static void main(String args{]){
String s1,
String 52:
String <3:
System. out.printin(s1.compareTo(s2));//0 because both are equal
System.out.printin(s1.compareTo(s3));//~
5 because "h" is 5 times lower than "m"
aaa
Output
0
5
Prepared by: Raju Poudel [MCA] 67Searching Strings
The String class provides two methods that allow you to search a string for a specified
character or substring:
* indexOf{ ) Searches for the first occurrence ofa character or substring.
+* lastIndexOf( ) Searches for the last occurrence of a character or substring
To search for the first occurrence of a character, use
int indexOf{int ch)
To search for the last occurrence of a character, use
int lastindexOflint ch)
Here, ch is the character being sought.
To search for the first or last occurrence of a substring, use
int indexOf(String str)
int lastindexOf{String str)
Here, str specifies the substring.
You can specify a starting point for the search using these forms:
int indexOf{int ch, int startindex)
int lastindexOffint ch, int startindex)
int indexOf{String str, int startindex)
int lastindexOf(String str, int startindex)
Here, startindex specifies the index at which point the search begins. For indexO{{ ), the
search runs from startindex to the end of the string. For lastIndexOf{ ), the search runs from
startindex to zero.
// Demonstrate indexOf() and lastIndex0F().
class indexOfDemo {
public static void main(String args[]) {
String § = "Now is the time for all good men " +
“to come to the aid of their country
System. out.print1n(s) ;
System.out.printIn("indexof(t) =" +
§.indexOF('t'));
System. out.println("lastIndexOF(t) = "+
s.lastIndex0F(‘t'));
System. out.printin("indexof(the) =
5. indexOF("the")) 5
System. out.print1n("lastIndexOf (the)
s.lastIndex0F("the")) ;
System.out.println("indexOF(t, 1¢) = "+
S.indexof('t', 10));
System. out.print1n("lastIndexOf(t, 60) +
s.lastIndexOf('t', 68));
System.out.printin("indexOf(the, 10) =
S.indexOF("the", 10));
System.out.printIn("lestIndexOf(the, 60) = "
§.lastIndexOf("the", 60));
"
+
Prepared by: Raju Poudel [MCA] 68Output
Now is the time for all good men to come to the aid of their country.
indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(the)
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55
Modifying a String
substring( )
The java string substring() method returns a part of the string.
We pass begin index and end index number position in the java substring method where
start index is inclusive and end index is exclusive. In other words, start index starts from 0
whereas end index starts from 1.
There are two types of substring methods in java string,
substring(int startindex)
and
substring(int startindex, int endindex)
Examples
public class SubstringExample{
public static void main(String args{]){
String s1="javatpoint";
System.out.printin(s1.substring(2,4));//returns va
System.out.printin(s1.substring(2));//returns vatpoint
aaa
public class SubstringExample2 {
public static void main(String[] args) {
String s1="Javetpoint";
String substr = si.substring(0); // Starts with 0 and goes to end
System.out.printin(substr);
String substr2 = s1.substring(5,10); // Starts from 5 and goes to 10
System.out.printin(substr2);
String substr3 = s1.substring(5,15); // Returns Exception
Prepared by: Raju Poudel [MCA] 69ont begin 5, end 15, length
concat()
You can concatenate two strings using concat( ), shown here:
String concat(String str)
This method creates a new object that contains the invoking string with the contents
of str appended to the end. concat( ) performs the same function as +. For example,
String s1 = "one";
String s2 = s1.concat("two");
puts the string “onetwo” into s2. It generates the same result as the following sequence:
String s1 = "one"
String s2 =s1 +"two";
replace!
The java string replace() method returns a string replacing all the old char or CharSequence
to new char or CharSequence.
There are two type of replace methods in java string.
1. replace(char oldChar, char newChar)
and
2. replace(CharSequence target, CharSequence replacement)
Java String replace(char old, char new) method example
public class ReplaceExample1{
public static void main(String argsf1){
String s1="javatpoint is a very good website"
String replaceString=s1.replace('a’,'e');//replaces all occurrences of 'a' to 'e!
System.out.printin(replaceString);
}
Output
Jevetpoint is © very good website
Java String replace(CharSequence target, CharSequence replacement) method example
public class ReplaceExample2{
public static void main(String aras{]){
String s1="my name is khan my name is java";
String replaceString=s1.replace("is","was");//replaces all occurrences of "is" to"
was"
System.out.printin(replaceString);
»
Output
my name was khan my name was java
Prepared by: Raju Poudel [MCA] 70trim
The java string trim() method eliminates leading and trailing spaces. The unicode value of
space character is '\u0020'. The trim() method in java string checks this unicode value
before and after the string, if it exists then removes the spaces and returns the omitted
string.
public class StringTrimExample {
public static void main(String[] args) {
String s1 =" hello java string";
System.out.printin(s1.length());
System.out.printin(s1); //Without trim()
String tr = si.trim();
System.out.printin(tr.length());
System.out.printin(tr); //With trim()
Output
22,
hello java string
uD
hello java string
String Buffer
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in
java is same as String class except it is mutable ie. it can be changed.
A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.
Important Constructors of StringBuffer class
Constructor Description
StringBuffer() creates an empty string buffer with the initial
capacity of 16.
StringBuffer(String str) creates a string buffer with the specified string.
StringBuffer(int creates an empty string buffer with the specified
capacity) capacity as length.
Prepared by: Raju Poudel [MCA] aImportant methods of StringBuffer class
Description
append(String s) is used to append the specified string with this string.
The append() method is overloaded like append(char),
append(boolean), append{(int), append(float),
append(double) etc.
insert(int offset, String s) | _ is used to insert the specified string with this string at
the specified position. The insert() method is overloaded
like insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
replace(int startindex, int | is used to replace the string from specified startIndex
endindex, String str) and endindex,
delete(int startindex, int is used to delete the string from specified startIndex and
endindex) endindex.
reverse() is used to reverse the string.
capacty() is used to return the current capacity.
ensureCapacity(int is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.
charat(int index} is used to return the character at the specified position.
length() is used to return the length of the string i.e. total
number of characters.
substring(int beginIndex) | is used to return the substring from the specified
beginIndex.
substring(int beginIndex, | is used to return the substring from the specified
int endIndex) beginIndex and endindex.
1) StringBuffer append() method
The append() method concatenates the given argument with this string.
class StringBufferExample{
publi main(String arasf]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.printin(sb);//prints Hello Java
+
Prepared by: Raju Poudel [MCA]2) StringBuffer insert() method
The insert() method inserts the given string with this string at the given position.
class StringButterExample2{
public static vold main(String argsf1}{
StringBuffer sb=new StringBuffer("Hello ");,
sb.insert(1,"Java");//now original string is changed
System.out.printin(sb);//prints HJavaello
+
3
3) StringBuffer replace() method
The replace() method replaces the given string from the specified beginindex and endindex.
class StringBufferExample3{
public static void main(String aras{1){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.printin(sb);//prints HJavalo
+
+
4) StringBuffer delete() and deleteCharAt() method
The delete|) method of StringBuffer class deletes the string from the specified beginindex to
endindex.
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.printin(sb);//prints Hlo
+
+
// Desonstrate delete() and deleteCharat ()
clase deleteDemo (
public static void main(String arga(]) (
sb.delete(4, 7)
Systen.out printin(*after delete: * + sb);
+s ab);
The following output is produced:
After delete: This a test.
After deleteCharAt: his a test.
Prepared by: Raju Poudel [MCA] 73