Svcet: Unit - 2
Svcet: Unit - 2
UNIT -2
2.1 Inheritance
Inheritance is the mechanism in java by which one class is allow to inherit the features
(fields and methods) of another class. It is process of deriving a new class from an existing
class. A class that is inherited is called a superclass and the class that does the inheriting is
called a subclass. Inheritance represents the IS-A relationship, also known as parent-child re-
lationship. The keyword used for inheritance is extends.
Syntax:
ET
class Subclass-name extends Superclass-name
{
//methods and fields
C
}
Here, the extends keyword indicates that we are creating a new class that derives from an
SV
existing class.
Note: The constructors of the superclass are never inherited by the subclass
Advantages of Inheritance:
• Code reusability - public methods of base class can be reused in derived classes
• Data hiding – private data of base class cannot be altered by derived class
• Overriding--With inheritance, we will be able to override the methods of the base
class in the derived class
Example:
// Create a superclass.
class BaseClass{
int a=10,b=20;
public void add(){
System.out.println(“Sum:”+(a+b));
}
}
// Create a subclass by extending class BaseClass.
public class Main extends BaseClass
{
public void sub(){
System.out.println(“Difference:”+(a-b));
}
public static void main(String[] args) {
Main obj=new Main();
/*The subclass has access to all public members of its superclass*/
obj.add();
ET
obj.sub();
}
}
C
Sample Output:
Sum:30
SV
Difference:-10
In this example, Main is the subclass and BaseClass is the superclass. Main object can
access the field of own class as well as of BaseClass class i.e. code reusability.
Types of inheritance
Single Inheritance :
In single inheritance, a subclass inherit the features of one superclass.
Example:
class Shape{
int a=10,b=20;
}
class Rectangle extends Shape{
public void rectArea(){
System.out.println(“Rectangle Area:”+(a*b));
}
}
public class Main
{
public static void main(String[] args) {
Rectangle obj=new Rectangle();
obj.rectArea();
}
}
ET
C
SV
Multilevel Inheritance:
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the
derived class also act as the base class to other class i.e. a derived class in turn acts as a base
class for another class.
Example:
class Numbers{
int a=10,b=20;
}
class Add2 extends Numbers{
int c=30;
public void sum2(){
System.out.println(“Sum of 2 nos.:”+(a+b));
}
}
class Add3 extends Add2{
public void sum3(){
ET
System.out.println(“Sum of 3 nos.:”+(a+b+c));
}
}
C
public class Main
{
SV
Example:
class Shape{
int a=10,b=20;
}
class Rectangle extends Shape{
public void rectArea(){
System.out.println(“Rectangle Area:”+(a*b));
}
}
class Triangle extends Shape{
public void triArea(){
System.out.println(“Triangle Area:”+(0.5*a*b));
ET
}
}
public class Main
C
{
public static void main(String[] args) {
SV
For example, Consider a class C derived from two base classes A and B. Class C inherits
A and B features. If A and B have a method with same signature, there will be ambiguity to
call method of A or B class. It will result in compile time error.
class A{
void msg(){System.out.println(“Class A”);}
}
class B{
void msg(){System.out.println(“Class B “);}
}
class C extends A,B{//suppose if it were
Public Static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
ET
}
}
Sample Output:
C
}
In this example since y is declared as private, it is only accessible by its own class mem-
bers. Subclasses have no access to it.
2.2 Using Super
The super keyword refers to immediate parent class object. Whenever you create the in-
stance of subclass, an instance of parent class is created implicitly which is referred by super
reference variable.
• It an be used to refer immediate parent class instance variable when both parent and
child class have member with same name
• It can be used to invoke immediate parent class method when child class has overridden
that method.
• super() can be used to invoke immediate parent class constructor.
Use of super with variables:
When both parent and child class have member with same name, we can use super key-
word to access mamber of parent class.
Example:
class SuperCls
{
int x = 20;
}
/* sub class SubCls extending SuperCls */
class SubCls extends SuperCls
{
int x = 80;
void display()
{
System.out.println(“Super Class x: “ + super.x); //print x of super class
ET
System.out.println(“Sub Class x: “ + x); //print x of subclass
}
}
C
/* Driver program to test */
class Main
SV
{
public static void main(String[] args)
{
SubCls obj = new SubCls();
obj.display();
}
}
Sample Output:
Super Class x: 20
Sub Class x: 80
In the above example, both base class and subclass have a member x. We could access x
of base class in sublcass using super keyword.
}
/* Driver program to test */
class Main
{
public static void main(String[] args)
{
SubCls obj = new SubCls();
obj.display();
}
}
Sample Output:
Sub Class x: 80
Super Class x: 20
In the above example, if we only call method display() then, the display() of sub class gets
invoked. But with the use of super keyword, display() of superclass could also be invoked.
Use of super with constructors:
The super keyword can also be used to invoke the parent class constructor.
Syntax:
super();
• super() if present, must always be the first statement executed inside a subclass
constructor.
• When we invoke a super() statement from within a subclass constructor, we are
invoking the immediate super class constructor
Example:
class SuperCls
{
ET
SuperCls(){
System.out.println(“In Super Constructor”);
}
C
}
/* sub class SubCls extending SuperCls */
SV
}
/* sub class B extending A */
class B extends A
{
B(){
super();
System.out.println(“B’s Constructor”);
}
}
/* sub class C extending B */
class C extends B{
C(){
super();
System.out.println(“C’s Constructor”);
}
}
/* Driver program to test */
class Main
{
public static void main(String[] args)
{
C obj = new C();
}
}
Sample Output:
ET
A’s Constructor
B’s Constructor
C’s Constructor
C
Invoking Superclass Parameterized Constructor
To call parameterized constructor of superclass, we must use the super keyword as shown
SV
below.
Syntax:
super(value);
Example:
class SuperCls{
int x;
SuperCls(int x){
this.x=x; // this refers to current invoking object
}
}
class SubCls extends SuperCls{
int y;
SubCls(int x,int y){
eterized constructor which accepts a integer value, and we used the super keyword to invoke
the parameterized constructor of the superclass.
2.4 The Object Class
The Object class is the parent class of all the classes in java by default (directly or indi-
rectly). The java.lang.Object class is the root of the class hierarchy. Some of the Object class
are Boolean, Math, Number, String etc.
Object
Some of the important methods defined in Object class are listed below.
Object class Methods Description
boolean equals(Object) Returns true if two references point to the same object.
String toString() Converts object to String
void notify()
void notifyAll() Used in synchronizing threads
void wait()
void finalize() Called just before an object is garbage collected
Returns a new object that are exactly the same as the current
Object clone()
object
int hashCode() Returns a hash code value for the object.
Example:
public class Test
{
ET
public static void main(String[] args)
{
/*hashcode is the unique number generated by JVM*/
C
Test t = new Test();
System.out.println(t);
SV
System.out.println(“end”);
}
protected void finalize() // finalize() is called just once on an object
{
System.out.println(“finalize method called”);
}
}
Sample Output:
Test@2a139a55
Test@2a139a55
705927765
end
finalize method called
In the above program, the default toString() method for class Object returns a string con-
sisting of the name of the class Test of which the object is an instance, the at-sign character
`@’, and the unsigned hexadecimal representation of the hash code of the object.
2.5 Abstract Classes And Methods
Abstract class
A class that is declared as abstract is known as abstract class. It can have abstract and
non-abstract methods (method with body). It needs to be extended and its method imple-
mented. It cannot be instantiated.
ET
Syntax:
abstract class classname
{
C
}
Abstract method
SV
A method that is declared as abstract and does not have implementation is known as ab-
stract method. The method body will be defined by its subclass.
Abstract method can never be final and static. Any class that extends an abstract class
must implement all the abstract methods declared by the super class.
Note:
A normal class (non-abstract class) cannot have abstract methods.
Syntax:
abstract returntype functionname (); //No definition
Syntax for abstract class and method:
modifier abstract class className
{
//declare fields
//declare methods
Now each animal must have a sound, by making this method abstract we made it compul-
sory to the child class to give implementation details to this method. This way we ensure that
every animal has a sound.
Rules
1. Abstract classes are not Interfaces.
2. An abstract class may have concrete (complete) methods.
3. An abstract class may or may not have an abstract method. But if any class has one or
more abstract methods, it must be compulsorily labeled abstract.
4. Abstract classes can have Constructors, Member variables and Normal methods.
5. Abstract classes are never instantiated.
6. For design purpose, a class can be declared abstract even if it does not contain any
abstract methods.
7. Reference of an abstract class can point to objects of its sub-classes thereby achieving
run-time polymorphism Ex: Shape obj = new Rectangle();
8. A class derived from the abstract class must implement all those methods that are
declared as abstract in the parent class.
9. If a child does not implement all the abstract methods of abstract parent class, then the
child class must need to be declared abstract as well.
Example 1
//abstract parent class
abstract class Animal
{
//abstract method
public abstract void sound();
}
//Lion class extends Animal class
public class Lion extends Animal
ET
{
public void sound()
{
C
System.out.println(“Roars”);
}
SV
Output:
Roars
In the above code, Animal is an abstract class and Lion is a concrete class.
Example 2
abstract class Bank
{
abstract int getRateOfInterest();
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
ET
class PNB extends Bank
{
int getRateOfInterest()
C
{
return 8;
SV
}
}
public class TestBank
{
public static void main(String args[])
{
Bank b=new SBI();//if object is PNB, method of PNB will be invoked
int interest=b.getRateOfInterest();
System.out.println(“Rate of Interest is: “+interest+” %”);
b=new PNB();
System.out.println(“Rate of Interest is: “+b.getRateOfInterest()+” %”);
}
}
Output:
Rate of Interest is: 7 %
Rate of Interest is: 8 %
Abstract class with concrete (normal) method
Abstract classes can also have normal methods with definitions, along with abstract
methods.
Sample Code:
abstract class A
{
abstract void callme();
public void normal()
{
System.out.println(“this is a normal (concrete) method.”);
ET
}
}
public class B extends A
C
{
void callme()
SV
{
System.out.println(“this is an callme (abstract) method.”);
}
public static void main(String[] args)
{
B b = new B();
b.callme();
b.normal();
}
}
Output:
this is an callme (abstract) method.
this is a normal (concrete) method.
{
SV
{
System.out.println(“ Within Derived fun()”);
}
}
public class Main
{
public static void main(String args[])
{
Derived d = new Derived();
}
}
Output:
Within Base Constructor
Within Derived Constructor
3. We can have an abstract class without any abstract method. This allows us to create
classes that cannot be instantiated, but can only be inherited.
Sample Code:
abstract class Base
{
void fun()
{
System.out.println(“Within Base fun()”);
}
}
class Derived extends Base
{
}
ET
public class Main
{
public static void main(String args[])
C
{
SV
The final keyword in java is used to restrict the user. The java final keyword can be ap-
plied to:
• variable
• method
• class
Java final variable - To prevent constant variables
Java final method - To prevent method overriding
Java final class - To prevent inheritance
Figure: Uses of final in java
Sample Code:
A final variable speedlimit is defined within a class Vehicle. When we try to change the
value of this variable, we get an error. This is due to the fact that the value of final variable
cannot be changed, once a value is assigned to it.
public class Vehicle
{
final int speedlimit=60;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
ET
Vehicle obj=new Vehicle();
obj.run();
}
C
}
Output:
SV
{
}
public static void main(String args[])
{
Vehicle obj=new Vehicle();
obj.run();
}
}
Output:
/Vehicle.java:3: error: variable speedlimit not initialized in the default constructor
final int speedlimit; //blank final variable
^
ET
1 error
Java Final Method
A Java method with the final keyword is called a final method and it cannot be overridden
in the subclass.
C
In general, final methods are faster than non-final methods because they are not required
to be resolved during run-time and they are bonded at compile time.
SV
Sample Code:
class XYZ
{
final void demo()
{
System.out.println(“XYZ Class Method”);
}
}
public class ABC extends XYZ
{
void demo()
{
Sample Code:
SV
class XYZ
{
final void demo()
{
System.out.println(“XYZ Class Method”);
}
}
public class ABC extends XYZ
{
public static void main(String args[])
{
{ {
OR
//code //code
} }
Sample Code:
final class XYZ
{
}
Output:
/ABC.java:5: error: cannot inherit from final XYZ
public class ABC extends XYZ
^
1 error
Important points on final in Java
• Final keyword can be applied to a member variable, local variable, method or class
in Java.
• Final member variable must be initialized at the time of declaration or inside the
constructor, failure to do so will result in compilation error.
• We cannot reassign value to a final variable in Java.
• The local final variable must be initialized during declaration.
• A final method cannot be overridden in Java.
• A final class cannot be inheritable in Java.
• Final is a different than finally keyword which is used to Exception handling in
Java.
• Final should not be confused with finalize() method which is declared in Object class
and called before an object is a garbage collected by JVM.
• All variable declared inside Java interface are implicitly final.
• Final and abstract are two opposite keyword and a final class cannot be abstract in
Java.
• Final methods are bonded during compile time also called static binding.
• Final variables which are not initialized during declaration are called blank final
variable and must be initialized in all constructor either explicitly or by calling
this(). Failure to do so compiler will complain as “final variable (name) might not be
initialized”.
• Making a class, method or variable final in Java helps to improve performance because
JVM gets an opportunity to make assumption and optimization.
ET
2.7 Interfaces
An interface is a reference type in Java. It is similar to class. It is a collection of abstract
methods. Along with abstract methods, an interface may also contain constants, default meth-
ods, static methods, and nested types. Method bodies exist only for default methods and static
C
methods.
An interface is similar to a class in the following ways:
SV
Syntax:
accessspecifier interface interfacename
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
When no access specifier is included, then default access results, and the interface is only
ET
available to other members of the package in which it is declared. When it is declared as pub-
lic, the interface can be used by any other code.
• The java file must have the same name as the interface.
• The methods that are declared have no bodies. They end with a semicolon after the
C
parameter list. They are abstract methods; there can be no default implementation of
any method specified within an interface.
SV
• Each class that includes an interface must implement all of the methods.
• Variables can be declared inside of interface declarations. They are implicitly final
and static, meaning they cannot be changed by the implementing class. They must
also be initialized.
• All methods and variables are implicitly public.
Sample Code:
The following code declares a simple interface Animal that contains two methods called
eat() and travel() that take no parameter.
/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}
Implementing an Interface
Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, the ‘implements’ clause is included in a class definition and then the
methods defined by the interface are created.
Syntax:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
Properties of java interface
• If a class implements more than one interface, the interfaces are separated with a
comma.
• If a class implements two interfaces that declare the same method, then the same
ET
method will be used by clients of either interface.
• The methods that implement an interface must be declared public.
• The type signature of the implementing method must match exactly the type signature
specified in the interface definition.
C
Rules
• A class can implement more than one interface at a time.
SV
• A class can extend only one class, but can implement many interfaces.
• An interface can extend another interface, in a similar way as a class can extend
another class.
Sample Code 1:
The following code implements an interface Animal shown earlier.
/* File name : MammalInt.java */
public class Mammal implements Animal
{
public void eat()
{
System.out.println(“Mammal eats”);
}
public void travel()
{
System.out.println(“Mammal travels”);
}
public int noOfLegs()
{
return 0;
}
public static void main(String args[])
{
Mammal m = new Mammal();
m.eat();
m.travel();
ET
}
}
Output:
C
Mammal eats
Mammal travels
SV
It is both permissible and common for classes that implement interfaces to define ad-
ditional members of their own. In the above code, Mammal class defines additional method
called noOfLegs().
Sample Code 2:
The following code initially defines an interface ‘Sample’ with two members. This inter-
face is implemented by a class named ‘testClass’.
import java.io.*;
// A simple interface
interface Sample
{
final String name = “Shree”;
void display();
}
Sample Code 3:
In this example, Drawable interface has only one method. Its implementation is provided
by Rectangle and Circle classes.
interface Drawable
{
void draw();
}
class Rectangle implements Drawable
{
public void draw()
{
System.out.println(“Drawing rectangle”);
}
}
class Circle implements Drawable
{
public void draw()
{
System.out.println(“Drawing circle”);
}
}
public class TestInterface
{
public static void main(String args[])
{
ET
Drawable d=new Circle();
d.draw();
}
C
}
Output:
SV
Drawing circle
Nested Interface
An interface can be declared as a member of a class or another interface. Such an inter-
face is called a member interface or a nested interface. A nested interface can be declared as
public, private, or protected.
Sample Code:
interface MyInterfaceA
{
void display();
interface MyInterfaceB
{
void myMethod();
}
}
public class NestedInterfaceDemo1 implements MyInterfaceA.MyInterfaceB
{
public void myMethod()
{
System.out.println(“Nested interface method”);
}
public static void main(String args[])
{
MyInterfaceA.MyInterfaceB obj= new NestedInterfaceDemo1();
obj.myMethod();
}
ET
}
Output:
Nested interface method
C
Differences between classes and interfaces
Both classes and Interfaces are used to create new reference types. A class is a collection
SV
of fields and methods that operate on fields. A class creates reference types and these refer-
ence types are used to create objects. A class has a signature and a body. The syntax of class
declaration is shown below:
class class_Name extends superclass implements interface_1,….interface_n
// class signature
{
//body of class.
}
Signature of a class has class’s name and information that tells whether the class has in-
herited another class. The body of a class has fields and methods that operate on those fields.
A Class is created using a keyword class.
When a class is instantiated, each object created contains a copy of fields and methods
with them. The fields and members declared inside a class can be static or nonstatic. Static
members value is constant for each object whereas, the non-static members are initialized by
each object differently according to its requirement.
Members of a class have access specifiers that decide the visibility and accessibility of
the members to the user or to the subclasses. The access specifiers are public, private and pro-
tected. A class can be inherited by another class using the access specifier which will decide
the visibility of members of a superclass (inherited class) in a subclass (inheriting class).
An interface has fully abstract methods (methods with nobody). An interface is syntacti-
cally similar to the class but there is a major difference between class and interface that is a
class can be instantiated, but an interface can never be instantiated.
An interface is used to create the reference types. The importance of an interface in Java
is that, a class can inherit only a single class. To circumvent this restriction, the designers of
Java introduced a concept of interface. An interface declaration is syntactically similar to a
class, but there is no field declaration in interface and the methods inside an interface do not
have any implementation. An interface is declared using a keyword interface.
Aspect for
Class Interface
comparison
An interface can never be instanti-
A class is instantiated to create
Basic
ET ated as the methods are unable to
objects.
perform any action on invoking.
Keyword class Interface
Access The members of a class can be The members of an interface are
specifier private, public or protected. always public.
C
The following example shows that a class that implements one interface:
public interface interface_example
{
public void method1();
public string method2();
}
public class class_name implements interface_example
{
public void method1()
{
..
}
ET
public string method2()
{
…
C
}
}
SV
interface I1 {}
interface I2 {}
class A
class B extends A implements I1, I2
{
}
Inheritance between two interfaces, is possible with the use of extends keyword only.
For example, in the following code, interface I2 extends the interface I1.
interface I1 { }
interface I2 extends I1{ }
2.8 Object cloning
Object cloning refers to creation of exact copy of an object. It creates a new instance of
ET
the class of current object and initializes all its fields with exactly the contents of the corre-
sponding fields of this object. In Java, there is no operator to create copy of an object. Unlike
C++, in Java, if we use assignment operator then it will create a copy of reference variable
and not the object. This can be explained by taking an example. Following program demon-
strates the same.
C
// Java program to demonstrate that assignment operator creates a new reference to same
object.
SV
import java.io.*;
class sample
{
int a;
float b;
sample()
{
a = 10;
b = 20;
}
}
class Mainclass
{
• Every class that implements clone() should call super.clone() to obtain the cloned
object reference.
• The class must also implement java.lang.Cloneable interface whose object clone
we want to create otherwise it will throw CloneNotSupportedException when clone
method is called on that class’s object.
• Syntax:
• protected Object clone() throws CloneNotSupportedException
import java.util.ArrayList;
class sample1
{
int a, b;
}
class sample2 implements Cloneable
{
int c;
int d;
sample1 s = new sample1();
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}
public class Mainclass
{
public static void main(String args[]) throws CloneNotSupportedException
{
ET
sample2 ob1 = new sample2();
ob1.c = 10;
ob1.d = 20;
C
ob1.s.a = 30;
ob1.s.b = 40;
SV
Shallow copy
Shallow copy is method of copying an object. It is the default in cloning. In this method
the fields of an old object ob1 are copied to the new object ob2. While copying the object type
field the reference is copied to ob2 i.e. object ob2 will point to same location as pointed out
by ob1. If the field value is a primitive type it copies the value of the primitive type. So, any
changes made in referenced objects will be reflected in other object.
Note:
Shallow copies are cheap and simple to make.
Deep Copy
To create a deep copy of object ob1 and place it in a new object ob2 then new copy of any
referenced objects fields are created and these references are placed in object ob2. This means any
changes made in referenced object fields in object ob1 or ob2 will be reflected only in that object
and not in the other. A deep copy copies all fields, and makes copies of dynamically allocated
memory pointed to by the fields. A deep copy occurs when an object is copied along with the
ET
objects to which it refers.
int a, b;
}
class Test2 implements Cloneable
{
int c, d;
Test ob1 = new Test();
public Object clone() throws CloneNotSupportedException
{
// Assign the shallow copy to new refernce variable t
Test2 t1 = (Test2)super.clone();
t1.ob1 = new Test();
// Create a new object for the field c
// and assign it to shallow copy obtained,
Type Description
Member Inner Class A class created within class and outside method.
Anonymous Inner Class A class created for implementing interface or extending class.
Its name is decided by the java compiler.
Method Local Inner Class A class created within method.
Static Nested Class A static class created within class.
Nested Interface An interface created within class or interface.
2.10 Inner Classes (Non-static Nested Classes)
Inner classes can be used as the security mechanism in Java. Normally, a class cannot be
related with the access specifier private. However if a class is defined as a member of other
class, then the inner class can be made private. This class can have access to the private mem-
bers of a class.
}
void print_inner() {
SV
• ArrayList is initialized by a size; however the size can increase if collection grows or
shrink if objects are removed from the collection.
• Java ArrayList allows us to randomly access the list.
• ArrayList cannot be used for primitive types, like int, char, etc.
• ArrayList in Java is much similar to vector in C++.
Java ArrayList class
Java ArrayList class extends AbstractList class which implements List interface. The List
interface extends Collection and Iterable interfaces in hierarchical order.
ET
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList
class and implements List interface.
The important points about Java ArrayList class are:
C
• Java ArrayList class can contain duplicate elements.
• Java ArrayList class maintains insertion order.
SV
a1.addAll(a2);
Iterator itr=a1.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
2.12 Java String
In general string is a sequence of characters. String is an object that represents a sequence
of characters. The java.lang.String class is used to create string object. In java, string is basi-
cally an object that represents sequence of char values. An array of characters works same as
java string. For example:
Java String class provides a lot of methods to perform operations on string such as com-
ET
pare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
The java.lang.String class implements Serializable, Comparable and CharSequence in-
terfaces. The CharSequence interface is used to represent sequence of characters. It is imple-
mented by String, StringBuffer and StringBuilder classes. It means can create string in java
C
by using these 3 classes.
The string objects can be created using two ways.
SV
1. By String literal
2. By new Keyword
String Literal
Java String literal is created by using double quotes. For Example:
1. 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 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”;
In the above example only one object will be created. Firstly JVM will not find any string
object with the value “Welcome” in string constant pool, so it will create a new object. After
that it will find the string with the value “Welcome” in the pool, it will not create new object
but will return the reference to the same instance. To make Java more memory efficient (be-
cause no new objects are created if it exists already in string constant pool).
2. by new keyword
String s=new String(“Welcome”);
In such case, JVM will create a new string object in normal (non pool) heap memory and
the literal “Welcome” will be placed in the string constant pool. The variable s will refer to
the object in heap (non pool).
The java String is immutable i.e. it cannot be changed. Whenever we change any string,
a new instance is created. For mutable string, you can use StringBuffer and StringBuilder
classes.
The following program explains the creation of strings
public class String_Example{
public static void main(String args[]){
String s1=”java”;
char c[]={‘s’,’t’,’r’,’i’,’n’,’g’};
ET
String s2=new String(c);
String s3=new String(“example”);
System.out.println(s1);
C
System.out.println(s2);
System.out.println(s3);
SV
}}
Java String class methods
The java.lang.String class provides many useful methods to perform operations on se-
quence of char values.
Method Description
char charAt(int index) returns char value for the particular index
int length() returns string length
static String format(String format, returns formatted string
Object... args)
static String format(Locale l, String returns formatted string with given locale
format, Object... args)
String substring(int beginIndex) returns substring for given begin index
String substring(int beginIndex, int returns substring for given begin index and
endIndex) end index
boolean contains(CharSequence s) returns true or false after matching the se-
quence of char value
s=s.concat(“ Programming”);
System.out.println(s);
}
}
Output:
Java Programming
ET
C
SV