String

String is a Class in java and defined in java.lang package. It’s not a primitive data type like int and long. String class represents character Strings.

The Java platform provides the String class to create and manipulate strings. Strings are a sequence of characters. Java String class provides a lot of methods to perform operations on string such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

String is an immutable object which means it is a constant and can cannot be changed once it has been created. In this tutorial we will learn about String class and String methods.

Java String
Creating Strings:
The most direct way to create a string is to write:
1
String greeting ="Hello world!";


Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!.

Example:
1
2
3
4
5
6
7
8
public class DemoExampleString {

 public static void main(String args[]) {
  String str1 = new String("Hello Vinod");
  System.out.println(str1);

 }
}

Output: 
Hello Vinod

String Methods:
The String Class defines a number of methods that allow us to accomplish a variety of string manipulation tasks.
s2=s1.toLowerCase;      //converts the string s1 to all lowercase

s2=s1.toUpperCase;      //converts the string s1 to all Uppercase

s2=s1.replace('x','y');    //Replace all occurance of x with y

s2=s1.trim()                 //Removes the white spaces at the beginning and end of the String s1.

s1.equals(s2)               //Returns true if s1 is equal to s2

s1.equalsIgnoreCase(s2) //Returns true if s1=s2, ignoring the case of characters.

s1.length()                  //Gives the Length of s1

s1.charAt(n)                //Gives nth character of s1

s1.compareTo(s2)        //Returns negative if s1<s2,positive if s1>s2, and zero if s1 is equal to s2

s1.concat(s2)              //concatenates s1 and s2

s1.substring(n)            //Gives substring starting from nth character

s1.substring(n,m)        //Gives substring starting from nth charater upto mth

s1.indexOf('x')            //Gives the position of the first occurence of 'x' in the string s1.

s1.indexOf('x','n')        // Gives the position of the 'x' that occurs after nth position in the string s1.

Example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class String_Example {

   public static void main(String[] args) {

    String st1 = "This World is Very Nice";
    String st2 = " And Beautiful.";

    //Comparing two strings. Return true If both match else return false.
    System.out.println("st1 equals to st2? -> "+st1.equals(st2));

    //Concatenates st2 with st1.
    System.out.println("Concatenation of st1 and st2 Is -> "+st1.concat(st2));

    //Retrieve the 9th Indexed character from string.
    System.out.println("Character at Index 9 Is -> "+st1.charAt(9));
    
    //Find the length of string.
    System.out.println("Length Of St1 -> "+st1.length());    

    //Converting whole string In lower case.
    System.out.println("String In Lowercase -> "+st1.toLowerCase());   

    //Converting whole string In upper case.
    System.out.println("String In uppercase -> "+st1.toUpperCase());

    //Retrieve the Index of first 'i' character.
    System.out.println("Index of 1st charater i Is -> "+st1.indexOf('i'));

    //Retrieve the index of 2nd most 'i' character.
    System.out.println("Index of 2nd charater i Is -> "+st1.indexOf('i', 3));
    
    //Retrieve the Index of word 'Very' from string.
    System.out.println("Index of word Very Is -> "+st1.indexOf("Very"));

    //Converting value From int to string.
    int j = 75;
    String val2 = String.valueOf(j);
    System.out.println("Value Of string val2 Is -> "+val2);

    //Converting string to integer.
    String val1="50";
    int i = Integer.parseInt(val1);
    System.out.println("Value Of int i Is -> "+i);
    
    //Print the String starting from 5th Index to 12th Index.
    System.out.println("Retrieving sub string from string -> "+st1.substring(5, 13));

    //Split string. 
    String splt[] = st1.split("Very");
    System.out.println("String Part 1 Is -> "+splt[0]);
    System.out.println("String Part 2 Is -> "+splt[1]); 

    //Trim String.
    System.out.println("Trimmed st2 -> "+st2.trim()); 
   }
}
Output:
st1 equals to st2? -> false Concatenation of st1 and st2 Is -> This World is Very Nice And Beautiful. Character at Index 9 Is -> d Length Of St1 -> 23 String In Lowercase -> this world is very nice String In uppercase -> THIS WORLD IS VERY NICE Index of 1st charater i Is -> 2 Index of 2nd charater i Is -> 11 Index of word Very Is -> 14 Value Of string val2 Is -> 75 Value Of int i Is -> 50 Retrieving sub string from string -> World is String Part 1 Is -> This World is String Part 2 Is -> Nice Trimmed st2 -> And Beautiful.

Why String objects are immutable in Java?
String objects are immutable in Java means we can not modify or change them.
Once string object is created its information can not be changed.

Let's try to understand the immutability concept by the example given below:

1
2
3
4
5
6
7
8
class TestStringImmutability {

 public static void main(String args[]) {
  String s = "Hello";
  s.concat(" World!");// concat() method appends the string at the end
  System.out.println(s);// will print Hello because strings are immutable objects
 }
}
There are following reasons of why strings are immutable in Java
1) String pool can not be implemented without making Strings immutable or final
Example:
String s1 = "Java";
String s2 = "Java";

Now if s1 changes the object from "Java" to "C++", reference variable also got
value s2="C++", which it doesn't even know about it. By making String immutable,
this sharing of String literal is possible.
2) For security reasons, Java strings are implemented immutable. String is widely
used as parameter for many java classes, e.g. network connection, DB string, opening
files, etc. If String is mutable, a connection or file would be changed and could lead
to serious security threat.
3) As strings are immutable so they are naturally thread safe.
4) The hashcode of a string is frequently used in Java. Being immutable guarantees
that hashcode will always be the same so that it can be cashed without worrying
about the changes.

As we understand that String objects are immutable, and we cannot change String object. Whenever we want to perform any modifications in a string, in such a case we use String buffer or String builder.

String Buffer:
  1. String buffers are preferred when heavy modification of character strings is involved (appending, inserting, deleting, modifying etc).
  2. StringBuffer class is used to create a mutable string object. 
  3. It represents growable and writable character sequence. 
  4. It is also thread safe i.e multiple threads cannot access it simultaneously. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class DemoStringBuffer {
 
 public static void main(String[] args) {

  String str = "study";
  str.concat("tonight");
  System.out.println(str); // Output: study
  StringBuffer strB = new StringBuffer("study");
  strB.append("tonight");
  System.out.println(strB); // Output: studytonight
 }
}

1
2
3
4
5
6
7
8
public class DemoStringBuffer1 {

 public static void main(String args[]) {
  StringBuffer sb = new StringBuffer("Hello ");
  sb.insert(1, "Java");// now original string is changed
  System.out.println(sb);// prints HJavaello
 }
}

String Builder:
  • 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 (no guarantee of synchronization).
1
2
3
4
5
6
7
8
class StringBuilderDemo {

 public static void main(String args[]) {
  StringBuilder sb = new StringBuilder("Hello ");
  sb.append("World");// now original string is changed
  System.out.println(sb);// prints Hello World
 }
}

Difference between string buffer and builder


<-- Previous || Next -->

No comments:

Post a Comment