HTML Java

Java String


String

  • String is a non-primitive datatype and a sequence of characters like “codersarts”.
  • When we create a string then we creates an object and its immutable object.
  • Means when its created can’t change and String is the only class where operator overloading supports in java.
  • Although, it uses String Buffer internally to perform concatenation.

String internally creates an array of Character or implicitly provides the implementation of an array.



String handling

The process of performing operation over the string is called string handling.

In order to perform operations on string java has so many classes.

  • String
  • StringBuffer
  • StringBuilder
  • StringTokenizer

“coders”+”arts” =codersarts

And we have 2 classes for manipulation in string in java

  • StringBuffer
  • StringBuilder


How to create a String?

We can create string by two ways:

  • Using string literal

    String companyName = “codersarts”;
    when we create string like this then jvm looks in the String constant pool and find value if stored there then it return the reference to that object(companyName) in this case otherwise it create a new String.

  • Using new keyword

    String companyName = new String(“codersarts”);
    We can create String object using new operator, just like any normal java class.



Comparison of String in java

Following methods are available for comparison in java

  • equals(),
  • equalsIgnoreCase(),
  • ==,
  • comapreTo(),
  • comapreToIgnoreCase()

Example

package com.string;

public class StringComparison {

  public static void main(String args[]) {
   String s1 = "coders";
   String s2 = "arts";
   String s3 = "Coders";
   String s4 = new String("arts");
   System.out.println(s2.equals(s4));
   System.out.println(s2.equals(s3));
   System.out.println(s1.equalsIgnoreCase(s3));
   System.out.println(s2==s4);
   System.out.println(s1.compareTo(s2));
   System.out.println(s1.compareTo(s3));
   System.out.println(s2.compareToIgnoreCase(s4));
 }
}
Try it »


Java String methods

  • split(): Its use to split the string using given regex expression 2 types of split() method.

    split(String regexExpression): This method Splits the String with the given Expression and return the array of string.

  • split(String regexExpression, int limit): This method Splits the String with the given Expression and return the array of string with the given limit.


String Constant Pool

  • JVM introduces special memory area for Strings called String Constatnt Pool.
  • Whenever we creates String literal then JVM first check in the pool.
  • And if the literal is present then it return the refernce of the String which is present in the pool or else a new String is created.