0% found this document useful (0 votes)
37 views48 pages

OOPS

oops concept

Uploaded by

Rishitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views48 pages

OOPS

oops concept

Uploaded by

Rishitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

21CSE46A - Object Oriented Programming

MODULE 2
I/O Basics & Files: Reading input, writing output - Scanner class, Buffered Reader class,
Reading and Writing files. Constructors: Visibility modifiers, Methods and Objects,
Inbuilt classes like String, Character, String Buffer, ‘this’ reference, nested classes.
What is File I/O?
Java I/O stream is the flow of data that you can either read from, or you can write to. It is
used to perform read and write operations in file permanently. Java uses streams to perform
these tasks. Java I/O stream is also called File Handling, or File I/O. It is available in
java.io package.

Java.io package provides classes for system input and output through files, network streams,
memory buffers, etc.

Some input-output
stream will be initialized automatically by the JVM and these streams are available in
System class as
1) System.out: standard output stream
2) System.in: standard input stream
3) System.ewrr: standard error stream
Streams
Streams are the sequence of bits(data).
There are two types of streams:
• Input Streams

• Output Streams
Input Streams:
Input streams are used to read the data from various input devices like keyboard, file,
network, etc.

Output Streams:
Output streams are used to write the data to various output devices like monitor, file, network,
etc.
Streams based on data
There are two types of streams based on data:
• Byte Stream: used to read or write byte data.

• Character Stream: used to read or write character data.

Byte Input Stream:


• These are used to read byte data from various input devices.
• InputStream is an abstract class and it is the super class of all the input byte
streams.
List of Byte Input Streams:

Byte Output Stream:


• These are used to write byte data to various output devices.
• Output Stream is an abstract class and it is the superclass for all the output byte
streams.
List of Byte Output Streams:
Character Input Stream:
• These are used to read char data from various input devices.
• Readeris an abstract class and is the super class for all the character input
streams.
List of Character Input Streams:

Character Output Stream:


• These are used to write char data to various output devices.
• Writeris an abstract class and is the super class of all the character output
streams.
List of Character Output Stream:
Example to read contents of file:
Example 1:
import java.io.*;
class ReadHello{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream(“hello.txt”);
int i=0;
while((i=fin.read())!=-1){
System.out.println((char)i);
}
fin.close();
} catch(Exception e){
system.out.println(e);}
}
}
}
Refer write file example to see contents of
hello.txt Output:
Hello Intellipaat
Example 2:
import java.io.*;
public class ReadFileDemo {
public static void main(String[] args) {
BufferedReader br = null;
BufferedReader br2 = null;
try{
br = new BufferedReader(new FileReader(“B:\\myfile.txt”));
String contentLine = br.readLine();
while (contentLine != null) {
System.out.println(contentLine);
contentLine = br.readLine();}
}
catch (IOException ioe)
{
ioe.printStackTrace();}
}
Output:
Now you know how to create & read
Example to write in a file:
Example 1:
import java.io.*;
public class Intellipaat{
public static void main(String args[]){
try{
FileOutputstream fo=new
FileOutputStream(“hello.txt”); String i=”Hello
Intellipaat “;
byte b[]=i.getBytes();/ /converting string into byte
array fo.write(i);
fo.close();
}
catch(Exception e){
system.out.println(e);}
}
}
This will create a file hello.txt
Output:
Hello Intellipaat
Example 2:
import java.io.*;
public class writeIntellipaatFirst{
public static void main(String args[]){
File file=new File(“visiters.txt”);
try{
PrintWriter output=new PrintWriter(file);
output.println(“Hello Visiters! Welcome to Intellipaat”);
output.close();
} catch(IOException ex){ System.out.println(“Error:”+ex);}
}
}

Java Input
We know that taking data inputs are important parts of a computer program. Sometimes our
application will need to read input data from keyboard. Java provides classes in the packages
such as java.lang, java.io and java.util to facilitate accepting data inputs. Several techniques
are there.
1. Using Command Line Arguments
We can take keyboard input using command line arguments. In the given addition example,
we are expecting two input values.

The first input is denoted as “args[0]” and the first input is denoted as “args[1]“. Since, both
of them are String values; we need to convert them into integer values for calculating the
sum. The Double class belongs to the java.lang package; so, we don’t have to import
anything. See the code below.
CommandLine.java
public class CommandLine {

public static void main(String[] args) {

int n = args.length;
int sum;

if (n < 2) {
System.out.println("INPUT ERROR!");
System.exit(0);
}
else {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
sum = a + b;
System.out.println("SUM = " + sum);
}

}
Output:
C:\testing>java CommandLine 20 30
SUM = 50
2. Using System class
We can also accept keyboard input using the java.lang.System class. It is a very useful
technique when we don’t have support for packages like java.io or java.util. Here, we are
taking as input one character value (stored in variable in ch) at a time. Subsequently, we are
appending this character value to the string named “str“. When we press ‘@‘ symbol, the
input taking is stopped. If everything goes fine, the string value will be converted to a
decimal number and finally be displayed.
As System.in.read() method has an exception associated with it, we have declared Exception
class in the main() method signature.
Since the classes System and Double belong to the java.lang package, we don’t have to
import anything. See the program below.
SimpleInput.java
public class SimpleInput {

public static void main(String[] args) throws Exception {


char ch;
String str = "";

System.out.println("Enter a decimal number (press '@' to quit): ");


while( (ch=(char)System.in.read()) != '@') {
str += ch;
}

double num = Double.parseDouble(str);


System.out.println("Number = " + num);
}

}
Output:
C:\testing>java SimpleInput
Enter a decimal number (press '@' to quit):
1234.75@
Number = 1234.75

3. Using BufferedReader class


We may also use java.io.BufferedReader class for keyboard input. Within the object of
BufferedReader class, we have to wrap the object of java.io.InputStreamReader class; as
because this class has a direct connection with the keyboard (i.e System.in). This technique
was very popular in Java 2, before the introduction of Scanner class. As the readLine()
method of BufferedReader has an exception (java.io.IOException) associated with it, we have
to declare this exception in the main() method signature. See it below.
Java2Input.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Java2Input {


public static void main(String[] args) throws IOException {

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter two decimal numbers: ");
double a = Double.parseDouble(input.readLine());
double b = Double.parseDouble(input.readLine());
double sum = a + b;
System.out.println("SUM = " + sum);

}
Output:
C:\testing>java ConsoleTest
Enter two decimal numbers:
24.35
33.40
SUM = 57.75

4. Using Scanner class


We can take keyboard input using java.util.Scanner class. This technique is very popular
among the programmers since its introduction with Java SE 5. See the program below.
ScannerTest.java
import java.util.Scanner;

public class ScannerTest {

public static void main(String[] args) {

// Creating object
Scanner sc = new Scanner(System.in);

System.out.println("Enter an integer: ");


int i = sc.nextInt();
System.out.println("Enter a word: ");
String s = sc.next();
System.out.println("Enter a boolean: ");
boolean b = sc.nextBoolean();
System.out.println("Enter a sentence: ");
// Creating a new object of Scanner is a must for a sentence
String str = new Scanner(System.in).nextLine();
System.out.println("Enter a decimal no: ");
double d = sc.nextDouble();

System.out.println("\nDisplay values: ");


System.out.println("i = " + i);
System.out.println("s = " + s);
System.out.println("b = " + b);
System.out.println("str = " + str);
System.out.println("d = " + d);

}
Output:
C:\testing>java ScannerTest
Enter an integer:
12
Enter a word:
Delhi
Enter a boolean:
true
Enter a sentence:
Java programming is a fun!
Enter a decimal no:
23.75

Display values:
i = 12
s = Delhi
b = true
str = Java programming is a fun!
d = 23.75
NOTE: With this technique, creating a new object of Scanner is a must for inputting a
sentence. Otherwise, that input taking task will be skipped to the next one.

5. Using Console class


We may accept keyboard input using java.io.Console class. This class has been introduced in
Java since JSE 6.
Here, we use the console() method of System class to create an object of Console class. See it
below.
ConsoleTest.java
import java.io.Console;

public class ConsoleTest {

public static void main(String[] args) {

Console cs = System.console();
System.out.println("Enter two decimal numbers: ");
double a = Double.parseDouble(cs.readLine());
double b = Double.parseDouble(cs.readLine());
double sum = a + b;
System.out.println("SUM = " + sum);
}

}
Output:
C:\testing>java ConsoleTest
Enter two decimal numbers:
24.35
33.40
SUM = 57.75
Java Output
We know that displaying variables is an important part of a computer program. Our Java
application can display the output data to the monitor using the standard output stream named
System.out.
In Java, we mostly use the System.out.print() and System.out.println() methods to display the
output data.
With print() method, the cursor stays at the same line; while with println(), the cursor moves
to the next line.
But, using these two methods, it is really difficult to format the output data according to the
requirements of programs.

That is why we may want to use the System.out.printf() method for getting the formatted
output like what we did in C programming.

An Example
This example illustrates the difference between println() and printf() methods.

Let us suppose we have been asked to perform the summation of the following series up
to two-decimal places:
S = 1 + 1/2 + 1/3 + · · · · · · · · · · + 1/n

The code solving the above programming problem is given below.


Series.java
public class Series {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


System.out.println("Enter the limit: ");
int a = sc.nextInt();
double t, sum = 0.0;
for (int i = 1; i <= a; i++) {
t = 1.0/(double)i;
sum += t;
}
// Displaying the result
System.out.println("The sum is: " + sum);

}
Output:
C:\testing>java Series
Enter the limit:
5
The sum is: 2.283333333333333
Observation: If we look at the output of the program, we could see that the result displayed
here is not up to two-decimal places. That means the displayed result fails to meet the
requirements of the program. We have used here println() method only.

The modified code using “printf()” method to display the result is given
below. Series_Modified.java
public class Series_Modified {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


System.out.println("Enter the limit: ");
int a = sc.nextInt();
double t, sum = 0.0;
for (int i = 1; i <= a; i++) {
t = 1.0/(double)i;
sum += t;
}
// Displaying the result
System.out.printf("Modified Sum = %.2f\n", sum);
}
}
Output:
C:\testing>java Series_Modified
Enter the limit:
5
Modified Sum = 2.28

Access Modifiers in Java

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default 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.
3. Protected: 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.
4. Public: 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.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.

Understanding Java Access Modifiers

Let's understand the access modifiers in Java by a simple table.

Access Modifier within class within package outside package by subclass only

Private Y N

Default Y Y

Protected Y Y

Public Y Y

1) Private

The private access modifier is accessible only within the

class. Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is a compile-time error.

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:

class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
2) Default

If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.

//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) Protected

The protected access modifier is accessible within package and outside the package but
through inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.

//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello

4) Public

The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.

Example of public access modifier

//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

Java Access Modifiers with Method Overriding

If you are overriding any method, overridden method (i.e. declared in subclass) must not be
more restrictive.

class A{
protected void msg(){System.out.println("Hello java");}
}

public class Simple extends A{


void msg(){System.out.println("Hello java");}//C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}

The default modifier is more restrictive than protected. That is why, there is a compile-time
error.

Constructors in Java
In Java, a constructor is a block of codes
similar to the method. It is called when an
instance of the class is created. At the time of
calling constructor, memory for the object is
allocated in the memory.
It is a special type of method which is used to
initialize the object.
Every time an object is created using the
new() keyword, at least one constructor is
called.

Constructors in Java
It calls a default constructor if there is no
constructor available in the class. In such
case, Java compiler provides a default
constructor by default.
There are two types of constructors in Java:
no-arg constructor, and parameterized
constructor.
Note: It is called constructor because it
constructs the values at the time of object
creation. It is not necessary to write a
constructor for a class. It is because java
compiler creates a default constructor if your
class doesn't have any.
Rules for creating Java constructor
There are two rules defined for the
constructor.
1.Constructor name must be the same as its
class name
2.A Constructor must have no explicit return
type
3.A Java constructor cannot be abstract,
static, final, and synchronized

Types of
Constructors
In Java, constructors can be
divided into 3 types: 1. No-Arg
Constructor
2. Parameterized Constructor
3. Default Constructor
1. Java No-Arg
Constructors
Similar to methods, a Java constructor
may or may not have any parameters
(arguments).
If a constructor does not accept any
parameters, it is known as a no
argument constructor.
For example,
Constructor()
{
// body of the constructor
}
class Flower
{
String name;
Flower()
{
name = "rose";
}
}
class Main
{
public static void main(String[] args)
{
Flower obj = new Flower();
System.out.println("Flower name = " + obj.name); }
}

2. Java Parameterized
Constructor
A Java constructor can also accept one or
more parameters. Such constructors are
known as parameterized constructors
(constructor with parameters). Example
class Main
{
String languages; //
constructor accepting single
value
Main(String lang)
{
languages = lang;

System.out.println(languages + " Programming Language");


}
public static void main(String[] args)
{
// call constructor by passing a single value
Main obj1 = new Main("Java"); Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}

3. Java Default
Constructor
If we do not create any constructor, the Java
compiler automatically create a no-arg
constructor during the execution of the
program. This constructor is called default
constructor.
Example
class Main
{
int a;
boolean b;
public static void main(String[]
args)
{
// A default constructor is called
Main obj = new Main();
System.out.println("Default
Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}

3. Java Default
Constructor
Here, we haven't created any constructors. Hence, the
Java compiler automatically creates the default
constructor.
The default constructor initializes any uninitialized
instance variables with default values.
In the above program, the
variables a and b are initialized
with default
value 0 and false respectively.

3. Java Default
Constructor The above program
is equivalent to:
class Main {

int a;
boolean b;

Main() {
a = 0;
b = false;
}
public static void main(String[] args) {
// call the constructor
Main obj = new Main();

System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}

Java Copy Constructor


There is no copy constructor in Java.
However, we can copy the values from
one object to another like copy
constructor in C++. There are many
ways to copy the values of one object
into another in Java. They are:
• By constructor
• By assigning the values of one object
into another
• By clone() method of Object class
In this example, we are going to copy
the values of one object into another
using Java constructor.
//Java program to initialize the values from one object to
another object. class Student{
int id;
String name;
//constructor to initialize integer and string
Student(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student(Student s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student s1 = new Student(101,“Mridula");
Student s2 = new Student(s1);
s1.display();
s2.display();
}
}
Copying values without constructor
We can copy the values of one object into another by
assigning the objects values to another object. In this case,
there is no need to create the constructor.
class Student{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student(){}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student s1 = new Student(101,“Mridula");
Student s2 = new Student();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
Important Notes on Java
Constructors
• Constructors are invoked implicitly when
you instantiate objects. • The two rules for
creating a constructor are:
The name of the constructor should be the
same as the class.
A Java constructor must not have a return
type.
• If a class doesn't have a constructor, the
Java compiler automatically creates a default
constructor during run-time. The default
constructor initializes instance variables with
default values. For example, the int variable
will be initialized to 0 Constructor types:
No-Arg Constructor - a constructor that does
not accept any arguments Parameterized
constructor - a constructor that accepts
arguments
Default Constructor - a constructor that is
automatically created by the Java compiler if
it is not explicitly defined.
• A constructor cannot be abstract or static or
final.
• A constructor can be overloaded but can not
be overridden.
Constructors Overloading in Java
Similar to Java method overloading, we can also create
two or more constructors with different parameters.
This is called constructors overloading.
class Main {

String language;

// constructor with no parameter


Main() {
this.language =
"Java";
}

// constructor
with a single
parameter
Main(String
language) {
this.language =
language;
}

public void
getName() {

System.out.println("Programming Langauage: " + this.language);


}

public static void main(String[] args) {

// call constructor with no parameter


Main obj1 = new Main();

// call constructor with a single parameter


Main obj2 = new Main("Python");

obj1.getName();
obj2.getName();
}
}
this keyword in Java

There can be a lot of usage of Java this


keyword. In Java, this is a reference
variable that refers to the current
object.
Usage of Java this keyword
Here is
given the
6 usage
of java
this
keyword.
1.this
can be
used to
refer
current
class instance variable.
2.this can be used to invoke current class
method (implicitly)
3.this() can be used to invoke current class
constructor.
4.this can be passed as an argument in the
method call.
5.this can be passed as argument in the
constructor call.
6.this can be used to return the current class
instance from the method.
1) this: to refer current class instance
variable
The this keyword can be used to refer current class instance
variable. If there is ambiguity between the instance variables
and parameters, this keyword resolves the problem of
ambiguity.
Program where this keyword is not
required
2) this: to invoke current class method

You may invoke the method of the current class by using the
this keyword. If you don't use the this keyword, compiler
automatically adds this keyword while invoking the method.
example
3) this() : to invoke current class
constructor
The this() constructor call can be used to
invoke the current class constructor. It is used
to reuse the constructor. In other words, it is
used for constructor chaining.
Calling default constructor from parameterized constructor:
Calling parameterized constructor from default constructor:
Real usage of this() constructor
call
The this() constructor call should be used to reuse the
constructor from the constructor. It maintains the
chain between the constructors i.e. it is used for
constructor chaining. example given below that
displays the actual use of this keyword.
4) this: to pass as an argument in the
method
The this keyword can also be passed as an argument in the
method. It is mainly used in the event handling. example:
Application of this that can be passed as an
argument:
In event handling (or) in a situation where we
have to provide reference of a class to another
one. It is used to reuse one object in many
methods.
5) this: to pass as argument in the
constructor call
We can pass the this keyword in the constructor also. It
is useful if we have to use one object in multiple
classes.

example:
6) this keyword can be used to return
current class instance
We can return this keyword as an statement from the
method. In such case, return type of the method must be the
class type (non-primitive). example:
Syntax of this that can be returned as a statement
return_type method_name(){
return this;
}
Example of this keyword that you return as a
statement from the method
Java String
In Java, string is basically an object that represents sequence of char values. An
array of characters works same as Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.

Java String Class Methods


The java.lang.String class provides a lot of built-in methods that are used to
manipulate string in Java. By the help of these methods, we can perform operations
on String objects such as trimming, concatenating, converting, comparing, replacing
strings etc.
Java String is a powerful concept because everything is treated as a String if you
submit any form in window based, web based or mobile application.
Let's use some important methods of String class.
Java String toUpperCase() and toLowerCase() method The Java
String toUpperCase() method converts this String into uppercase letter and String
toLowerCase() method into lowercase letter.
Stringoperation1.java
1. public class Stringoperation1
2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.toUpperCase());//SACHIN
7. System.out.println(s.toLowerCase());//sachin
8. System.out.println(s);//Sachin(no change in original)
9. }
10. }
Output:
SACHIN
sachin
Sachin
Java String trim() method
The String class trim() method eliminates white spaces before and after the
String. Stringoperation2.java
1. public class Stringoperation2
2. {
3. public static void main(String ar[])
4. {
5. String s=" Sachin ";
6. System.out.println(s);// Sachin
7. System.out.println(s.trim());//Sachin
8. }
9. }
Output:
Sachin
Sachin
Java String startsWith() and endsWith() method
The method startsWith() checks whether the String starts with the letters passed as
arguments and endsWith() method checks whether the String ends with the letters
passed as arguments.
Stringoperation3.java
1. public class Stringoperation3
2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.startsWith("Sa"));//true
7. System.out.println(s.endsWith("n"));//true
8. }
9. }
Output:
true
true
Java String charAt() Method
The String class charAt() method returns a character at specified
index. Stringoperation4.java
1. public class Stringoperation4
2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.charAt(0));//S
7. System.out.println(s.charAt(3));//h
8. }
9. }
Output:
S
h
Java String length() Method
The String class length() method returns length of the specified
String. Stringoperation5.java
1. public class Stringoperation5
2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.length());//6
7. }
8. }
Output:
6
Java String intern() Method
A pool of strings, initially empty, is maintained privately by the class

String.
When the intern method is invoked, if the pool already contains a String equal to this
String object as determined by the equals(Object) method, then the String from the
pool is returned. Otherwise, this String object is added to the pool and a reference to
this String object is returned.
String Interning in Java is a process where identical strings are searched in the string pool
and if they are present, the same memory is shared with other strings having the same value.
The intern() method creates an exact copy of a String that is present in the heap memory and
stores it in the String constant pool.
Takeaway - intern() method is used to store the strings that are in the heap in the string
constant pool if they are not already present.
Example of String intern() in Java
String str1 = new String("Java");
String str2 = new String("Java");
System.out.println(str1 == str2);
str3 = str1.intern();
str4 = str2.intern();
System.out.println(str3 == str4);
Output
false
true
Explanation - The strings str1 and str2 are not equal as they have different memory location
in the heap. When we apply the intern() method on str1 and store it in str3, it gets created in
the String constant pool. But when the compiler executes the statement for applying the
intern() method on str2, it checks the String constant pool first if the value is already present
or not.
Here, since the value "Java" was already present, it only returns the reference and does not
create the string again.
Whenever a new string is created, JVM first checks the string pool. In case, if it encounters
the same string, then instead of creating a new string, it returns the same instance of the found
string to the variable. If the string was not present, it creates a new string literal then allocates
memory to it.
Therefore, this method helps to save memory space.
Stringoperation6.java
1. public class Stringoperation6
2. {
3. public static void main(String ar[])
4. {
5. String s=new String("Sachin");
6. String s2=s.intern();
7. System.out.println(s2);//Sachin
8. }
9. }
Output:
Sachin
Java String valueOf() Method
The String class valueOf() method coverts given type such as int, long, float, double,
boolean, char and char array into String.
Stringoperation7.java
1. public class Stringoperation7
2. {
3. public static void main(String ar[])
4. {
5. int a=10;
6. String s=String.valueOf(a);
7. System.out.println(s+10);
8. }
9. }
Output:
1010
Java String replace() Method
The String class replace() method replaces all occurrence of first sequence of
character with second sequence of character.
Stringoperation8.java
1. public class Stringoperation8
2. {
3. public static void main(String ar[])
4. {
5. String s1="Java is a programming language. Java is a platform. Java is an
Islan d.";
6. String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to
" Kava"
7. System.out.println(replaceString);
8. }
9. }
Output:
Kava is a programming language. Kava is a platform. Kava is an Island. In
Java, a String is a sequence of characters represented as an instance of the
java.lang.String class.
Internally, strings are represented as an array of Unicode characters indexed
starting with 0, 1, 2, and so on, from left to right.

All the operations that we use in an array can also be performed on String objects. Strings
as array of characters

Interfaces in string
The String class implements CharSequence, Serializable,
and Comparable interfaces. Below are the details of these interfaces:
• The CharSequence interface provides charAt() used to access the char value at the
specified index.
• The Comparable interface provides the compareTo() method to compare the
objects.
• The Serializable interface is a markup interface as it does not provide any methods
or constants.
The Serializable interface simply provides information to the JVM at run-time to
enable serialization and deserialization.
Interfaces implemented by the String class
In Java, strings are immutabletheir object cannot be modified after it is initialized.
The string can be initialized at the time of object creation. Thereafter, an entirely new
string object is created in the memory whenever the’ string’ object is modified. String
literals are stored in the Java heap memory storage area known as the String Pool.
Syntax

String <string_variable> = "<char_sequence>";

String <string_variable> = new String("<char_sequence>");

Code

String str = "Hello";

String str1 = new String("World");

Explanation
In the first case, the string object named "Hello" is created as a literal and stored in
the String pool, which results in optimization of memory by JVMJava Virtual Machine. On
the other hand,"World" is created using the new operator with the string object. An
entirely new memory will be allocated dynamically, and this string would not be added
to the String pool.

The java.lang.String class


implements Serializable, Comparable and CharSequence

interfaces.

CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String,
StringBuffer and StringBuilder classes implement it. It means, we can create strings
in Java by using these three classes.

The Java String is immutable which means it cannot be changed. Whenever we


change any string, a new instance is created. For mutable strings, you can use
StringBuffer and StringBuilder classes.
What is String in Java?
Generally, String is a sequence of characters. But in Java, string is an object that
represents a sequence of characters. The java.lang.String class is used to create a
string object.
How to create a string object?
There are two ways to create String object:
1. By string literal
2. By new keyword
1) 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
the string doesn't exist in the pool, a new string instance is created and placed in the
pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance

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 that is why it will create a new
object. After that it will find the string with the value "Welcome" in the pool, it will not
create a new object but will return the reference to the same instance. Note: String
objects are stored in a special memory area known as the "string constant pool".
Why Java uses the concept of String literal?
To make Java more memory efficient (because no new objects are created if it exists
already in the string constant pool).
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference varia
ble
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 a heap (non-pool).
Java String Example
StringExample.java
1. public class StringExample{
2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}
Output:
java
strings
example
The above code, converts a char array into a String object. And displays the String
objects s1, s2, and s3 on console using println() method.
Java String class methods
The java.lang.String class provides many useful methods to perform operations on
sequence of char values.
No. Method Description

1 char charAt(int index) It returns char value for the particular index

2 int length() It returns string length

3 static String format(String format, It returns a formatted string.


Object... args)

4 static String format(Locale l, String It returns formatted string with given locale.
format, Object... args)

5 String substring(int beginIndex) It returns substring for given begin index.

6 String substring(int beginIndex, int It returns substring for given begin index
endIndex) and end index.

7 boolean contains(CharSequence s) It returns true or false after matching the


sequence of char value.

8 static String join(CharSequence It returns a joined string.


delimiter, CharSequence...
elements)
9 static String join(CharSequence It returns a joined string.
delimiter, Iterable<? extends
CharSequence> elements)

10 boolean equals(Object another) It checks the equality of string with the


given object.

11 boolean isEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the specified string.

13 String replace(char old, char new) It replaces all occurrences of the specified
char value.

14 String replace(CharSequence old, It replaces all occurrences of the specified


CharSequence new) CharSequence.

15 static String It compares another string. It doesn't


equalsIgnoreCase(String another) check case.

16 String[] split(String regex) It returns a split string matching regex.

17 String[] split(String regex, int limit) It returns a split string matching regex and
limit.

18 String intern() It returns an interned string.

19 int indexOf(int ch) It returns the specified char value index.

20 int indexOf(int ch, int fromIndex) It returns the specified char value index
starting with given index.

21 int indexOf(String substring) It returns the specified substring index.

22 int indexOf(String substring, int It returns the specified substring index


fromIndex) starting with given index.

23 String toLowerCase() It returns a string in lowercase.

24 String toLowerCase(Locale l) It returns a string in lowercase using


specified locale.
25 String toUpperCase() It returns a string in uppercase.

26 String toUpperCase(Locale l) It returns a string in uppercase using


specified locale.

27 String trim() It removes beginning and ending spaces


of this string.

28 static String valueOf(int value) It converts given type into string. It is an


overloaded method.

Nested Classes in Java


In Java, it is possible to define a class within another class, such classes are known
as nested classes. They enable you to logically group classes that are only used in
one place, thus this increases the use of encapsulation, and creates more readable
and maintainable code.
• The scope of a nested class is bounded by the scope of its enclosing
class. Thus in below example, class NestedClass does not exist
independently of class OuterClass.
• A nested class has access to the members, including private members, of
the class in which it is nested. But the enclosing class does not have access
to the member of the nested class.
• A nested class is also a member of its enclosing class.

• As a member of its enclosing class, a nested class can be


declared private, public, protected, or package private(default). •
Nested classes are divided into two categories:
1. static nested class : Nested classes that are
declared static are called static nested classes.
2. inner class : An inner class is a non-static nested class.
Syntax:
class OuterClass
{
...
class NestedClass
{
...
}
}
Static nested classes
In the case of normal or regular inner classes, without an outer class object existing,
there cannot be an inner class object. i.e., an object of the inner class is always strongly
associated with an outer class object. But in the case of static
nested class, Without an outer class object existing, there may be a static nested class
object. i.e., an object of a static nested class is not strongly associated with the outer
class object.As with class methods and variables, a static nested class is associated
with its outer class. And like static class methods, a static nested class cannot refer
directly to instance variables or methods defined in its enclosing class: it can use them
only through an object reference.They are accessed using the enclosing class name.
OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
j
• Java
// Java program to demonstrate accessing
// a static nested class

// outer class
class OuterClass {
// static member
static int outer_x = 10;

// instance(non-static) member
int outer_y = 20;

// private member
private static int outer_private = 30;

// static nested class


static class StaticNestedClass {
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);

// can access private static member of


// outer class
System.out.println("outer_private = "
+ outer_private);

// The following statement will give compilation


// error as static nested class cannot directly
// access non-static members
// System.out.println("outer_y = " + outer_y);

// Therefore create object of the outer class


// to access the non-static member
OuterClass out = new OuterClass();
System.out.println("outer_y = " + out.outer_y);

}
}
}

// Driver class
public class StaticNestedClassDemo {
public static void main(String[] args)
{
// accessing a static nested class
OuterClass.StaticNestedClass nestedObject
= new OuterClass.StaticNestedClass();

nestedObject.display();
}
}

Output:
outer_x = 10
outer_private = 30
outer_y = 20
Inner classes
To instantiate an inner class, you must first instantiate the outer class. Then,
create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new
InnerClass(); There are two special kinds of inner classes :
1. Local inner classes
2. Anonymous inner classes
• Java

// Java program to demonstrate accessing


// a inner class

// outer class
class OuterClass
{
// static member
static int outer_x = 10;

// instance(non-static) member
int outer_y = 20;
// private member
private int outer_private = 30;

// inner class
class InnerClass
{
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);

// can also access non-static member of outer class


System.out.println("outer_y = " + outer_y);

// can also access a private member of the outer class


System.out.println("outer_private = " + outer_private);

}
}
}

// Driver class
public class InnerClassDemo
{
public static void main(String[] args)
{
// accessing an inner class
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
innerObject.display();

}
}

Output:
outer_x = 10
outer_y = 20
outer_private = 30
Comparison between normal or regular class and static nested class
S.N Normal/Regular inner class Static nested class
O
1. Without an outer class object Without an outer class object
existing, there cannot be an inner existing, there may be a static
class object. nested class object. That is, static

S.N Normal/Regular inner class Static nested class


O
That is, the inner class object is nested class object is not
always associated with the outer associated with the outer
class object. class object.

2. Inside normal/regular inner class, Inside static nested class,


static members can’t be declared. static members can be
declared.

3. As main() method can’t be As main() method can be


declared, regular inner class can’t declared, the static nested class
be invoked directly from the can be invoked directly from the
command prompt. command prompt.

4. Both static and non static members Only a static member of


of outer class can be accessed outer class can be accessed
directly. directly.

class OuterClass {

int x = 10;

class InnerClass {

int y = 5;

public class Main {

public static void main(String[] args) {

OuterClass myOuter = new OuterClass();

OuterClass.InnerClass myInner = myOuter.new InnerClass();

System.out.println(myInner.y + myOuter.x); }

You might also like