String in java example

  • String is a sequence of characters. But in Java, a string is an object that represents a sequence of characters.
  • The java.lang.String class is used to create string object.

There are two ways to create a String object:

(1)By string literal : Java String literal is created by using double quotes.
For Example: String s=“Welcome”;  

(2)By new keyword : Java String is created by using a keyword “new”.
For example: String s=new String(“Welcome”); It creates two objects (in String pool and in heap) and one reference variable where the variable ‘s’ will refer to the object in the heap.

What is Java String Pool?

Java String Pool: Java String pool refers to collection of Strings which are stored in heap memory. In this, whenever a new object is created, String pool first checks whether the object is already present in the pool or not. If it is present, then same reference is returned to the variable else new object will be created in the String pool and the respective reference will be returned. 

Before we go ahead, One key point we should know that Strings are immutable.

Immutable-By immutable, we mean that Strings are constant, their values cannot be changed after they are created. Because String objects are immutable, they can be shared. For example:

 String str =”abc”;
is equivalent to:

 char data[] = {‘a’, ‘b’, ‘c’};
 String str = new String(data);

Strings Method

length()-This function is used to return the length of the string(i.e.,number of character present in the string).You must note that the length is an integer number.Hence it return an integer value.

Syntax-int variable=string variable.length();

Example-String str="COMPUTER";

               int k=str.length();

Here,K=8,as number of characters available in the string str is 8.

 

charAt()-This function returns a character from the given index(position number) of the string

Syntax-char variable=string variable.charAt(index);

Example-String s="COMPUTER";

               char c=s.charAt(3);;

Here;c ='p' as the character at 3rd index is P.Please note that the index must not exceed the length of the string.

indexOf()-This function return the index(i.e. position number) of the string.

Syntax-int variable=string variable.indexOf(character);

Example-String s="COMPUTER";

                int n=s.indexOf 'P';

Here,the value returned by the function is 3.Hence,n=3.

              String s="MALAYALAM";

              int n=s.indexOf(4,'A');

This function will return the index of 'A' available in the string after 4th index.Hence ,n=5.

lastIndexOf()-This function is applied to find the index of last occurence of a character in a String.

Syntax-int variable=String variable.lastIndexOf(character);

Example-String s="MALAYALAM";

               int n=s.lastIndexOf('A');

               It returns 7 to the integer variable n.Hence,n=7.

substring()-This function is used to extract a part of string(i.e.,simultaneous character from one index to another).

Syntax-String variable1=string variable.substring(index);

Example-String s="COMPUTER";

                String p=s.substring(3);

The function will return all the character from the string starting from 3rd index.Hence,p=PUTER

trim()-This function is used to remove the blanks from either side of the string.Other blanks which are available in between the words,remain unchanged.

Syntax-String variable1=String variable.trim();

Example-String s="COMPUTER APPLICATIONS";

               String p=s.trim();

toLowerCase()-This function returns the character of the string in lower case letters.If any character is already in lower case or the character is a special character then it remains same.

Syntax-Striing variable1=string variable.toLowerCase();

Example-String s="COMPUTER";

               String p=s.toLowerCase();

Here ,p result "computer".

toUpperCase()-This funcction returns a string after converting all the character in upper case letters.If any character is already in upper case or the character is a special case character then it remain same.

Syntax-String variable1=string variable.toUpperCase();

Example-String s ="computer";

                String p=s.toUpperCase();

Here,p results "COMPUTER".

equals()-This function is used to compare two string together to check whether they are identical or not.It returns a Boolean type value true if bott are same,false otherwise.

Syntax-boolean variable=string variable1.equals(string variable 2);

Example-String x="COMPUTER";

               String y="computer";

               if(x.equals(y))

               System.out.println("same");

               else

               System.out.println("different");

The given program snippet display a different mesage.

You must note that equals() function treat corresponding upper case and lower case character differently.

You can use equalsIgnoreCase() function if you want to ignore case

Java String class methods

The java.lang.String class provides many useful methods to perform operations on sequence of char values.

No.MethodDescription
1char charAt(int index)returns char value for the particular index
2int length()returns string length
3static String format(String format, Object... args)returns a formatted string.
4static String format(Locale l, String format, Object... args)returns formatted string with given locale.
5String substring(int beginIndex)returns substring for given begin index.
6String substring(int beginIndex, int endIndex)returns substring for given begin index and end index.
7boolean contains(CharSequence s)returns true or false after matching the sequence of char value.
8static String join(CharSequence delimiter, CharSequence... elements)returns a joined string.
9static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)returns a joined string.
10boolean equals(Object another)checks the equality of string with the given object.
11boolean isEmpty()checks if string is empty.
12String concat(String str)concatenates the specified string.
13String replace(char old, char new)replaces all occurrences of the specified char value.
14String replace(CharSequence old, CharSequence new)replaces all occurrences of the specified CharSequence.
15static String equalsIgnoreCase(String another)compares another string. It doesn't check case.
16String[] split(String regex)returns a split string matching regex.
17String[] split(String regex, int limit)returns a split string matching regex and limit.
18String intern()returns an interned string.
19>int indexOf(int ch)returns the specified char value index.
20int indexOf(int ch, int fromIndex)returns the specified char value index starting with given index.
21int indexOf(String substring)returns the specified substring index.
22int indexOf(String substring, int fromIndex)returns the specified substring index starting with given index.
23String toLowerCase()returns a string in lowercase.
24String toLowerCase(Locale l)returns a string in lowercase using specified locale.
25String toUpperCase()returns a string in uppercase.
26String toUpperCase(Locale l)returns a string in uppercase using specified locale.
27String trim()removes beginning and ending spaces of this string.
28static String valueOf(int value)converts given type into string. It is an overloaded method.