Day 8 : String, String Methods, String Builder and String Buffer in Java

Day 8 : String, String Methods, String Builder and String Buffer in Java

String :

String is an object that represents a sequence of characters. The java.lang.String class is used to create a string object.

How to create a string object?

There are two ways to create String object:

  • By string literal
  • By new keyword

String Literal :

  • Java String literal is created by using double quotes.
  • Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool.

Example :

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

In this example :

  • Only one object will be created.
  • Firstly, JVM will not find any string object with the value "Welcome" in string constant pool that is why it will create a new object.
  • After that it will find the string with the value "Welcome" in the pool, it will not create a new object but will return the reference to the same instance.

By new keyword :

String?s=new?String("Welcome");//creates?two?objects?and?one?reference?variable??        

In this case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-pool).

Example :

public class StringExample{    
public static void main(String args[]){    
String s1="java"; // creating string by Java string literal    
char ch[]={'s','t','r','i','n','g','s'};    
String s2=new String(ch); // converting char array to string    
String s3=new String("example"); // creating Java string by new keyword    
System.out.println(s1);    
System.out.println(s2);    
System.out.println(s3);    
}
}            
Output :
java
strings
example        

In this example :

  • Converts a char array into a String object. And displays the String objects s1, s2, and s3 on console using println() method.

String class methods :

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

  • charAt() - The charAt() method returns char value for the particular index.
  • length() - The length() returns length of charcters in a String.
  • format() - The format() method returns a formatted string based on the argument passed.
  • replace() - The replace() method replaces each matching occurrence of a character/text in the string with the new character/text.
  • replaceAll() - The replaceAll() method replaces each substring that matches the regex of the string with the specified text.
  • replaceFirst() - The replaceFirst() method returns a new string where the first occurrence of the matching substring is replaced with the replacement string.
  • substring() - The substring() method extracts a part of the string (substring) and returns it.
  • equals() - The equals() method returns true if two strings are identical and false if the strings are different.
  • equalsIgnoreCase() - It compares another string. It doesn't check case. returns true if the strings are equal, ignoring case considerations. returns false if the strings are not equal. returns false if the str argument is null.
  • contains() - The contains() method checks whether the specified string (sequence of characters) is present in the string or not.
  • indexOf() - The indexOf() method returns the index of the first occurrence of the specified character/substring within the string.
  • trim() - The trim() method removes any leading (starting) and trailing (ending) whitespaces from the specified string.
  • toLowerCase() - The toLowerCase() method converts all characters in the string to lowercase characters.
  • toUpperCase() - The toUpperCase() method converts all characters in the string to uppercase characters.
  • concat() - The concat() method concatenates (joins) two strings and returns it.
  • valueOf() - The valueOf() method returns the string representation of the argument passed.
  • matches() - The matches() method checks whether the string matches the given regular expression or not.
  • startsWith() - The startsWith() method checks whether the string begins with the specified string or not.
  • endsWith() - The endsWith() method checks whether the string ends with the specified string or not.
  • isEmpty() - The isEmpty() method checks if string is empty.
  • intern() - The intern() method a canonical representation of the string.
  • getBytes() - The getBytes() method returns a byte array.
  • contentEquals() - The contentEquals() method returns true if the string contains the same sequence of characters as the specified parameter. If not, returns false.
  • hashCode() - The hashCode() method returns the hashcode, which is an int value, of the string.
  • join() - The join() method returns a new string with the given elements joined with the specified delimiter.
  • subSequence() - The subSequence() method returns a CharSequence.
  • toCharArray() - The toCharArray() method returns a char array.

String Buffer :

  • Mutable : Unlike String, which is immutable (its contents cannot be changed after it is created), StringBuffer is mutable. This means you can append, insert, replace, and delete characters in a StringBuffer object without creating new strings.
  • Thread-safe : StringBuffer is designed to be thread-safe. It includes synchronized methods to ensure that multiple threads can manipulate the same StringBuffer instance safely.
  • Performance : Due to its mutability, StringBuffer can be more efficient than String for operations that involve frequent modifications (e.g., concatenation in a loop).

Example :

public class StringBufferExample{  
    public static void main(String[] args){  
        StringBuffer buffer = new StringBuffer("hello");  
        buffer.append("java");  
        System.out.println(buffer);  
    }  
}          
Output :
hellojava        

In this example :

  • StringBuffer buffer = new StringBuffer("hello"); : Creates a new StringBuffer object initialized with the string "hello". Unlike String, StringBuffer is mutable, so you can modify its content.
  • buffer.append("java"); : Modifies the buffer by appending the string "java" to its existing content. This operation does not create a new String object but modifies the internal buffer of buffer.
  • System.out.println(buffer); : Prints the content of buffer to the console. After appending "java", the content of buffer is "hellojava".

String Builder :

  • Mutable: Like StringBuffer, StringBuilder is mutable, meaning you can modify the sequence of characters it holds without creating new objects.
  • Not Thread-safe: Unlike StringBuffer, StringBuilder is not synchronized. This means it is not suitable for concurrent access by multiple threads unless you synchronize it externally.
  • Performance: StringBuilder is generally faster than StringBuffer because it does not incur the overhead of synchronization.

Example :

public class StringBuilderExample{  
    public static void main(String[] args){  
        StringBuilder builder=new StringBuilder("hello");  
        builder.append("java");  
        System.out.println(builder);  
    }  
}          
Output :
hellojava        

In this example :

  • StringBuilder builder = new StringBuilder("hello"); : Creates a new StringBuilder object initialized with the string "hello". Unlike String, StringBuilder is mutable, so you can modify its content.
  • builder.append("java"); : Modifies the builder by appending the string "java" to its existing content. This operation does not create a new String object but modifies the internal buffer of builder.
  • System.out.println(builder); : Prints the content of builder to the console. After appending "java", the content of builder is "hellojava".

Difference Between String, String Buffer and String Builder

  • Concurrency: Use StringBuffer for thread-safe operations and StringBuilder for better performance in single-threaded scenarios.
  • Performance: StringBuilder generally performs better than StringBuffer due to lack of synchronization overhead.
  • Immutability vs Mutability: String is immutable, while StringBuffer and StringBuilder are mutable, allowing direct modifications.

  • Use String when the content is fixed or shouldn’t change.
  • Use StringBuffer when thread safety is necessary or when you need to perform operations in a concurrent environment.
  • Use StringBuilder for most string manipulations in single-threaded applications where performance is crucial.


要查看或添加评论,请登录

POOJAASHREE P V的更多文章

  • Day 13 : File Handling in Java

    Day 13 : File Handling in Java

    File Class : The File class of the java.io package is used to perform various operations on files and directories.

  • Day 12 : Scanner Class in Java

    Day 12 : Scanner Class in Java

    Scanner Class : Scanner class in Java is found in the java.util package.

  • Day 11 : Exception Handling in Java

    Day 11 : Exception Handling in Java

    Exception : An exception is an event that disrupts the normal flow of the program. It is an object which is thrown at…

  • Day 10 : Arrays in Java

    Day 10 : Arrays in Java

    Arrays : Array is an object which contains elements of a similar data type. The elements of an array are stored in a…

  • Day 9 : Date and Time in Java

    Day 9 : Date and Time in Java

    Date and Time : In Java, managing date and time involves several classes from the package, introduced in Java 8. The…

  • Day 7 : Math Class and Math Methods in Java

    Day 7 : Math Class and Math Methods in Java

    Math Class : Math class provides several methods to work on math calculations like min(), max(), avg(), sin(), cos()…

  • Day 6 : Methods in Java

    Day 6 : Methods in Java

    Method : A method is a block of code or collection of statements or a set of code grouped together to perform a certain…

  • Day 5 : Looping Statements in Java

    Day 5 : Looping Statements in Java

    Looping Statements : Looping statements are used to execute a block of code repeatedly based on certain conditions…

    1 条评论
  • Day 4 : Conditional Statements in Java

    Day 4 : Conditional Statements in Java

    Conditional Statements : Conditional statements are control flow statements that allow you to execute different blocks…

  • Day 3 : Variables, Data Types and Operators

    Day 3 : Variables, Data Types and Operators

    Variables : A variable is a container which holds the value while the Java program is executed. A variable is assigned…

社区洞察

其他会员也浏览了