Java - Unit 2 - Stringbuffer

You might also like

You are on page 1of 100

Java Programming- Unit II

Classes

•class defines a new data type.


•Once defined, this new type can be used to
create objects of that type.

•A class is a template for an object,

•An object is an instance of a class.


General Form of a Class
class classname {
type instance-variable1;
type instance-variable2;

// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
Note: The data, or variables, defined within a class are called instance
variables. The code contained within methods. Collectively, the methods
and variables defined within a class arecalled members of the class.
Simple Class
class Box {
double width;
double height; 24 bytes –mybox width

double depth;
}

A class defines a new type of data. In this case, the new data type is called Box
create a Box object,
Box mybox = new Box(); // create a Box object called mybox

Creating an object contains its own copy of each instance variable defined by the
class.
Every Box object will contain its own copies of the instance variables width,
height, and depth. To access these variables, you will use the dot (.) operator.
The dot operator links the name of the object with the name of an instance
variable.
For Ex:
mybox.width = 100;
Simple Class - Example
class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box. Volume is 3000.0
public class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
Simple Class - Example
class Box {
double width;
double height;
double depth;
}
public class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box(); Volume is 3000.0
Box mybox2 = new Box(); Volume is 162.0
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's Note: mybox1’s data is completely
instance variables */
mybox2.width = 3; separate from the data contained in
mybox2.height = 6; mybox2
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}
Declaring Objects
Declare an object of type Box:
Box mybox = new Box();
or
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object

After firstline executes,mybox contains the value null, which indicates that
it does not yet point to an actual object
After the second line executes, mybox holds the memory address of the
actual Box object.
Assigning Object Reference Variables
Box b1 = new Box();
Box b2 = b1;

Any changes made to the object through b2 will affect the object to which b1 is referring, since they are
the same object.

After firstline executes,mybox contains the value null, which indicates that
it does not yet point to an actual object
After the second line executes, mybox holds the memory address of the
actual Box object.
Assigning Object Reference Variables
class Box {
double width;
double height;
double depth;
}
public class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = mybox1; Volume is 3000.0
double vol; Volume is 162.0
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);

mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is ― + vol);

}
}
Assigning Object Reference Variables
class Box {
double width;
double height; For example:
double depth;
}
Box b1 = new Box();
public class BoxDemo2 { Box b2 = b1;
public static void main(String args[]) {
Box mybox1 = new Box(); // ...
Box mybox2 = mybox1;
double vol;
b2 = null;
// assign values to mybox1's instance variables Here, b2 has been set to null,
mybox1.width = 10;
mybox1.height = 20; but b1 still points to the original
mybox1.depth = 15; object.
/* assign different values to mybox2's
instance variables */ Alhough b1 and b2 both refer to
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
the same object, they are not
linked in any other way.
mybox2.width = 3;
mybox2.height = 6; For example, a null assignment to
mybox2.depth = 9;
// compute volume of first box
b1 will simply unhook b1 from
vol = mybox1.width * mybox1.height * mybox1.depth; the original object
System.out.println("Volume is " + vol);
mybox2=null; without affecting the object or
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
affecting b2.
System.out.println("Volume is " + vol);

}
Volume is 3000.0
} Volume is 162.0
Volume is 162.0
Introducing Methods
classes consist of two things: instance variables and methods.

This is the general form of a method:


returntype name(parameter-list) {
// body of method
return value;
}

• type specifies the type of data returned by the method.


• If the method does not return a value, its return type must be void.
•The name of the method is specified by name.
•The parameter-list is a sequence of type and identifier pairs separated by commas.
•Parameters are essentially variables that receive the value of the arguments passed to the
method when it is called.
•If the method has no parameters, then the parameter list will be empty.
•Methods that have a return type other than void return a value to the calling routine using
•the following form of the return statement:
•return value;
•Here, value is the value returned.
Adding a Method to the Box Class
// This program includes a method inside the box class.
class Box {
double width;
double height;
double depth;
// display volume of a box
void volume() { Volume is 3000.0
System.out.print("Volume is ");
System.out.println(width * height * depth); Volume is 162.0
}
}
public class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// display volume of first box
mybox1.volume();
// display volume of second box
mybox2.volume();
}
}
Returning a Value
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
} Volume is 3000.0
}
class BoxDemo4 { Volume is 162.0
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Adding a Method That Takes Parameters
// This program uses a parameterized method.
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth; Volume is 3000.0
}
// sets dimensions of box Volume is 162.0
void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
}
public class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// initialize each box
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Constructors

•A constructor initializes an object immediately upon creation.


•It has the same name as the class in which it resides and is syntactically similar
to a method.
•The constructor is automatically called immediately after the object is created,
before the new operator completes.
•Constructors have no return type, not even void.
•This is because the implicit return type of a class’ constructor is the class type
itself.
•It is the constructor’s job to initialize the internal state of an object so that the
code creating an instance will have a fully initialized, usable object immediately
Constructors
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
Output
depth = 10; Constructing Box
}
// compute and return volume
Constructing Box
double volume() { Volume is 1000.0
return width * height * depth;
}
Volume is 1000.0
}
public class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Constructors - Example

class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
Output
depth = 10; Constructing Box
}
// compute and return volume
Constructing Box
double volume() { Volume is 1000.0
return width * height * depth;
}
Volume is 1000.0
}
class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Parameterized Constructors

class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
Output
} Volume is 3000.0
// compute and return volume
double volume() {
Volume is 162.0
return width * height * depth;
}
}
class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
1. AREA AND PERIMETER OF CIRCLE- Practicals

import java.io.*;
public class circle
{
public static void main(String args[]) throws IOException
{
double radius;
double area;
double perimeter;
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter the radius: ");
String t=in.readLine(); Output
radius= Double.parseDouble(t); Enter the radius: 4
area=3.14*radius*radius;
perimeter=2*3.14*radius;
Area of circle: 50.24
System.out.println("Area of circle: "+area); Perimeter of circle: 25.12
System.out.println("Perimeter of circle: "+perimeter);
}
}
this Keyword

•Sometimes a method need to refer to the object that invoked it.


•To allow this, Java defines the this keyword.
•this can be used inside any method to refer to the current object.
•this is always a reference to the object on which the method was
invoked.
•this is a reference to an object of the current class’ type is permitted
this Keyword

•Sometimes a method need to refer to the object that invoked it.


•To allow this, Java defines the this keyword.
•this can be used inside any method to refer to the current object.
•this is always a reference to the object on which the method was
invoked.
•this is a reference to an object of the current class’ type is permitted
Example
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
Instance Variable Hiding

when a local variable has the same name as an instance variable, the local
variable hides the instance variable.

this keyword resolves any name space collisions that might occur between
instance variables and local variables.

// Use this to resolve name-space collisions.


Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Garbage Collection

•Since objects are dynamically allocated by using the new


operator, how such objects are destroyed and their memory
released for later reallocation.
•Java de-allocates automatically.
•The technique that accomplishes this is called garbage
collection.
Note:There is no explicit need to destroy objects as in C++.
finalize method()

•If an an object needs to perform some action when it is


destroyed.
For example, if an object is holding some non-Java resource
such as a file handle and if programmer wants to make sure
these resources are freed before an object is destroyed.
•Java provides a mechanism called finalization
//The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
Specify those actions that must be performed before an object
is destroyed
Overloading Methods

• Java allows to define two or more methods within the same


class that share the same name, as long as their parameter
declarations are different.
• Methods are said to be overloaded, and the process is
referred to as method overloading.
• Method overloading is one of the ways that Java supports
polymorphism
• Overloaded methods must differ in the type and/or number of
their parameters.
• The return type alone is insufficient to distinguish two
versions of a method.
• When an overloaded method is invoked, Java uses the
type and/or number of arguments to determine which version
of the overloaded method to actually call.
Overloading Methods
// Demonstrate method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter. Output
void test(int a) {
System.out.println("a: " + a);
No parameters
} a: 10
// Overload test for two integer parameters.
void test(int a, int b) {
a and b: 10 20
System.out.println("a and b: " + a + " " + b); double a: 123.25
}
// overload test for a double parameter
Result of ob.test(123.25):
double test(double a) { 15190.5625
System.out.println("double a: " + a);
return a*a;
}
}
public class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Overloading Methods
// Automatic type conversions apply to overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for two integer parameters. Output
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
No parameters
} a and b: 10 20
// overload test for a double parameter
void test(double a) {
Inside test(double) a: 88
System.out.println("Inside test(double) a: " + a); Inside test(double) a: 123.2
}
}
public class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
ob.test();
ob.test(10, 20);
ob.test(i); // this will invoke test(double)
ob.test(123.2); // this will invoke test(double)
}
}

Note: this version of OverloadDemo does not define test(int). Therefore, when test( ) is called with an integer argument inside
Overload, no matching method is found. However, Java can automatically convert an integer into a double, and this
conversion can be used to resolve the call.
3. Overloading Methods - Practicals
class areaclass
{
void area()
{
int r=5;
System.out.println("The area of circle with radius 5 is :"+3.14*r*r);
}
void area(int a)
{
System.out.println("area of a circle with radius "+a+"is= "+3.14*a*a);
}
void area(int a,int b)
{
System.out.println("area of a rectangle with length and breadth:"+a+" "+b+"is "+a*b);
}
double area(double a,double b)
{
Output
return(1.0/2.0)*a*b; The area of circle with radius 5 is :78.5
}
} area of a circle with radius 10is= 314.0
public class overloadarea
{
area of a rectangle with length and
public static void main(String args[]) breadth:10 20is 200
{
areaclass ob=new areaclass(); area of triangle is :15.0
double result;
ob.area();
ob.area(10);
ob.area(10,20);
result= ob.area(5.0,6.0);
System.out.println("area of triangle is :"+result);
}
}
Overloading Constructors
public class OverloadCons {
class Box {
public static void main(String args[]) {
double width;
// create boxes using the various constructors
double height;
Box mybox1 = new Box(10, 20, 15);
double depth;
Box mybox2 = new Box();
// constructor used when all dimensions
Box mycube = new Box(7);
specified
double vol;
Box(double w, double h, double d) {
// get volume of first box
width = w;
vol = mybox1.volume();
height = h;
System.out.println("Volume of mybox1 is " + vol);
depth = d;
// get volume of second box
}
vol = mybox2.volume();
// constructor used when no dimensions
System.out.println("Volume of mybox2 is " + vol);
specified
// get volume of cube
Box() {
vol = mycube.volume();
width = -1; // use -1 to indicate
System.out.println("Volume of mycube is " + vol);
height = -1; // an uninitialized
}
depth = -1; // box
}
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume Output
double volume() { Volume of mybox1 is 3000.0
return width * height * depth; Volume of mybox2 is -1.0
}
} Volume of mycube is 343.0
Using Objects as Parameters

// Objects may be passed to methods.


class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o) {
Output
if(o.a == a && o.b == b) return true; ob1 == ob2: true
else return false; ob1 == ob3: false
}
}
public class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " +
ob1.equals(ob2));
System.out.println("ob1 == ob3: " +
ob1.equals(ob3));
}
Overloading Constructors
public class OverloadCons2 {
/ Here, Box allows one object to initialize another.
public static void main(String args[]) {
class Box {
// create boxes using the various constructors
double width;
Box mybox1 = new Box(10, 20, 15);
double height;
Box mybox2 = new Box();
double depth;
Box mycube = new Box(7);
// Notice this constructor. It takes an object of type Box.
Box myclone = new Box(mybox1); // create copy of mybox1
Box(Box ob) { // pass object to constructor
double vol;
width = ob.width;
// get volume of first box
height = ob.height;
vol = mybox1.volume();
depth = ob.depth;
System.out.println("Volume of mybox1 is " + vol);
}
// get volume of second box
// constructor used when all dimensions specified
vol = mybox2.volume();
Box(double w, double h, double d) {
System.out.println("Volume of mybox2 is " + vol);
width = w;
// get volume of cube
height = h;
vol = mycube.volume();
depth = d;
System.out.println("Volume of cube is " + vol);
}
// get volume of clone
// constructor used when no dimensions specified
vol = myclone.volume();
Box() {
System.out.println("Volume of clone is " + vol);
width = -1; // use -1 to indicate
}
height = -1; // an uninitialized
}
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len; } Output
// compute and return volume Volume of mybox1 is 3000.0
double volume() {
return width * height * depth;
Volume of mybox2 is -1.0
} Volume of cube is 343.0
} Volume of clone is 3000.0
Argument Passing

There are two ways to pass an argument to a subroutine.


• Call-by-Value - copies the value of an argument into the formal parameter of
the subroutine. Therefore, changes made to the parameter of the subroutine
have no effect on the argument.
• Call-by-Reference -a reference to an argument (not the value of the
argument) is passed to the parameter. Inside the subroutine, this reference is
used to access the actual argument specified in the call. This means that
changes made to the parameter will affect the argument used to call the
subroutine.

• In Java, when you pass a primitive type to a method, it is passed by


value. (argument has no effect outside the method. When you pass an
object to a method)

• The situation changes when objects are passed by what is effectively call-
by-reference. when a variable is created of a class type, a reference to
an object is created, the parameter that receives it will refer to the same
object as that referred to by the argument
Argument Passing

// Primitive types are passed by value. // Objects are passed by reference.


class Test { class Test {
void meth(int a, int b) {
int a, b; Ob, o– a 30
a30 Test(int i, int j) {
a*= 2; a = i; Output b 10
b /= 2; b 10 b = j;
} }
}
Ob // pass an object ob.a and ob.b before call: 15 20
a=15 void meth(Test o) {
class CallByValue {
o.a *= 2; ob.a and ob.b after call: 30 10
public static void main(String args[]) { b=20 o.b /= 2;
Test ob = new Test(); }
int a = 15, b = 20; }
System.out.println("a and b before call: " + class CallByRef {
public static void main(String args[]) {
a + " " + b);
Test ob = new Test(15, 20);
ob.meth(a, b); System.out.println("ob.a and ob.b before call: " +
System.out.println("a and b after call: " + ob.a + " " + ob.b);
a + " " + b); ob.meth(ob);
} System.out.println("ob.a and ob.b after call: " +
ob.a + " " + ob.b);
}
}
Output }
a and b before call: 15 20
a and b after call: 15 20
Returning Objects

A method can return any type of data, including class types that you create.
// Returning an object.
class Test {
int a; ob2 –
Test(int i) { a=12
a = i;
} Output
Test incrByTen() { Ob1 – a =2
Test temp = new Test(a+10); ob1.a: 2
return temp;
}
ob2.a: 12
} ob2.a after second increase: 22
class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: "
+ ob2.a);
}
}
Recursion

Amethod that calls itself is said to be recursive.


// A simple example of recursion.
class Factorial {
// this is a recursive method
int fact(int n) {
int result;
if(n==1) return 1; Output
result = fact(n-1) * n;
return result; Factorial of 3 is 6
}
}
Factorial of 4 is 24
class Recursion { Factorial of 5 is 120
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
Recursion

Amethod that calls itself is said to be recursive.


// Another example that uses recursion.
class RecTest {
int values[];
RecTest(int i) {
values = new int[i];
} Output
// display array -- recursively [0] 0
void printArray(int i) { [1] 1
if(i==0) return;
else printArray(i-1);
[2] 2
System.out.println("[" + (i-1) + "] " + values[i-1]); [3] 3
} [4] 4
} [5] 5
class Recursion2 {
public static void main(String args[]) {
[6] 6
RecTest ob = new RecTest(10); [7] 7
int i; [8] 8
for(i=0; i<10; i++) [9] 9
ob.values[i] = i;
ob.printArray(10);
}
}
Access Control

Java provides four types of access modifiers or visibility specifiers.


default, public, private, and protected

• protected applies only when inheritance is involved.


• When a member of a class is modified by the public specifier, then that member can be accessed by
any other code.
• When a member of a class is specified as private, then that member can only be accessed by other
members of its class
• All members of a class have used the default access mode, which is essentially public.
Access Control

/* This program demonstrates the difference between public and private.*/


class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) { // set c's value
c = i;
}
int getc() { // get c's value
return c;
}
}
class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " +
ob.b + " " + ob.getc());
}
}
static

Instance variables declared as static are, essentially, global variables. When objects of its class are
declared, no copy of a static variable is made. Instead, all instances of the class share the same static
variable.
class StaticDemo
Methods declared as static have several restrictions:
{
•They can only call other static methods. static int a = 42;
•They must only access static data. static int b = 99;
•They cannot refer to this or super in any way. static void callme()
class UseStatic {
System.out.println("a = " + a);
{ static int a = 3; Static block initialized. }
static int b; x = 42 }
static void meth(int x) a=3 class StaticByName
{ System.out.println("x = " + x); {
b = 12 public static void main(String args[])
System.out.println("a = " + a);
{StaticDemo.callme();
System.out.println("b = " + b); }
System.out.println("b = " + StaticDemo.b);
static }
{System.out.println("Static block initialized."); }
b = a * 4;
} a = 42
public static void main(String args[]) b = 99
{meth(42);
}
}
final

A variable can be declared as final. Doing so prevents its contents from being
final int YES = 1;
final int NO = 0;
final double PI =3.14;
Nested and Inner Classes

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.
• If class B is defined within class A, then B does not exist independently of A.
• A nested class has access to the members, including private members, of the
class in which it is nested.
• Enclosing class does not have access to the members of the nested class.
Nested and Inner Classes

// Demonstrate an inner class.


class Outer
{
int outer_x = 100;
void test()
{
Inner inner = new Inner(); Output
inner.display(); display: outer_x = 100
}
// this is an inner class
class Inner
{
void display()
{ System.out.println("display: outer_x = " + outer_x);
}
}
}
public class InnerClassDemo
{
public static void main(String args[])
{
Outer outer = new Outer();
outer.test();
}
}
Nested and Inner Classes

// This program will not compile.


class Outer
{ int outer_x = 100;
void test()
{ Inner inner = new Inner();
inner.display();
} Output
// this is an inner class display: outer_x = 100
class Inner
{
int y = 10; // y is local to Inner
void display()
{System.out.println("display: outer_x = " + outer_x);
}
}
void showy()
{ System.out.println(y); // error, y not known here!
}
}
public class InnerClassDemo
{ public static void main(String args[])
{
Outer outer = new Outer();
outer.test();
}
String

•An object of the String class represents a string of characters.


•The String class belongs to the java.lang package, which does not require an import
statement.
•Like other classes, String has constructors and methods.
•Unlike other classes, String has two operators, + and += (used for concatenation).
String

A string is a sequence of characters. Java implements strings as objects of type String.


String Constructors
String s = new String(); - will create an instance of String with no characters in it

String(char chars[ ]); - a String initialized by an array of characters


Ex : char chars[] = { 'a', 'b', 'c' };
String s = new String(chars)
This constructor initializes with the string ―abc‖

String(char chars[ ], int startIndex, int numChars) – start Index specifies the index at which
the subrange begins, and numChars specifies the number of characters to use
Ex : char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
This initializes with the characters ―cde‖

String(StringstrObj) - Construct a String object that contains the same character sequence
as another String object
String

// Construct one String from another.


class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'}; Output
Java
String s1 = new String(c);
Java
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
String

String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)

asciiChars specifies the array of bytes. The second form allows you to specify a subrange.

// Construct string from subset of char array.


class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 }; Output
String s1 = new String(ascii); ABCDEF
System.out.println(s1); CDE
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
Note : The contents of the array are copied whenever you create a String object from an
array. If you modify the contents of the array after you have created the string, the String
will be unchanged.
String - Immutability

•Once created, a string cannot be changed: none of its methods changes the
string.
•Such objects are called immutable.
•Immutable objects are convenient because several references can point to the
same object safely

String word1 = "Java";


String word1 = ―Java";
String word2 = word1;
String word2 = new String(word1);

word1 word1 ―Java"


―Java"
word2 ―Java"
word2
String – Immutability - Disadvantages

Less efficient — you need to create a new string and throw away the old one even for small
changes

String word = ―Java";


char ch = Character.toUpperCase(word.charAt (0));
word = ch + word.substring (1);

word ―java"

―Java"
String

 These methods are called using the dot notation:


String str1 = “Java”;
System.out.println(str1.length()); // 4
String

// index 012345678901
String s1 = “Java Program";
String s2 = “HERBERT";
System.out.println(s1.length()); // 12
System.out.println(s1.indexOf("e")); // g
System.out.println(s1.substring(7, 10)) // “ogr"
String s3 = s2.substring(2, 5);
System.out.println(s3.toLowerCase()); // “rbe"
String

 Methods like substring, toLowerCase, etc. create/return


a new string, rather than modifying the current string.
String s = “java";
s.toUpperCase();
System.out.println(s); // java

 To modify a variable, you must reassign it:


String s = “java";
s = s.toUpperCase();
System.out.println(s); // JAVA
String methods – Character extraction

char charAt(int where) - 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 thespecified location.

void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart) -


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 containsthe characters from sourceStart
through sourceEnd–1.

char[ ] toCharArray( ) - It returns an array of characters for the entire string.

byte[ ] getBytes( ) - getBytes( ) is most useful when you are exporting a


String value into an environment that does not support 16-bit Unicode
characters
String methods – Character extraction

public class Main


{
public static void main(String arg[])
{
String str = "Welcome to Java ";
char ch1 = str.charAt(5);
System.out.println(ch1);
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[10];
s.getChars(start, end, buf, 0);
System.out.println(buf);
char[] characters = str.toCharArray();
for (int i=0;i<characters.lenth;i++) {
System.out.print(characters[i]);
} Output
System.out.println(); m
byte[] bs = str.getBytes();
for (byte b: bs) { demo
System.out.print(b+" "); Welcome to Java
} 87 101 108 99 111 109 101 32 116 111 32 74
}
}
97 118 97 32
String methods – Comparison

String name = “Dr.Herbert”;


if (name.startsWith("Dr.")) {
System.out.println(“Dr”);
}
If(name.equals(“Dr.Herbert”)
{ System.out.println(“equal”);
}
if (name.equalsIgnoreCase(“Dr.HERBERT")) {
System.out.println(“Equal ignore");
}
String methods – Comparison

boolean regionMatches(int startIndex, String str2, int


str2StartIndex, int numChars)
boolean regionMatches(boolean ignoreCase,int startIndex, String
str2,int str2StartIndex, int numChars)
startIndex specifies the index at which the region begins within the
invoking String object. The String being compared is specified by str2. The
index at which the comparison will start within str2 is specified by
str2StartIndex. The length of the substring being compared is passed in
numChars. In the second version, if ignoreCase is true, the case of the
characters is ignored. Otherwise, case is significant.
String methods – Comparison

boolean regionMatches(int startIndex, String str2, int


str2StartIndex, int numChars)
boolean regionMatches(boolean ignoreCase,int startIndex, String
str2,int str2StartIndex, int numChars)
startIndex specifies the index at which the region begins within the
invoking String object. The String being compared is specified by str2. The
index at which the comparison will start within str2 is specified by
str2StartIndex. The length of the substring being compared is passed in
numChars. In the second version, if ignoreCase is true, the case of the
characters is ignored. Otherwise, case is significant.
compareTo(String str) - Compares two strings lexicographically
compareToIgnoreCase(String str)- Compares two strings lexicographically,
ignoring case differences

Value Meaning
Less than zero The invoking string is less than str.
Greater than zero The invoking string is greater than str.
Zero The two strings are equal.
String methods – Comparison

boolean regionMatches(int startIndex, String str2, int


str2StartIndex, int numChars)
boolean regionMatches(boolean ignoreCase,int startIndex, String
str2,int str2StartIndex, int numChars)
startIndex specifies the index at which the region begins within the
invoking String object. The String being compared is specified by str2. The
index at which the comparison will start within str2 is specified by
str2StartIndex. The length of the substring being compared is passed in
numChars. In the second version, if ignoreCase is true, the case of the
characters is ignored. Otherwise, case is significant.
compareTo(String str) - Compares two strings lexicographically
compareToIgnoreCase(String str)- Compares two strings lexicographically,
ignoring case differences

Value Meaning
Less than zero The invoking string is less than str.
Greater than zero The invoking string is greater than str.
Zero The two strings are equal.
String methods – Comparison

class strcomparison
{
public static void main(String args[]){
String s1="Sita";
String s2="Sita";
String s3="Ram";
String s4="Hello World";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s4.regionMatches(6, "world", 0, 4));//false
System.out.println(s4.regionMatches(true, 6, "world", 0,
4));//true
}
}
String methods

String concat(String)
String trim()
String replace(char original,char replacement)
static String valueOf(double num) “10.45”
static String valueOf(long num)
static String valueOf(char chars[])
static String valueOf(char chars[],int startindex,int numchars)
static String valueOf(Object ob)
14.Program for string manipulation.

import java.io.*;
class strmanp else if (Character.isDigit(ch))
{ digits++;
public static void main(String[] args) throws else if (Character.isWhitespace(ch))
IOException { blanks++;
else
String str; spchar++;
int vowels=0, digits=0, blanks=0, cons=0, }
spchar=0; System.out.println("Vowels : " + vowels);
char ch; System.out.println("Constants : " +
DataInputStream inp=new cons);
DataInputStream(System.in); System.out.println("Digits : " + digits);
System.out.print("Enter a string : "); System.out.println("Blanks : " + blanks);
str=inp.readLine(); System.out.println("Special Character :
for(int i=0;i<str.length();i++) " + spchar);
{ }
ch=str.charAt(i); }
if(ch=='a' || ch=='A' || ch=='e' || ch=='E' ||
ch=='i' || ch=='I' || ch=='o' || ch=='O' || ch=='u'
|| ch=='U')
vowels++;
else if (Character.isLetter(ch))
cons++;
Command-Line Arguments

Sometimes we want to pass information into a program when you run it. A command-line
argument is the information that directly follows the program’s name on the command
line when it is executed.
To access the command-line arguments inside a Java program is quite easy— they are
stored as strings in a String array passed to the args parameter of main( ). The first
command-line argument is stored at args[0], the second at args[1], and so on.

// Display all command-line arguments.


class CommandLine {
public static void main(String args[])
{
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}
StringBuffer

• A StringBuffer is like a String, but can be modified.


• The length and content of the StringBuffer sequence can be
changed through certain method calls.
• StringBuffer defines three constructors:

– StringBuffer()
– StringBuffer(int size)
– StringBuffer(String str)

string
StringBuffer Operations
• length - Returns the length of this string buffer.
int length()

• setLength - Sets the length of the StringBuffer.


void setLength(int newLength)

• capacity - Returns the current capacity of the String buffer. The capacity is
the amount of storage available for newly inserted characters. (16 additional
character is added automatically)
int capacity()

• Ensurecapacity - Preallocate space for a certain number of characters after


a StringBuffer has been constructed. (to set the size of the buffer)
void ensurecapacity(int capacity)

string
StringBuffer Operations
• charAt - -charAt( ) returns the character at the specified location(index).
char charAt(int index)

• setCharAt - sets the character at the specified location.(index)


char charAt(int index)

• getChars – copy a substring of a StringBuffer into an array


void getChars(int startindex, int endindex, char
target[], int targetstartindex)

string
StringBuffer Operations

• The principal operations on a StringBuffer are the append and


insert methods, which are overloaded so as to accept data of
any type.

Here are few append methods:


StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Oject obj)

• The append method concatenates the stringat the end of the


buffer.

string
StringBuffer Operations

• Insert method adds the characters at a specified point.

Here are few insert methods:


StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)

Index specifies at which point the string will be inserted into


the invoking StringBuffer object.

string
StringBuffer Operations

• reverse() - The character sequence contained in this


string buffer is replaced by the reverse of the sequence.
public StringBuffer reverse()

string
StringBuffer Operations

• delete() - Removes the characters in a substring of this


StringBuffer. The substring begins at the specified start
and extends to the character at index end - 1 or to the
end of the StringBuffer if no such character exists. If start
is equal to end, no changes are made.

StringBuffer delete(int startindex, int endindex)


StringBuffer deleteCharAt(int loc)

string
StringBuffer Operations

• replace() - Replaces the characters in a substring of this


StringBuffer with characters in the specified String.
StringBuffer replace(int startindex, int endindex,
String str)

• substring() - Returns a new String that contains a


subsequence of characters currently contained in this
StringBuffer. The substring begins at the specified index
and extends to the end of the StringBuffer.
String substring(int startindex)
String substring(int startindex, int endindex)
string
StringBuffer Operations

• replace() - Replaces the characters in a substring of this


StringBuffer with characters in the specified String.
StringBuffer replace(int startindex, int endindex,
String str)

• substring() - Returns a new String that contains a


subsequence of characters currently contained in this
StringBuffer. The substring begins at the specified index
and extends to the end of the StringBuffer.
String substring(int startindex)
String substring(int startindex, int endindex)
string
Example- StringBuffer
import java.io.*; while(i<=strlen)

Class Substr {

{ public static void main(String arg[]) throws temp=str.substring(i,i+substrlen);

Exception Enter the string :


if(temp.equals(substr))
hello world
Enter the substring to be removed {
{ StringBuffer str; hello
world str.delete(i,i+substrlen);
String substr,temp; number of substring removed 1
strlen=strlen-substrlen;
int strlen,i=0,ctr=0, substrlen;
ctr++;
DataInputStream din=new }
DataInputStream(System.in); else
System.out.println("Enter the string : "); {
str=new StringBuffer(din.readLine()); i=i+1;

System.out.println("Enter the substring to be }

removed"); }
System.out.println(str);
substr=din.readLine();
System.out.println("number of substring
strlen=str.length();
removed "+ ctr);
substrlen=substr.length();
}
strlen=strlen-substrlen; }
Wrapper Classes

The java.lang package contains wrapper classes that correspond to each primitive
type.
This makes it possible to have class types that behave somewhat like primitive types.
Wrapper classes also contain a number of useful predefined constants and static
methods Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
void Void
Wrapper Classes

The following declaration creates an Integer object which represents the integer 40
as an object
Integer age = new Integer(40);

An object of a wrapper class can be used in any situation where a primitive value will
not suffice

For example, some objects serve as containers of other objects

Primitive values could not be stored in such containers, but wrapper objects could be
Wrapper Classes

Wrapper classes also contain static methods that help manage the associated type
For example, the Integer class contains a method to convert an integer stored in a
String to an int value:

num = Integer.parseInt(str);

The wrapper classes often contain useful constants as well


For example, the Integer class contains MIN_VALUE and MAX_VALUE which hold
the smallest and largest int values
Autoboxing

Autoboxing is the automatic conversion of a primitive value to a corresponding


wrapper object:
Integer obj;
int num = 42;
obj = num;

The assignment creates the appropriate Integer object

The reverse conversion (called unboxing) also occurs automatically as needed


Inheritance

A class that is inherited is called a superclass. The class that does the inheriting is called
a subclass. Therefore, a subclass is a specialized version of a superclass.
It inherits all of theinstance variables and methods defined by the superclass and adds its
own, unique elements.
Terminology

Inheritance is a fundamental Object Oriented concept

A class can be defined as a "subclass" of another class.


The subclass inherits all data attributes of its superclass
The subclass inherits all methods of its superclass
The subclass inherits all associations of its superclass

The subclass can: superclass: Person


Add new functionality - name: String
Use inherited functionality - dob: Date

Override inherited functionality

subclass: Employee
- employeeID: int
- salary: int
- startDate: Date
What really happens?

When an object is created using new, the system must allocate enough
memory to hold all its instance variables.
This includes any inherited instance variables

In this example, we can say that an Employee "is a kind of" Person.
An Employee object inherits all of the attributes, methods and
associations of Person

Person
- name: String
Person
- dob: Date
name = "John
Smith"
dob = Jan 13, 1954 Employee
is a kind of name = "Sally Halls"
Employee dob = Mar 15, 1968
- employeeID: int employeeID = 37518
- salary: int salary = 65000
- startDate: Date startDate = Dec 15,
2000
Inheritance in Java

Inheritance is declared using the "extends" keyword


If inheritance is not defined, the class extends a class called Object

public class Person Person


{ - name: String
private String name; - dob: Date
private Date dob;
[...]

public class Employee extends Person


Employee
{
- employeeID: int
private int employeID;
- salary: int
private int salary;
- startDate: Date
private Date startDate;
[...]

Employee anEmployee = new Employee();


Inheritance Hierarchy

Each Java class has one (and only one) superclass.


C++ allows for multiple inheritance

Inheritance creates a class hierarchy


Classes higher in the hierarchy are more general and more abstract
Classes lower in the hierarchy are more specific and concrete

There is no limit to the number of Class


subclasses a class can have
Class Class Class
There is no limit to the depth of the
class tree.
Class Class Class

Class
The class called Object

At the very top of the inheritance tree is a class called Object

All Java classes inherit from Object.


All objects have a common ancestor
This is different from C++

The Object class is defined in the java.lang package


Examine it in the Java API Specification

Object
Constructors and Initialization

Classes use constructors to initialize instance variables


When a subclass object is created, its constructor is called.
It is the responsibility of the subclass constructor to invoke the
appropriate superclass constructors so that the instance variables
defined in the superclass are properly initialized

Superclass constructors can be called using the "super" keyword in a


manner similar to "this"
It must be the first line of code in the constructor

If a call to super is not made, the system will automatically attempt to


invoke the no-argument constructor of the superclass.
Constructors - Example
public class BankAccount
{
private String ownersName;
private int accountNumber;
private float balance;

public BankAccount(int anAccountNumber, String aName)


{
accountNumber = anAccountNumber;
ownersName = aName;
}
[...]
}

public class OverdraftAccount extends BankAccount


{
private float overdraftLimit;

public OverdraftAccount(int anAccountNumber, String aName, float aLimit)


{
super(anAccountNumber, aName);
overdraftLimit = aLimit;
}
}
Method Overriding

Subclasses inherit all methods from their superclass


Sometimes, the implementation of the method in the superclass does not
provide the functionality required by the subclass.
In these cases, the method must be overridden.

To override a method, provide an implementation in the subclass.


The method in the subclass MUST have the exact same signature as the
method it is overriding.
Method overriding - Example
public class BankAccount
{
private String ownersName;
private int accountNumber;
protected float balance;

public void deposit(float anAmount)


{
if (anAmount>0.0)
balance = balance + anAmount;
}

public void withdraw(float anAmount)


{
if ((anAmount>0.0) && (balance>anAmount))
balance = balance - anAmount;
}

public float getBalance()


{
return balance;
}
}
Method overriding - Example

public class OverdraftAccount extends BankAccount


{
private float limit;

public void withdraw(float anAmount)


{
if ((anAmount>0.0) && (getBalance()+limit>anAmount))
balance = balance - anAmount;
}

}
Object References and Inheritance

Inheritance defines "a kind of" relationship.


In the previous example, OverdraftAccount "is a kind of" BankAccount

Because of this relationship, programmers can "substitute" object


references.
A superclass reference can refer to an instance of the superclass OR an
instance of ANY class which inherits from the superclass.

BankAccount anAccount = new BankAccount(123456, "Craig");

BankAccount account1 = new OverdraftAccount(3323, "John", 1000.0);

BankAccount
anAccount
name = "Craig"
accountNumber = 123456
OverdraftAccount
name = "John"
account1 accountNumber = 3323
limit = 1000.0
Polymorphism

In the previous slide, the two variables are defined to have the same type
at compile time: BankAccount
However, the types of objects they are referring to at runtime are
different

What happens when the withdraw method is invoked on each object?


anAccount refers to an instance of BankAccount. Therefore, the
withdraw method defined in BankAccount is invoked.
account1 refers to an instance of OverdraftAccount. Therefore, the
withdraw method defined in OverdraftAccount is invoked.

Polymorphism is: The method being invoked on an object is determined AT


RUNTIME and is based on the type of the object receiving the message.
Final Methods and Final Classes

Methods can be qualified with the final modifier


Final methods cannot be overridden.
This can be useful for security purposes.

public final boolean validatePassword(String username, String Password)


{
[...]

Classes can be qualified with the final modifier


The class cannot be extended
This can be used to improve performance. Because there an be no
subclasses, there will be no polymorphic overhead at runtime.

public final class Color


{
[...]
Review

What is inheritance? What is a superclass? What is a subclass?


Which class is at the top of the class hierarchy in Java?
What are the constructor issues surrounding inheritance?
What is method overriding? What is polymorphism? How are they related?
What is a final method? What is a final class?

You might also like