You are on page 1of 10

STRINGS

In C/C++ languages, a string represents an array of characters, where the 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.String is a class avalabile in
java.lang package.String is a class , it can be used like a data type, as:
String s=”java”;
here s is an object of class String.
String is immutable object which means that it cannot be changed once it is
created.
Mutable object – You can change the states and fields after the object is
created. For examples: StringBuilder, java.util.Date and etc.
Immutable object – You cannot change anything after the object is created. For
examples: String, boxed primitive objects like Integer, Long and etc.

How to create a string object?


There are two ways to create String object:
• By string literal
• By new keyword

1) String Literal
This is the most common way of creating string. In this case a string literal is
enclosed with double quotes.

String s1="welcome";

String s2="welcome"; //It doesn't create a new instance


When we create a String using double quotes, JVM looks in the string pool
to find if any other String is stored with same value. If found, it just returns
the reference to that String object else it creates a new String object with
given value and stores it in the String pool.

2) By new keyword
By using new keyword we can create two different object in memory having
the same string.
String str1 = new String("Welcome");
String str2 = new String("Welcome");

3) The third way of creating the strings is by converting the character arrays
into strings. Let us take a character type array: arr[] With some characters, as:
char arr[]={‘a’,’c’,’e’,’q’};
Now create a string object, by passing the array name to it, as:
String s=new String(arr);
Immutable String in Java:
In java, string objects are immutable. Immutable simply means unmodifiable
or unchangeable.
Once string object is created its data or state can't be changed but a new
string object is created.
ex: class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable
objects
}
}
Output:Sachin
Now it can be understood by the diagram given below. Here Sachin is not
changed but a new object is created with sachintendulkar. That is why string
is known as immutable.
As you can see in the above figure that two objects are created but s
reference variable still refers to "Sachin" not to "Sachin Tendulkar".

But if we explicitely assign it to the reference variable, it will refer to "Sachin


Tendulkar" object.For example:

class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
In such case, s points to the "Sachin Tendulkar". Please notice that still
sachin object is not modified.
Java StringBuffer class:
The StringBuffer class in java is used to create strings same as String class.
but by using StringBuffer class we can create mutable objects whereas String
class is used to create immutable (unmodifiable) string.
ex: class Testimmutablestring{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
output : Hello java
StringBuffer Class Method
StringBuffer append(x): It is used to add text at the end of the existence
text. Here are a few of its forms:
StringBuffer append(String str)
StringBuffer append(int num)
ex: StringBuffer sb = new StringBuffer("Hello ");
sb.append("World ");
sb.append(2017);
System.out.println(sb);
Output: Hello World 2017
StringBuffer insert(): It is used to insert text at the specified index
position. These are a few of its forms:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
Here, index specifies the index at which point the string will be inserted into
the invoking StringBuffer object.
import java.io.*;
class ex {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("BooksBooks");
s.insert(5, "for");
System.out.println(s); // returns BooksforBooks
s.insert(0, 5);
System.out.println(s); // returns 5BooksforBooks
s.insert(3, true);
System.out.println(s); // returns 5BotrueoksforBooks
}
}
delete(int startIndex, int endIndex): accepts two integer arguments. The
former serves as the starting delete index and latter as the ending delete
index. Therefore the character sequence between startIndex and endIndex–1
are deleted. The remaining String content in the buffer is returned.
StringBuffer sb = new StringBuffer("Hello World");
System.out.println(sb.delete(5,11)); //prints Hello
deleteCharAt(int index): deletes single character within the String inside
the buffer. The location of the deleted character is determined by the passed
integer index. The remaining String content in the buffer is returned.
StringBuffer sb = new StringBuffer("Hello World!");
System.out.println(sb.deleteCharAt(11)); //prints "Hello World".
reverse(): Reverses the existing String or character sequence content in the
buffer and returns it. The object must have an existing content or else a
NullPointerException is thrown.
StringBuffer sb = new StringBuffer("Hello World");
System.out.println(sb.reverse());
length(): Returns the StringBuffer object’s length.
capacity(): Returns the total allocated capacity of the StringBuffer object.
package com.journaldev.java;
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
int sbLength = sb.length();
int sbCapacity = sb.capacity();
System.out.println("String Length of " + sb + " is " +
sbLength);
System.out.println("Capacity of " + sb + " is " +
sbCapacity);
}
}
Output produced by above StringBuffer example program:
String Length of Hello is 5
Capacity of Hello is 21Output: dlroW olleH
toString(): The toString() method of StringBuffer class is the inbuilt method
used to returns a string representing the data contained by StringBuffer
Object.
class gg {
public static void main(String[] args)
{
// create a StringBuffer object
// with a String pass as parameter
StringBuffer str
= new StringBuffer("booksForbooks"); // print string
System.out.println("String contains = "
+ str.toString());
}}
Output:String contains = booksForbooks
substring(int beginIndex): is used to return the substring from the
specified beginIndex.
public String substring(int beginIndex, int endIndex): is used to
return the substring from the specified beginIndex and endIndex.

STRING ARRAY:
java string array is used to hold fixed number of Strings. Sttring array is very
common in simple java programs, specially among beginners to java and to
test some specific scenarios. Even java main method argument is string array
– public static void main(String[] args).

• Java String array is basically an array of objects.


• There are two ways to declare string array – declaration without size and
declare with size.
• There are two ways to initialize string array – at the time of declaration,
populating values after declaration.
• We can do different kind of processing on string array such as iteration,
sorting, searching etc.

Java String Array Declaration


Below code snippet shows different ways for string array
declaration in java.
String[] strArray; //declare without size

String[] strArray1 = new String[3]; //declare with size

In the above code, strArray is null whereas strArray1 value is [null,


null, null].

String[] thisIsAStringArray = new String[5];


String Array Initialization
String[] thisIsAStringArray = new String[5];
thisIsAStringArray[0] = "AAA";
thisIsAStringArray[1] = "BBB";
thisIsAStringArray[2] = "CCC";
thisIsAStringArray[3] = "DDD";
thisIsAStringArray[4] = "EEE";

Note, since there are only 5 elements and index started from 0, the last index will
be 4. Or we could use the formula ( array length - 1). This means if we access the
index greater than 4, an Exception will be raised. Example:
String[] thisIsAStringArray = new String[5];
thisIsAStringArray[5] = "FFF";

The code will throw a java.lang.ArrayIndexOutOfBoundsException


There are multiple ways to initialize a String Array. Initialization can also be done
at the same time as the declaration. Here is an example:
string[] thisIsAStringArray = {"AAA", "BBB", "CCC",
"DDD", "EEE"};
This will create a String Array of length 5. Element at index 0
will have the value "AAA", element at index 1 will have the
value "BBB", and so on. Hence, when we run this code:

String[] thisIsAStringArray = {"AAA", "BBB", "CCC",


"DDD", "EEE"};
System.out.println( thisIsAStringArray[0] );
System.out.println( thisIsAStringArray[1] );
System.out.println( thisIsAStringArray[2] );
System.out.println( thisIsAStringArray[3] );
System.out.println( thisIsAStringArray[4] );

It will produce this output:


AAA
BBB
CCC
DDD
EEE

Note that initializing an array will override the old


contents of the array. For example

String[] thisIsAStringArray = {"Apple", "Banana", "Orange"};

thisIsAStringArray = new String[] {"Asparagus", "Carrot",


"Tomato"};
System.out.println( thisIsAStringArray[0] );
System.out.println( thisIsAStringArray[1] );
System.out.println( thisIsAStringArray[2] );

The code will have the output below. This is because the old
contents {"Apple", "Banana", "Orange"}, will be discarded and
replaced with the new contents.

Asparagus

Carrot
Tomato

You might also like