Java Notes-Unit 3-New Syllabus
Java Notes-Unit 3-New Syllabus
JAVA PROGRAMMING
UNIT III NOTES
2. STRING HANDLING
2.1. Strings
2.2. String Array
2.3. String Buffer Class
COMPILED BY
Mrs.I.POONKODY., ASSISTANT PROFESSOR.,
NEW PRINCE SHRI BHAVANI ARTS AND SCIENCE COLLEGE
JAVA NOTES : UNIT – III (Page 2 of 26)
1.1)Defining A Class:
A class defines a user defined data type. This data type is then used to create objects of
thattype. Thus a class is a template for an object. The object is an instance of a class. A
class isdeclared using the keyword class. Generally a class consists of instance variables
and methods. The variables declared within a class are called instance variable. The
methods contain codes to access the instance variables of the class. The instance variables
and methods declared within a class are called members of the class.
Syntax:
Example:
class Rect
{
public double length;
public double breadth;
}
Syntax:
modifiers data_type method_name(parameter-list)
{
Method-body;
}
Example:
class Rect
{
double length;
double breadth;
void getvalues(int p,int q)
{
length=p;
breadth=q;
}
double area()
{
double ans=length*breadth;
return (ans);
}
}
Syntax:
Example:
class sample
{
public static void main(String args[]) throws IOException
{
Rect r = new Rect();
r.getvalues(2,3);
double result=r.area();
System.out.println(“Area of rectangle”+result);
}
}
Output:
Area of rectangle 6.0
JAVA NOTES : UNIT – III (Page 4 of 26)
1.2)Constructor:
A Constructor can be used to initialize the members of the class. It initializes the members
immediately upon creation.
Rules:
• A Constructor is having the same name as class name.
• It has no return type even void.
• Constructors are executed automatically immediately after the object is created.
Syntax:
class Class-name
{
Class-name( ) //constructor
{
}
}
Types of constructors:
1) Default Constructor
2) Parameterized Constructor
1) Default Constructor:
Constructors without argument are called default constructor. The default constructor
automatically initializes all instance variables to zero.
Example:
import java.io.*;
class Rect
{
int length,breadth;
Rect()
{
length=0;
breadth=0;
}
int area()
{
return(length*breadth);
}
}
In the above example, we have created a constructor with no arguments. The constructors
can be accessed as:
JAVA NOTES : UNIT – III (Page 5 of 26)
class test
{
public static void main(String args[])
{
Rect r1 = new Rect(); //Default Constructor
System.out.println(r1.area());
}
}
Output:
0
2) Parameterized Constructor:
Constructor with arguments are called parameterized constructor.
Example:
import java.io.*;
class Rect
{
int length,breadth;
Rect(int x, int y)
{
length=x;
breadth=y;
}
int area()
{
return(length*breadth);
}
}
In the above example, we have created a constructor with arguments. The constructors can
be accessed as:
class test
{
public static void main(String args[])
{
Rect r2 = new Rect(10,20); //parameterized Constructor
System.out.println(r2.area());
}
}
Output:
200
JAVA NOTES : UNIT – III (Page 6 of 26)
In the above example, we have created two constructors, one with no arguments and the
second with two arguments.The constructors can be accessed as
class test
{
public static void main(String args[])
{
Rect r1 = new Rect(); //Default Constructor
System.out.println(r1.area());
Rect r2 = new Rect(10,20); //parameterized Constructor
System.out.println(r2.area());
}
}
Output:
0
200
JAVA NOTES : UNIT – III (Page 7 of 26)
1,4)Method Overloading:
When two or more methods in the same class share the same name, but their parameter
declarations are different then the methods are said to be overloaded and the process is referred
to as method overloading. Java supports overloading. It is one of the ways that Java implements
the concept of polymorphism.
When an overloaded method is invoked, Java uses the type and/or number of arguments
as a guide to determine which version of the overloaded method to call. When Java
encounters a call to an overloaded method, it executes that version of the method whose
parameters match the arguments used in the call.
Example:
import java.io.*;
class addition
{
int sum;
void add(int x, int y)
{
sum=x+y;
System.out.println("Sum = "+sum);
}
void add(int x, int y, int z)
{
sum=x+y+z;
System.out.println("Sum = "+sum);
}
}
class Overload
{
public static void main(String args[])
{
addition ob = new addition();
ob.add(10,20);
ob.add(10,20,30);
}
JAVA NOTES : UNIT – III (Page 8 of 26)
Here we are overloading the method add(). In the main method there are two calls to the
add() method. First call is with two int values (10,20) so the first add() will be called and
then the second call has three int values (10,20,30) so the second add() will be called.
Output:
Sum=30
Sum=60
Advantage:
Increases the readability of the program.
1.5)Static Members:
➢ Static variables are used to create variables that is common to all instances of the
class.
➢ Java creates only one copy for a static variable which can be used even if the class is
not instantiated.
➢ Eg. static int count;
static int getdata(int x,int y);
➢ The static variables and methods can be called without using the object.
Rules:
• The static methods are called using class names.
• They can only call other static methods.
• They can only access static data.
• They cannot refer to ‘this’ or ‘super’ keyword.
Example:
import java.io.*;
class operation
{
static double mul(double x, double y)
{
return( x*y);
}
}
class test
{
public static void main (String args[])
{
System.out.println(operation.mul(3.2,2.2));
}
}
Output:
7.04
JAVA NOTES : UNIT – III (Page 9 of 26)
1.6)Nesting of methods:
A method that is called inside another method is called nesting of methods. Here the nested
method can be called directly without using an dot operator.
Example:
import java.io.*;
class nesting
{
int largest(int m,int n)
{
if (m>=n)
return(m);
else
return(n);
}
void display()
{
int lar=largest(40,50);
System.out.println(lar);
}
}
class test
{
public static void main (String args[])
{
nesting n = new nesting();
n.display();
}
}
Output:
50
Example:
class Rect2
{
int length,breadth;
void show(int length,int breadth)
{
this.length=length;
JAVA NOTES : UNIT – III (Page 10 of 26)
this.breadth=breadth;
}
}
class test
{
public static void main(String args[])
{
Rect2 r=new Rect2();
r.show(5,6);
}
}
Example:
import java.io.*;
class cmdpgm
{
void display(int x)
{
System.out.println("X="+x);
}
}
class test
{
public static void main(String arg[ ]) throws IOException
{
cmdpgm cp=new cmdpgm( );
int xx=Integer.parseInt(arg[0]);
cp.display(xx );
}
}
To Execute:
C:\>bca\Javaprogram>java test 20
In the above example value 20 is the data item passed to main( ) using the command line
arguments.
Output:
X=20
JAVA NOTES : UNIT – III (Page 11 of 26)
1.9)Inheritance:
Inheritance is a mechanism in which one object acquires all the properties and behaviours of
parent object. Inheritance represents the IS-A relationship, also known as parent child
relationship.
1) A class that is inherited is called a superclass or base class or parent class.
2) The class that does the inheriting is called a subclass or derived class or child class.
3) You can only specify one superclass for any subclass that you create. Java does not
support the inheritance of multiple super classes into a single subclass.
Advantages:
• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.
Syntax:
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.
Types of Inheritance:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
1. Single Inheritance:
When a class inherits from a single base class, it is known as single inheritance. It is the most
simplest form of Inheritance.
A Base class
B Derived class
Example:
import java.io.*;
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
JAVA NOTES : UNIT – III (Page 12 of 26)
Output:
barking...
eating...
2. Multilevel Inheritance:
In this type of inheritance the derived class inherits from a class, which in turn inherits from some
other class. The Super class for one, is a sub class for the other. The mechanism of deriving a class
from another derived class is known as multilevel inheritance.
A Base class
C Derived class
Example:
import java.io.*;
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
JAVA NOTES : UNIT – III (Page 13 of 26)
}
}
class Test
{
public static void main(String args[])
{
Puppy p=new Puppy();
p.weep();
p.bark();
p.eat();
}
}
Output:
weeping...
barking...
eating...
3. Hierarchical Inheritance:
The traits of one class may be inherited by more than one class is known as hierarchical inheritance.
It is a method of inheritance where one or more derived classes are derived from common base
class.
A Base class
C Derived classes
Example:
import java.io.*;
class Animal
{
JAVA NOTES : UNIT – III (Page 14 of 26)
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class Cat extends Animal
{
void meow()
{
System.out.println("meowing...");
}
}
class Test
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//Compile time.Error
}
}
Output:
meowing...
eating...
4. Multiple Inheritance:
Interfaces:
Java does not support multiple inheritances. Java provides an alternate approach known as
Interfaces to support the concept of multiple inheritance. Java class cannot be a subclass for
more than one superclass. It can implement more than one interfaces
Defining Interfaces:
An interface is basically a kind of class. Like classes, interface contain methods and variables
but with a major difference. The difference is that interface define only abstract and
final fields.
Syntax:
interface interface_name
{
Variable declarations;
Method declarations;
}
Example:
interface item
{
static final int code=100;
void display();
}
Extending Interfaces:
Like classes, interface can also be extended. The new sub-interface will inherit the members
of the super-interface. This is achieved by using the keyword extends.
Syntax:
JAVA NOTES : UNIT – III (Page 16 of 26)
Example :
interface itemconstants
{
int code=100;
string name=”Fan”;
}
interface itemmethods
{
void display();
}
Implementing Interfaces:
A class can extend only one other class but an interface can extend any number of interfaces.
When a class implements more than one interface, they are repeated by comma(,).
Syntax:
Example:
interface Writeable
{
void writes();
}
interface Readable
{
void reads();
}
Class test
{
public static void main(String args[])
{
Student s = new Student();
s.reads();
s.writes();
}
}
Output:
Student reads..
Student writes..
JAVA NOTES : UNIT – III (Page 18 of 26)
1.10)Method Overriding:
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.
Example:
import java.io.*;
class Bank
{
int getinterest()
{
return 0;
}
}
class SBI extends Bank
{
int getinterest()
{
return 8;
}
}
class AXIS extends Bank
{
int getinterest()
{
return 9;
}
}
class Test
{
public static void main(String args[])
{
SBI s=new SBI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getinterest());
JAVA NOTES : UNIT – III (Page 19 of 26)
Output:
SBI Rate of Interest: 8
AXIS Rate of Interest: 9
Class Interface
1) The members of a class can be constants The members of an interface are always
or variables. declared as constant.
2) The class definition can contain the code The methods in an interface has no code
for each if its methods. associated with them.
3) It can be instantiated by declaring It cannot be used to declare objects. It can
objects. only be inherited by a class.
4) It can use various access specifiers like It can only use the public access specifier.
public, private, protected, etc
1.13)Final Variable:
When a variable is declared final, its contents cannot be modified. You must initialise a final
variable at the time of its declaration.
Example :
final double PI = 3.14;
It is a common coding practice to use uppercase letters for variables declared as final.
1.14)Final Method:
Final method is used to prevent method overriding. To disallow a method from being
overridden, specify the final modifier at the start of the declaration of the method. This
means that methods declared as final cannot be overridden. Once a method has been declared
final in a class, its subclass cannot override it.
JAVA NOTES : UNIT – III (Page 20 of 26)
Example :
class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth() // ERROR! Can't override.
{
System.out.println("Illegal!");
}
}
Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do
so, a compile-time error will result.
1.15)Final classes:
A final class is used to prevent inheritance. If you want to prevent a class from being
inherited you precede the class declaration with the word final. When a class it declared
final, all of its methods are also implicitly declared final.
Example :
final class A
{
// ...
}
// The following class is illegal.
class B extends A // ERROR! Can't subclass A
{ // ...
}
It is illegal for B to inherit A since A is declared as final.
To add a finalizer to a class, you simply define the finalize() method.The java run time calls
that method whenever it is about to recycle an object of that class.
Example:
protected void finalize()
{
// finalization code here
JAVA NOTES : UNIT – III (Page 21 of 26)
}
Here, the keyword protected is a specifier that prevents access to finalize() by code defined
outside its class.
Rules:
1) Any class which contains one or more abstract methods must also be declared abstract.
2) There can be no object of an abstract class.
3) An abstract class cannot be instantiated with the new operator.
Example :
import java.io.*;
abstract class shape
{
abstract void draw();
}
class rectangle extends shape
{
void draw()
{
//method body
}
}
class test
{
public static void main(String args[])
{
shape s = new rectangle();
s.draw();
}
}
Types:
1) public
2) private
3) protected
4) friend
1) public specifier- The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the package.
JAVA NOTES : UNIT – III (Page 22 of 26)
Example:
public int n1,n2,n3;
2) private specifier- The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.
Example:
private double p,n,r;
3) protected specifier- The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
Example:
protected int x,y,z;
4) friend- The access level of a friend modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
Subclass in other
packages Y Y N N
Other classes in
other packages Y N N N
2.STRING HANDLING
2.1)Strings:
• Java string is a sequence of characters.
• They are objects of type String.
• Once a String object is created it cannot be changed.
• Strings are Immutable.
• The java.lang.String class is used to create a string object.
1) String Literal:
Java String literal is created by using double quotes. For Example:
String s="welcome";
2) By new keyword:
String s=new String("Welcome");
Example:
class StringDemo
{
public static void main(String args[])
{
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
Output:
hello.
Declaration:
String[] stringArray1 //Declaration of the String Array without specifying the size
String[] stringArray2 = new String[2]; //Declarartion by specifying the size
Initialization:
Below is the initialization of the String Array:
Output:
Ani
Sam
Joe
2.3)String methods:
s1.trim(); Removes white spaces at the String s1=new String(“ hello ”);
begining and end of the Output: hello
String s1