Java Module1
Java Module1
Java Module1
(MODULE - 1)
1
MODULE – I
INTRODUCTION TO JAVA:
Java is a high-level, third generation programming language, like C, FORTRAN, Smalltalk, Perl,
and many others.
Java language is called as an Object-Oriented Programming language .
Java is a general-purpose, object-oriented programming language developed by Sun
Microsystems of USA in 1991.
HISTRORY OF JAVA:
The history of Java starts with the Green Team. Java team members (also known as Green
Team), initiated this project to develop a language for digital devices such as set-top boxes,
televisions, etc.
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991.
The small team of sun engineers was called as Green Team.
James Gosling is known as the father of Java.
Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
After that, it was called Oak .
In 1995, Oak was renamed as "Java".
Java was initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.
JAVA ARCHITECTURE
Java Architecture is a collection of components, i.e., JVM, JRE, and JDK. It integrates the process of
interpretation and compilation. It defines all the processes involved in creating a Java program. Java
Architecture explains each and every step of how a program is compiled and executed.
2
Byte Code:
Byte Code can be defined as an intermediate code generated by the compiler after the
compilation of source code(JAVA Program). This intermediate code makes Java a platform-
independent language.
Compiler converts the source code or the Java program into the Byte Code and secondly, the
Interpreter executes the byte code on the system. The Interpreter can also be called JVM(Java
Virtual Machine). The byte code is the common piece between the compiler(which creates it)
and the Interpreter (which runs it).
3
o Java Virtual Machine (JVM)
o Java Runtime Environment (JRE)
o Java Development Kit (JDK)
It is a Java platform component that gives us an environment to execute java programs. JVM's main task
is to convert byte code into machine code.
- JVM (Java Virtual Machine) is an abstract machine.
- It is called a virtual machine because it doesn't physically exist.
- It is a specification that provides a runtime environment in which Java bytecode can be executed.
4
Java Development Kit (JDK):
- The Java Development Kit (JDK) is a software development environment which is used to
develop Java applications and applets.
- It physically exists.
- It contains JRE + development tools.
Tools of JDK:
Appletviewer( It is used for viewing the applet)
Javac(It is a Java Compiler)
Java(It is a java interpreter)
Javap(Java diassembler,which convert byte code into program description)
Javah(It is for java C header files)
Javadoc(It is for creating HTML document)
Jdb(It is Java debugger)
JVM ARCHITECTURE
The JVM (Java Virtual Machine) architecture consists of several components that work together to
execute Java programs. Here is a high-level overview of the JVM architecture:
JVM consists of three main components.
1. ClassLoader.
2. Memory Area /Runtime Memory/Data Area.
3. Execution Engine.
5
1. Class Loader: The Class Loader component is responsible for loading Java class files into the JVM
at runtime. It performs tasks such as locating and reading class files, verifying their bytecode, and
defining the classes within the JVM.
c. Stack :
Each thread in the JVM has a Java Stack that stores method-specific data, including local
variables, method arguments, and method invocation records. It also manages method calls and
returns.
d. PC registers:
If the method that was executed was not a native method, the pc registers will store
information about the method’s next execution. A native method is a Java method that is implemented in
another programming language, such as C or C++.
e. Native method area:
6
If any native methods are accessed or executed, the native method area provides facility to
store them.
3. Execution Engine : The Execution Engine executes Java bytecode. It can employ different
techniques for bytecode execution, such as interpretation, Just-In-Time (JIT) compilation, or a
combination of both.
Native Method Interface (JNI): The JNI allows Java programs to interact with native code
written in languages like C or C++. It provides a mechanism for Java code to call native methods
and access native libraries.
JVM Languages: The JVM architecture supports languages other than Java through additional
compilers and runtime support. Examples include Kotlin, Scala, and Groovy, which can all be
compiled into bytecode and executed on the JVM.
JAVA BUZZWORDS:
The features of Java are also known as Java buzzwords. Java is an object oriented programming
language developed by Sun Microsystems of USA in 1991. Java is first programming language which is
not attached with any particular hardware or operating system. Program developed in Java can be
executed anywhere and on any system.
7
2. Compiled and Interpreted
3. Platform Independent and portable
4. Object- oriented
5. Robust and secure
6. Distributed
7. Multithreaded and Interactive
8. High performance
9. Dynamic and Extensible
Object- oriented
Java is truly object-oriented language. In Java, almost everything is an Object. All program code
and data exist in objects and classes.
8
Basic Concept of OOP(Object-Oriented Programming):
There are some basic concepts of object oriented programming as follows:
1. Object :
Any entity that has state and behavior is known as an object.
For example, a chair, pen, table, keyboard, bike, etc.
It can be physical or logical.
An Object can be defined as an instance of a class.
An object contains an address and takes up some space in memory.
2. Class :
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual
object.
Class doesn't consume any space.
3. Data abstraction :
Hiding internal details and showing functionality is known as abstraction
4. Data encapsulation :
Binding (or wrapping) code and data together into a single unit are known as
encapsulation.
For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation.
5. Inheritance :
When one object acquires all the properties and behaviors of a parent object, it
is known as inheritance.
It provides code reusability.
6. Polymorphism :
If one task is performed in different ways, it is known as polymorphism.
7. Dynamic binding :
Dynamic binding is also referred to as a run-time polymorphism.
In this type of binding, the functionality of the method call is not decided at
compile-time.
In other words, it is not possible to decide which piece of code will be executed
as a result of a method call at compile-time
9
Java comes with an extensive set of classes; organize in packages that can be used in program
by Inheritance. The object model in Java is trouble-free and easy to enlarge.
Distributed
Java is called as Distributed language for construct applications on networks which can contribute both
data and programs. Java applications can open and access remote objects on Internet easily. That means
multiple programmers at multiple remote locations to work together on single task
High performance
Java performance is very extraordinary for an interpreted language, majorly due to the use of
intermediate bytecode. Java architecture is also designed to reduce overheads during runtime.
The incorporation of multithreading improves the execution speed of program.
10
UNDERSTANDING THE SEMANTIC AND SYNTAX DIFFERENCES BETWEEN C++ AND
JAVA
INDEX COMPARISON C++ JAVA
PARAMETER
1 Developed / C++ was developed by Bjarne Java was developed by James
Founded by Stroustrup at Bell Labs in 1979. Gosling at Sun Microsystems.
It was developed as an extension Now, it is owned by Oracle.
of the C language.
2 Programming It has support for both Java has support only for object-
model procedural programming and oriented programming models.
object-oriented programming.
3 Platform C++ is platform dependent. Java is platform-independent. It is
dependence based on the concept of Write
Once Run Anywhere.
4 Features supported C++ supports features like Java does not support features like
multiple inheritance, operator multiple inheritance, operator
overloading, Goto statements, overloading, Goto statements,
structures, pointers, unions, etc. structures, pointers, unions, etc.
5 Compiler and C++ uses compiler only. C++ is Java uses both compiler and
Interpreter compiled and run using the interpreter. Java source code is
compiler which converts source converted into bytecode at
code into machine code so, C++ compilation time. The interpreter
is platform dependent. executes this bytecode at runtime
and produces output. Java is
interpreted that is why it is
platform-independent.
6 Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads.
7 virtual keyword C++ supports virtual keyword so Java has no virtual keyword. We
that we can decide whether or can override all non-static
not to override a function. methods by default. In other
words, non-static methods are
virtual by default.
11
We can develop two types of java programs:
i. Stand-alone applications
o These are the programs written in Java to carry out certain tasks on a stand-alone
local computer.
o A stand-alone program that can be invoked from command line .
o A program that has a “main” method
ii. Web applets
o A program embedded in a web page , to be run when the page is browsed .
o A program that contains no “main” method
12
[ Two ways of using Java]
DATA TYPES :
A data type is a scheme for representing values. An example is int which is the Integer, a data
type.
Values are not just numbers, but any manner of data that a computer can process.
The data type defines the kind of data that is represented by a variable.
As with the keyword class, Java data types are case sensitive.
13
interface
Following table shows the datatypes with their size and ranges.
14
o Minimum value is -32,768 (-2^15)
o Maximum value is 32,767 (inclusive) (2^15 -1)
o Default value is 0.
o Example: short s = 10000, short r = -20000
int
o Int data type is a 32-bit signed two's complement integer.
o Minimum value is - 2,147,483,648.(-2^31)
o Maximum value is 2,147,483,647(inclusive).(2^31 -1)
o The default value is 0.
o Example: int a = 100000, int b = -200000
long
o Long data type is a 64-bit signed two's complement integer.
o Minimum value is -9,223,372,036,854,775,808.(-2^63)
o Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
o Default value is 0L.
o Example: long a = 100000L, int b = -200000L
15
4. Boolean data type:
o It is used when we want to test a particular condition during the excution of the program.
o There are only two values that a boolean type can hold: true and false.
o Boolean type is denoted by the keyword boolean and uses only one bit of storage.
o Default value is false.
o Example: boolean one = true
SIMPLE JAVA PROGRAM: Let's take our very first and a simple java program to understand
various terms required to write an application.
Example:
class FirstProgram
{
public static void main(String args[])
{
System.out.println(“ This is my first program”);
}
}
System is a built-in class present in java.lang package. It contains pre-defined methods and
fields, which provides facilities like standard input, output, etc.
16
out is a static final field (ie, variable)in System class which is of the type PrintStream (a built-
in class, contains methods to print the different data values). static fields and methods must be
accessed by using the class name, so ( System.out ).
out here denotes the reference variable of the type PrintStream class.
println() is a public method in PrintStream class to print the data values. Hence to access a
method in PrintStream class, we use out.println().
VARIABLES:
Variables are labels that express a particular position in memory and connect it with a data type .
Syntax:
dataType variableName;
17
System.out.println("Good Morning " + nm);
}
}
Example:
import java.io.*;
class read1
{
public static void main(String args[]) throws Exception
{
InputStreamReader IR = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(IR);
int c = a + b;
System.out.println("Result = " + c);
}
}
Input through keyboard using Scanner class:
Methods of Scanner class:
18
Example: Write a program to enter two numbers from keyboard using Scanner class and display
their sum.
import java.util.*;
class ReadScanner
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int c=a+b;
System.out.println("The result is "+c);
}
}
Example -2:
import java.util.Scanner;
class ScannerTest
{
public static void main(String args[])
19
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
20
output:
c:\javac Add.java
c:\java Add 5 2
7
21
float a=23.4f;
int b=12;
a=b;
System.out.println("a="+a+" b= "+b);
}
}
Output: a=12.0 b=12
Example:
class TypeTest
{
public static void main(String args[])
{
float a=34.5f;
int b=12;
b=(int)a;
System.out.println("a="+a+" b= "+b);
}
}
22
Output: a=34.5 b=34
SCOPE OF VARIABLES:
There are three types of variables in java
local variable :
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor or block.
Local variables are visible only within the declared method, constructor or block.
Access modifiers cannot be used for local variables.
There is no default value for local variables so local variables should be declared and an
initial value should be assigned before the first use.
instance variable :
Instance variables are declared in a class, but outside a method, constructor or any block.
When a space is allocated for an object in the heap, a slot for each instance variable value
is created.
Instance variables are created when an object is created with the use of the keyword 'new'
and destroyed when the object is destroyed.
Access modifiers can be given for instance variables.
static variable
Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
Static variables are created when the program starts and destroyed when the program
stops.
CONSTANTS:
Constant means fixed value which is not change at the time of execution of program. In Java, there are
two types of constant as follows:
23
Numeric Constants
o Integer constant : Example- 23 411 , 7,00,000
o Real constant : Example – 0.0234 , 0.777 ,-1.23
Character Constants
o Character constant : Example – 'A‘ , '7‘ ', '\‘
o String constant :Example - “WELCOME” , “END OF PROGRAM”
Symbolic constant:
In Java program, there are many things which are required repeatedly and if we want to make changes
then we have to make these changes in whole program where this variable is used. For this purpose, Java
provides ̳final‘ keyword to declare the value of variable as follows:
Syntax:
final type Symbolic_name=value;
Example:
final float PI=3.1459
Constant Importance
\b Back space
\t Tab
\n New Line
\\ Back slash
'\'' Single Quote
'\'” Double Quote
KEYWORDS:
o Keywords are important part of Java.
o Java language has reserved 50 words as keywords.
o Keywords have specific meaning in Java.
o We cannot use them as variable, classes and method.
Following table shows keywords.
24
OPERATORS
Java carries a broad range of operators. An operator is symbols that specify operation to be
performed may be certain mathematical and logical operation. Operators are used in programs to operate
data and variables. They frequently form a part of mathematical or logical expressions.
Special Operators:
i. Instanceof Operator
The instanceof is an object reference operator and returns true is the object on the left-hand
side is an instance of the class given on the right-hand side. This operator allows us to
determine whether the object belongs to a particular class or not.
Example:
person instanceof student
is true if the object person belongs to the class student, otherwise it is false.
ii. Dot Operator
The dot operator ( . ) is used to access the instance variavles and methods of class objects.
Example:
person1.age , student1. Roll etc
Separators
Separators are symbols. It shows the separated code.
Example: , ,., ; etc
Mathematical Functions
Mathematical functions such as cos, sqrt, log etc are frequently used in analysis of real life problems.
Java supports these basic mathematical functions through Math class defined in the java. lang package.
26
Syntax:
Math. function_name( )
Example:
class math1
{
Public static void main(String args[ ])
{
double x;
x = Math.max(22, 46);
System.out.println(“ The maximum number is :” + x );
x = Math.sqrt(64);
System.out.println(“Square root is :” + x);
x = Math.pow(2, 3);
System.out.println(“ The power is :” + x);
}
}
Conditional Statement:
Selection statement is also called as Decision making statements because it provides the decision
making capabilities to the statements.
27
{
True - Statement block;
}
else
{
False - Statement block;
}
Example:
Write a program to find out the greatest number among three number using nested if (taking input
through Command line argument).
28
}//End of class
switch statement :
Syntax:
switch(condition)// condition means case value
{
case value-1:
statement block1;
break;
case value-2:
statement block2;
break;
....
...
default:
statement block-default;
break;
}
statement a;
Example:
Enter a number (0-9) through command line argument and print in words using switch statement.
29
case 1:
System.out.println("ONE");
break;
case 2:
System.out.println("TWO");
break;
case 3:
System.out.println("THREE");
break;
case 4:
System.out.println("FOUR");
break;
case 5:
System.out.println("FIVE");
break;
case 6:
System.out.println("SIX");
break;
case 7:
System.out.println("SEVEN");
break;
case 8:
System.out.println("EIGHT");
break;
case 9:
System.out.println("NINE");
break;
default:
System.out.println("OUT OF RANGE");
}
}
}
30
Loop Statement:
The process of repeatedly executing a statements and is called as looping. The statements may be
executed multiple times (from zero to infinite number). If a loop executing continuous then it is called as
Infinite loop. Looping is also called as iterations.
while loop
Syntax:
While(condition)
{
Statement block;
}
do-while loop
Syntax:
do
{
Statement block;
}
While(condition);
31
{
public static void main(String args[])
{
for(int i=1;i<=5;i++)
{
for(int s=1;s<=5-i;s++)
System.out.print(" ");
for(int j=1;j<=i;j++)
System.out.print(j);
for(int j=i-1;j>=1;j--)
System.out.print(j);
System.out.println();
}
}
}
Example:
// Program to check if a number entered through keyboard is prime or not
import java.util.Scanner;
public class PrimeDemo
{
32
break;
}
}
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
WRAPPER CLASSES
we may come across situations where we need to use objects instead of primitive data types. In order
to achieve this, Java provides wrapper classes.
Wrapper class in java provides the mechanism to convert primitive into object and object into
primitive.
All the wrapper classes are subclasses of the abstract class Number.
The eight classes of java.lang package are known as wrapper classes in java. The list of eight
wrapper classes are given below:
The object of the wrapper class contains or wraps its respective primitive data type. Converting
primitive data types into object is called boxing, and this is taken care by the compiler.
33
The automatic conversion of primitive into object is known as autoboxing and vice-versa unboxing.
The Number class is part of the java.lang package.
When x is assigned an integer value, the compiler boxes the integer because x is integer object. Later, x
is unboxed so that they can be added as an integer.
34
public static void main(String[] args)
{
float f = 10.10f;
Float obj1 = new Float(f);
System.out.println(obj1);
double d = 10.10;
Float obj2 = new Float(d);
System.out.println(obj2);
class WrapperTest
{
public static void main(String args[]) throws Exception
{
InputStreamReader IR=new InputStreamReader(System.in);
BufferedReader BR=new BufferedReader(IR);
35
float tot = m1+m2;
ARRAYS IN JAVA:
An array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where we
store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.
An array is a way to hold more than one value at a time.
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type.
An array is used to store a collection of data, but it is often more useful to think of an array as a
collection of variables of the same type.
36
or
dataTypearrayRefVar[ ];
Example:
int[ ]myArray;
or
int myArray[ ];
Creating Arrays:
You can create an array by using the new operator with the following syntax:
arrayRefVar = newdataType[arraySize];
or
dataType[]arrayRefVar = new dataType[arraySize];
or
dataType[]arrayRefVar = {value0, value1, ..., valuek};
System.out.println("FirstArray");
for(i=0; i<4; i++)
System.out.println(array1[i]);
37
System.out.println("SecondArray");
for(i=0; i<4; i++)
System.out.println(array2[i]);
System.out.println("ThirdArray");
for(i=0; i<4; i++)
System.out.println(array3[i]);
}
}
Example2:
public class testArray
{
public static void main(String[] args) {
int[] a = {10, 11, 12,13};
int total = 0;
for (int i = 0; i<a.length; i++) {
total += a[i];
}
38
System.out.println("Max is " + max);
}
}
int n = a.length ;
System.out.println(“The original array is :”);
for (int i = 0; i<n; i++)
System.out.println(a[i] + " ");
for (int i=0;i< n ; i++)
{
for (int j = i + 1 ; j < n ; j++)
{
if (a[i] < a[j])
{ int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
39
}
}
Program
class Testarray3
{
public static void main(String args[])
40
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Example:
class ArrayDemo3
{
public static void main(String args[])
{
int a[]=new int[4];
a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
41
Example:
import java.util.*;
class ArrayDemo
{
public static void main(String args[])
{
for(int i=0;i<n;i++)
{
System.out.println("Enter a number:");
int num=sc.nextInt();
a[i]=num;
}
JAVA STRINGS
Strings are used for storing text. A String variable contains a collection of characters surrounded by
double quotes:
42
i. String
ii. StringBuffer
iii. StringBuilder.
The String class is an immutable class whereas StringBuffer and StringBuilder classes are
mutable.
STRING CLASS
A Java string is an instantiated object of the String class.
43
S1.subString(n, m) Gives substring starting from nth character upto mth(not including mth )
String.ValueOf(p) Creates a string object of the parameter p
p.toStirng( ) Creates a string representation of the object p.
S1.indexOf(‘x’) Gives the position of first occurrence of ‘x’ in the string s1
S1.indexOf(‘x’ , n) Gives the position of ‘x’ that occurs after nth position in the string s1
String.ValueOf(variable) Converts the parameter value to string representation
Write a program enters a string and test all the method present in string class.
public class StringDemo
{
public static void main(String args[])
{
String s1="This is a Demo of String Class";
System.out.println("Length :"+ s1.length());
System.out.println("Charactr at :" + s1.charAt(0));
int start=10;
int end=14;
char c[]=new char[end-start];
s1.getChars(start,end,c,0);
System.out.println(c);
System.out.println("UpperCase :"+s1.toUpperCase());
System.out.println("LowerCase :"+s1.toLowerCase());
System.out.println("IndexOf :"+s1.indexOf('a'));
System.out.println(s1.indexOf('F'));
System.out.println(s1.indexOf('a',9));
System.out.println("Java".compareTo("java") );
System.out.println("java".compareTo("Java") );
44
System.out.println("Jav".compareTo("Java") );
if((s1.startsWith("This"))&&(s1.endsWith("Class")))
System.out.println("Java");
else
System.out.println("C");
String st1="Java";
String st2 = "java";
if(st1.equalsIgnoreCase(st2))
System.out.println ("They are equal");
else
System.out.println ("They are not equal");
Output:
Length :30
Character at :T
Demo
Uppercase : THIS IS A DEMO OF STRING CLASS
Lowercase : this is a demo of string class
IndexOf :8
-1
27
45
Last Index Of :27
-32
32
-1
Java Core
Java
Temp = This
They are equal
New string = Gava
STRINGBUFFER CLASS
StringBuffer is a peer class of String. While String creates strings of fixed length, StringBuffer creates
strings of flexible length that can be modified in terms of both length and content. We can insert
characters and substrings in the middle of the string or append another string at the end.
The StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class is same as
String except it is mutable i.e. it can be changed.
Method Task
s1.setCharAt(n, ‘x’) Modifies the nth character to x
s1.append(s2) Appends the string s2 to s1 at the end
s1. Insert(n, s2) Inserts the string s2 at the position n of the string
s1
s1.setLength(n) Sets the length of the string s1 to n. If n<
s1.length( ) s1 is truncated. If n> s1.length( ) zeros
are added to s1.
Example:
class stringBufferDemo{
public static void main(String args[]){
46
System.out.println("Append :"+sb);//prints Hello Java
sb.insert(1,"Java");
System.out.println("Insert :" + sb);
sb.replace(1,3,"Java");
System.out.println("Replace :"+sb);
sb.delete(1,3);
System.out.println("Delete :"+sb);
sb.reverse();
System.out.println("Reverse :"+sb);
sb1.append("Hello");
System.out.println("Cpacity after appending :"+sb1.capacity()); //now 16
}
}
Output:
47
Example:
Enter a string from keyboard and check whether it is palindrome or not.
import java.io.*;
class pallindromeTest
{
public static void main(String args[]) throws Exception
{
int a[ ] = new int[10];
System.out.println("Enter a string:");
String s1 = br.readLine();
int length=s1.length();
char b[]=s1.toCharArray();
char c[]=new char[length];
int j = 0;
for(int i=length-1;i>=0;i--)
{
c[j]=b[i];
j++;
}
48
}
if(count==length)
System.out.println(s1 + " is palindrome.");
else
System.out.println(s1 + " is not palindrome.");
}//End of main
}
Example 2:
WAP to test between = = and equals().
class equalsDemo
{
public static void main(String arg[])
{
String s1="Hello";
String s2=new String("Hello");
//Use of ==
if(s1==s2)
System.out.println("Same reference");
else
System.out.println("Different reference");
if(s1.equals(s2))
System.out.println("String same");
else
System.out.println("String different ");
}
}
Output:
Different reference
49
String same
STRINGBUILDER CLASS
StringBuilder in Java represents a mutable sequence of characters.
The String Class creates an immutable sequence of characters whereas the StringBuilder class
creates a mutable sequence of characters.
The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized.
It is available since JDK 1.5.
The function of StringBuilder is very much similar to the StringBuffer class, as both of them
provide an alternative to String Class by making a mutable sequence of characters.
However, the StringBuilder class differs from the StringBuffer class on the basis of
synchronization.
The StringBuilder class provides no guarantee of synchronization whereas the StringBuffer
class does.
If synchronization is required then it is recommended that StringBuffer be used.
String Builder is not thread-safe and high in performance compared to String buffer.
50
Important methods of StringBuilder class
Method Description
public StringBuilder append(String s) It is used to append the specified string with this
string.
public StringBuilder insert(int offset, String s) It is used to insert the specified string with this
string at the specified position.
public StringBuilder replace(int startIndex, int It is used to replace the string from specified
endIndex, String str) startIndex and endIndex.
public StringBuilder delete(int startIndex, int It is used to delete the string from specified
endIndex) startIndex and endIndex.
public StringBuilder reverse() It is used to reverse the string.
public int capacity() It is used to return the current capacity.
public int length() It is used to return the length of the string i.e. total
number of characters.
public char charAt(int index) It is used to return the character at the specified
position.
public String substring(int beginIndex, int It is used to return the substring from the specified
endIndex) beginIndex and endIndex.
public String substring(int beginIndex) It is used to return the substring from the specified
beginIndex.
Example:
Write a program in Java to create object using StringBuilder class and demonstrate the usages of
various methods of StringBuilder class.
Program:
class StringBuilderDemo
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello ");
51
sb.append("Trident");
System.out.println(sb);
sb.insert(1,"Java");
System.out.println(sb);
sb.replace(10,16,"TACT");
System.out.println(sb);
sb.delete(1,5);
System.out.println(sb);
sb.reverse();
System.out.println(sb);
}
}
Output:
52