0% found this document useful (0 votes)
9 views15 pages

Strings

The document provides an overview of arrays and strings in Java, detailing their initialization, assignment, and various operations. It explains one-dimensional, two-dimensional, and three-dimensional arrays, as well as string comparison methods and concatenation techniques. Additionally, it covers the StringBuffer class for mutable strings, including its key methods and behaviors.

Uploaded by

javahost07
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)
9 views15 pages

Strings

The document provides an overview of arrays and strings in Java, detailing their initialization, assignment, and various operations. It explains one-dimensional, two-dimensional, and three-dimensional arrays, as well as string comparison methods and concatenation techniques. Additionally, it covers the StringBuffer class for mutable strings, including its key methods and behaviors.

Uploaded by

javahost07
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

ARRAYS IN JAVA

Array: An array is a collection of elements that can store more than one value of similar types.
Ex: int a[]={10,20,30}; 10 20 30
 An array allocates the memory in a sequential manner 0 1 2
 For arrays the index number starts from “Zero”
 Size of an array = number of elements X size of data type.
 For n values there will be ‘n-1’ index numbers since the index number starts from “ZERO”.

Initialization Of An Array: Storing the values into an array at the time of memory allocation is
said to be “initialization” of an array. 10 20 30
Ex: int a[]={10,20,30};
0 1 2
The elements of an array should be accessed by using index numbers. Hence arrays are also called as
“index variables.”
class ArrayOne
{
Public static void main(String a[])
{
int a[]={10,20,30};
for(int i=0;i<3;i++)
{
[Link](a[i]);
}
}
}

Assigning the values into an array: The process of storing the values into an array after the
allocation of memory is said to be assigning the values into an array.
class ArrayTwo
{
Public static void main(String a[])
{
int i;
int a[]=new int[3];
a[0]=100;
a[1]=200;
a[2]=300;
for(i=0;i<3;i++)
{
[Link](a[i]);
}
}
}

Accepting the values into an array


import [Link].*;
class ArrayOneAccept
{
Public static void main(String a[])
{
BufferedReader br = new Buffered Reader(new InputStreamReader([Link]));
int n,i;
[Link](“Enter the number of the values to be stored in the array……”);
n=[Link]([Link]());
int a[]=new int[n];
[Link](“Enter the “+n+” values);
for(i=0;i<n;i++)
{
a[i]=[Link]([Link]());
}
[Link](“The values are….”);
for(i=0;i<n;i++)
{
[Link](a[i]);
}
}
}

Two Dimensional Array:


 In this array, every element consists of two indices.
 One index represents row number and the other index represents column number.
 These are arrays are used in solving matrices.
 These are arrays are also called as Array of Array, because 2-Dimensional array contains a
group of single dimensional arrays as a part of it.

Initialization Of 2-Dimensional Array:


datatype arrayname[][]={
{ value1,value2,……,valuen};
{ value1,value2,……,valuen};
{ value1,value2,……,valuen};
};

class ArrayTwoDim
{
public static void main(String a[])
{
int i,j;
int a[][]={{10,20},{30,40}};
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
[Link](a[i][j]+” “);
}
[Link](“\n”);
}
}
}
Three Dimensional Array:
 In 3-D arrays every element consists of 3 dimensions
 In 3-D arrays every element consists of 3 indices
 First index number represents the index of single dimensional array
 The next two indices represents row, column number of a two dimensional array.
 3-D array consists of a single dimensional array and every element of a single dimensional
array consists of 2-d array.

Strings:
 Most of the data that transmits on Internet will be in the form of groups of characters. Such
groups of characters are called 'strings'.
 For example, in a business order form, a person enters details like his name, credit card
number, address, etc., which are all nothing but Strings only.
 So a string represents a group of characters.
 In C/C++ languages, a string represents an array of characters, where the last character will
be '\0' (called null character).
 This last character being '\0' represents the end of the string. But this is not valid in Java. In
Java, a string is an object of String class. It is not a character array.
 In Java, we got character arrays also, but strings are given a different treatment because of
their extensive use on Internet.
 Java Soft people have created a class separately with the name ‘String’ in [Link]
(language) package with all necessary methods to work with strings.
 But in Java all classes are also considered as data types. So, we can also say class String as a
data type.
 Even though String is a class, it is used often used in the form of a datatype as:
String s=”java”; Here, s is a variable of the data type 'String'.

Is String a class or data type?


 String is a class in [Link] package.
 But in Java, all classes are also considered as data types.
 So we can take String as a data type also.

Can we call a class as a data type?


 Yes, a class is also called 'user-defined' data type. This is because a user can create a class.

Java String compare

 We can compare string in java on the basis of content and reference.


 It is used in authentication (by equals() method), sorting (by compareTo()
Method), reference matching (by == operator) etc.

There are three ways to compare string in java:


 By equals() method
 By = = operator
 By compareTo() method
1) String compare by equals() method: The String equals() method compares the original content
of the string. It compares values of string for equality.
String class provides two methods:
 public boolean equals(Object another) compares this string to the specified object.
 public boolean equalsIgnoreCase(String another) compares this String to another string,
by ignoring case.
class Teststringcomparison1
{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
[Link]([Link](s2));//true
[Link]([Link](s3));//true
[Link]([Link](s4));//false
}
}

Output:
true
true
false

class Teststringcomparison2
{
public static void main(String args[])
{
String s1="Sachin";
String s2="SACHIN";
[Link]([Link](s2));//false
[Link]([Link](s2));//true
}
}
Output:
false
true

2) String compare by == operator: The = = operator compares references not values.

class Teststringcomparison3
{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
[Link](s1==s2);//true (because both refer to same instance)
[Link](s1==s3);//false(because s3 refers to instance created in nonpool)
}
}
Output:
true
false

3) String compare by compareTo() method: The String compareTo() method compares values
lexicographically and returns an integer value that describes if first string is less than, equal to or
greater than second string.

Suppose s1 and s2 are two string variables. If:


s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value

class Teststringcomparison4
{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
[Link]([Link](s2));//0
[Link]([Link](s3));//1(because s1>s3)
[Link]([Link](s1));//-1(because s3 < s1 )
}
}

Output:
0
1
-1
String Concatenation in Java
In java, string concatenation forms a new string that is the combination of multiple strings. There are
two ways to concat string in java:
 By + (string concatenation) operator
 By concat() method

1) String Concatenation by + (string concatenation) operator


Java string concatenation operator (+) is used to add strings. For Example:
class TestStringConcatenation1
{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
[Link](s);//Sachin Tendulkar
}
}
Output:
Sachin Tendulkar

The Java compiler transforms above code to this:

String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();

In java, String concatenation is implemented through the StringBuilder (or StringBuffer) class and its
append method. String concatenation operator produces a new string by appending the second
operand onto the end of the first operand. The string concatenation operator can concat not only
string but primitive values also. For Example:

class TestStringConcatenation2
{
public static void main(String args[]){
String s=50+30+"Sachin"+40+40;
[Link](s);//80Sachin4040
}
}
Output:
80Sachin4040

Note: After a string literal, all the + will be treated as string concatenation operator.

2) String Concatenation by concat() method


The String concat() method concatenates the specified string to the end of current string.
Syntax: public String concat(String another)
Let's see the example of String concat() method.
class TestStringConcatenation3
{
public static void main(String args[])
{
String s1="Sachin ";
String s2="Tendulkar";
String s3=[Link](s2);
[Link](s3);//Sachin Tendulkar
}
}

Sachin Tendulkar

Substring in Java
A part of string is called substring. In other words, substring is a subset of another string. In case of
substring startIndex is inclusive and endIndex is exclusive.
Note: Index starts from 0.
 You can get substring from the given string object by one of the two methods:
 public String substring(int startIndex): This method returns new String object containing
the substring of the given string from specified startIndex (inclusive).
 public String substring(int startIndex, int endIndex): This method returns new String
object containing the substring of the given string from specified startIndex to endIndex.

In case of string:
 startIndex: inclusive
 endIndex: exclusive

Let's understand the startIndex and endIndex by the code given below.
 String s="hello";
 [Link]([Link](0,2));//he
 In the above substring, 0 points to h but 2 points to e (because end index is exclusive).

Example of java substring


public class TestSubstring
{
public static void main(String args[])
{
String s="SachinTendulkar";
[Link]([Link](6));//Tendulkar
[Link]([Link](0,6));//Sachin
}
}

Output:
Tendulkar
Sachin

Java StringBuffer class


Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is
same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously.
So it is safe and will result in an order.

Important Constructors of StringBuffer class

Constructor Description

StringBuffer() creates an empty string buffer with the initial capacity of 16.

StringBuffer(String str) creates a string buffer with the specified string.

StringBuffer(int creates an empty string buffer with the specified capacity as


capacity) length.

Important methods of StringBuffer class


Modifier and Method Description
Type

public append(String s) is used to append the specified string with this string. The
synchronized append() method is overloaded like append(char),
StringBuffer append(boolean), append(int), append(float),
append(double) etc.

public insert(int offset, String s) is used to insert the specified string with this string at the
synchronized specified position. The insert() method is overloaded like
StringBuffer insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.

public replace(int startIndex, int is used to replace the string from specified startIndex and
synchronized endIndex, String str) endIndex.
StringBuffer

public delete(int startIndex, int is used to delete the string from specified startIndex and
synchronized endIndex) endIndex.
StringBuffer

public reverse() is used to reverse the string.


synchronized
StringBuffer

public int capacity() is used to return the current capacity.

public void ensureCapacity(int is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.

public char charAt(int index) is used to return the character at the specified position.

public int length() is used to return the length of the string i.e. total number
of characters.

public String substring(int beginIndex) is used to return the substring from the specified
beginIndex.

public String substring(int beginIndex, is used to return the substring from the specified
int endIndex) beginIndex and endIndex.
What is mutable string: A string that can be modified or changed is known as mutable string.
StringBuffer and StringBuilder classes are used for creating mutable string.

1) StringBuffer append() method: The append() method concatenates the given argument with this
string.

class StringBufferExample
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
[Link]("Java");//now original string is changed
[Link](sb);//prints Hello Java
}
}

2) StringBuffer insert() method: The insert() method inserts the given string with this string at the
given position.

class StringBufferExample2
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
[Link](1,"Java");//now original string is changed
[Link](sb);//prints HJavaello
}
}

3) StringBuffer replace() method: The replace() method replaces the given string from the
specified beginIndex and endIndex.

class StringBufferExample3
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3,"Java");
[Link](sb);//prints HJavalo
}
}

4) StringBuffer delete() method: The delete() method of StringBuffer class deletes the string from
the specified beginIndex to endIndex.

class StringBufferExample4\{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3);
[Link](sb);//prints Hlo
}
}

5) StringBuffer reverse() method: The reverse() method of StringBuilder class reverses the
current string.

class StringBufferExample5
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
[Link]();
[Link](sb);//prints olleH
}
}

6) StringBuffer capacity() method: The capacity() method of StringBuffer class returns the current
capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases
from its current capacity, it increases the capacity by (oldcapacity*2)+2.

For example if your current capacity is 16, it will be (16*2)+2=34.

class StringBufferExample6
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

7) StringBuffer ensureCapacity() method: The ensureCapacity() method of StringBuffer class


ensures that the given capacity is the minimum to the current capacity. If it is greater than the current
capacity, it increases the capacity by (oldcapacity*2)+2.

For example if your current capacity is 16, it will be (16*2)+2=34.

class StringBufferExample7
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
[Link](10);//now no change
[Link]([Link]());//now 34
[Link](50);//now (34*2)+2
[Link]([Link]());//now 70
}
}

Java StringBuilder class: Java StringBuilder class is used to create mutable (modifiable) string. The
Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is
available since JDK 1.5.

Important Constructors of StringBuilder class

Constructor Description

StringBuilder() creates an empty string Builder with the initial capacity of 16.

StringBuilder(String str) creates a string Builder with the specified string.

StringBuilder(int length) creates an empty string Builder with the specified capacity as length.

Important methods of StringBuilder class

Method Description

public StringBuilder is used to append the specified string with this string. The append()
append(String s) method is overloaded like append(char), append(boolean),
append(int), append(float), append(double) etc.

public StringBuilder insert(int is used to insert the specified string with this string at the specified
offset, String s) position. The insert() method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int, float), insert(int,
double) etc.

public StringBuilder replace(int is used to replace the string from specified startIndex and endIndex.
startIndex, int endIndex, String
str)

public StringBuilder delete(int is used to delete the string from specified startIndex and endIndex.
startIndex, int endIndex)
public StringBuilder reverse() is used to reverse the string.

public int capacity() is used to return the current capacity.

public void ensureCapacity(int is used to ensure the capacity at least equal to the given minimum.
minimumCapacity)

public char charAt(int index) is used to return the character at the specified position.

public int length() is used to return the length of the string i.e. total number of
characters.

public String substring(int is used to return the substring from the specified beginIndex.
beginIndex)

public String substring(int is used to return the substring from the specified beginIndex and
beginIndex, int endIndex) endIndex.

Java StringBuilder Examples


Let's see the examples of different methods of StringBuilder class.

1) StringBuilder append() method: The StringBuilder append() method concatenates the given
argument with this string.

class StringBuilderExample
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello ");
[Link]("Java");//now original string is changed
[Link](sb);//prints Hello Java
}
}

2) StringBuilder insert() method: The StringBuilder insert() method inserts the given string with
this string at the given position.

class StringBuilderExample2
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello ");
[Link](1,"Java");//now original string is changed
[Link](sb);//prints HJavaello
}
}

3) StringBuilder replace() method: The StringBuilder replace() method replaces the given string
from the specified beginIndex and endIndex.

class StringBuilderExample3
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello");
[Link](1,3,"Java");
[Link](sb);//prints HJavalo
}
}

4) StringBuilder delete() method: The delete() method of StringBuilder class deletes the string
from the specified beginIndex to endIndex.

class StringBuilderExample4
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello");
[Link](1,3);
[Link](sb);//prints Hlo
}
}

5) StringBuilder reverse() method: The reverse() method of StringBuilder class reverses the
current string.

class StringBuilderExample5
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello");
[Link]();
[Link](sb);//prints olleH
}
}

6) StringBuilder capacity() method: The capacity() method of StringBuilder class returns the
current capacity of the Builder. The default capacity of the Builder is 16. If the number of character
increases from its current capacity, it increases the capacity by (oldcapacity*2)+2.
For example if your current capacity is 16, it will be (16*2)+2=34.
class StringBuilderExample6
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

7) StringBuilder ensureCapacity() method: The ensureCapacity() method of StringBuilder class


ensures that the given capacity is the minimum to the current capacity. If it is greater than the current
capacity, it increases the capacity by (oldcapacity*2)+2.
For example if your current capacity is 16, it will be (16*2)+2=34.

class StringBuilderExample7
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
[Link](10);//now no change
[Link]([Link]());//now 34
[Link](50);//now (34*2)+2
[Link]([Link]());//now 70
}
}

Difference between String and StringBuffer


There are many differences between String and StringBuffer. A list of differences between String
and StringBuffer are given below:
No. String StringBuffer

1) String class is immutable. StringBuffer class is mutable.

2) String is slow and consumes more memory when you StringBuffer is fast and consumes
concat too many strings because every time it creates less memory when you cancat
new instance. strings.
3) String class overrides the equals() method of Object StringBuffer class doesn't override
class. So you can compare the contents of two strings the equals() method of Object class.
by equals() method.

You might also like