Understanding Java String methods with examples

Understanding Java String methods with examples

Representing the sequence of char values is done by an object named “Strings”. This object is used to print alphabetical characters. Java string methods can perform various kinds of operations such as substring, compare, concat, equals, split, length, replace, compareTo, intern, etc. The Serializable, Comparable, and CharSequence interfaces are implemented by the java.lang.String class.

What are Strings and Char?

A string is typically a series of characters in a programming language, either as a literal constant or as some sort of variable. The letter can either be fixed in length or allow its elements to alter.

A string in Java is a group of characters that is an instance of an object belonging to java.lang class. The string class in Java is used to produce and edit strings. A string cannot have its value modified after it has been generated. Strings are collections of characters.

String welcome = "Hello";

The Unicode coding system, which was created to support a number of different world languages, is used to store letters and symbols in the character datatype, also known as char. Put characters between single quotes (‘P’) to make them stand out from other symbols. The char is used placing them between single quotes e.g. ‘A’, ‘P’, etc.

char result = 'B';
System.out.println(result);
Is same as 
char[] ch ={'j','a','v','a','t','p','o','i','n','t'}; 
String example = new String(ch);  
System.out.println(example);
Is same as 
String new = “javapoint”

Also read, Why Java is so popular among Developers!

How to create a String object?

We use String literal or new keyword to create a String object. With the help of double quotes (“”) we create a string literal.

String new = “Welcome”;

Using String Literal

The “string constant pool” is checked first by the JVM whenever a string literal is created. A reference to the pooled instance of the string is returned if it already exists. If the string is missing from the pool, a new instance of the string is produced and added to the pool. 

String new1 = “Welcome”;
String new2 = “Welcome”; // It doesn’t create a new instance.

There will only be one thing produced. First off, the JVM will construct a new object since it cannot identify an existing string object in the string constant pool that has the value “Welcome.” Following that, it will search the pool for the string with the value “Welcome,” returning a reference to the same instance rather than creating a new one. Generally, String literal is used by every programmer as it uses less memory because no new objects will be created in the String constant pool.

Using New Keyword

In this scenario, the literal “Welcome” will be added to the string constant pool and a new string object will be created in regular (non-pool) heap memory by the JVM. The object in a heap will be identified by the variable s (non-pool).

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

Also read, Writing Your First Program in Java

What is StringBuffer?

The introduction of StringBuffer coincided with Java’s initial release. It is coordinated. The thread is secure. Because numerous threads are unable to access at once, it is slow. It can change. Strings can be changed without an object being created.

public class StringBuilderExample{
   public static void main(String[] args){
      StringBuilder builder=new StringBuilder("Hi");
      builder.append("Java 8");
      System.out.println("StringBuilderExample" +builder);
   }
}

Also read, Why the SaaS Market is Now Anyone’s Game

What is StringBuilder?

Java’s StringBuilder class is used to build mutable, or otherwise changeable, strings of characters. The Java Strings class allows an immutable set of characters; equivalent to StringBuffer, the StringBuilder class provides an alternate. However, StringBuilder and StringBuffer differ significantly in one important way: the latter is non-synchronized. Due to its speed advantage over StringBuffer when using a single thread, StringBuilder in Java is a better option.

public class StringBufferExample{
   public static void main(String] [args){
      StringBuffer buffer=new StringBuffer("Hi");
      buffer.append("Java 8");
      System.out.println("StringBufferExample" +buffer);
   }
}

Also read, Learn about Java Datatypes and how we use them

Different types of String methods and examples

I have explained different String methods as much as I can in this class with their respective examples you can copy these examples and run them in your compiler for a better understanding.

charAt()

The character returns to the specified index.

Return Type

char

Example

public class Main {
  public static void main(String[] args) {
    String myStr = "Hello";
    char result = myStr.charAt(2);
    System.out.println(result);
  }
}

codePointAt()

Unicode of character is returned for a specified index.

Return Type

int

Example

public class Main {
  public static void main(String[] args) {
    String myStr = "Hello";
    int result = myStr.codePointAt(3);
    System.out.println(result);
  }
}

codePointBefore()

The Unicode of the character is returned before specifying the index.

Return Type

int

Example

public class Main {
  public static void main(String[] args) {
    String myStr = "Hello";
    int result = myStr.codePointBefore(2);
    System.out.println(result);
  }
}

toLowerCase()

This converts the string to lowercase.

Return Type

String

Example

public class Main {
  public static void main(String[] args) {
    String txt = "HELLO WORLD";
    System.out.println(txt.toLowerCase());
  }
}

toUpperCase()

This converts the string to upper case letters.

Return Type

String

Example

public class Main {
  public static void main(String[] args) {
    String txt = "hello world";
    System.out.println(txt.toUpperCase());
  }
}

length()

It shows the length of the string.

Return Type

int

Example

public class Main {
  public static void main(String[] args) {
    String txt = "BCDEFGHIJKLMNOPQRSTUVWXY";
    System.out.println(txt.length());
  }
}

trim()

From both ends, this method removes the whitespace in the string.

Return Type

String

Example

public class Main {
  public static void main(String[] args) {
    String myStr = "       Hello Class!        ";
    System.out.println(myStr);
    System.out.println(myStr.trim());
  }
}

contains()

This method determines whether a string includes a specific character sequence.

Return Type

Boolean

Example

public class Main {
  public static void main(String[] args) {
    String myStr = "Hello";
    System.out.println(myStr.contains("Hel"));
    System.out.println(myStr.contains("e"));
    System.out.println(myStr.contains("Hi"));
    System.out.println(myStr.contains("Hol"));
  }
}

isEmpty()

This method determines whether or not a string is empty.

Return Type

Boolean

Example

public class Main {
  public static void main(String[] args) {
    String myStr1 = "BonJour";
    String myStr2 = "";
    System.out.println(myStr1.isEmpty());
    System.out.println(myStr2.isEmpty());
  }
}

endWith()

This method determines whether a string has the specific character at the end (s)

Return Type

Boolean

Example

public class Main {
  public static void main(String[] args) {
    String myStr = "BonJour";
    System.out.println(myStr.endsWith("Bon"));
    System.out.println(myStr.endsWith("ur"));
    System.out.println(myStr.endsWith("Jour"));
  }
}

Also read, Simple explanation of Java Operators

Final Words

The String is one of the most important parts of Java programming language as it is the most used. his object is used to print alphabetical characters. “Strings” can perform various kinds of operations such as substring, compare, concat, equals, split, length, replace, compareTo, intern, etc.

A string is typically a series of characters in a programming language, either as a literal constant or as some sort of variable whereas char is known for the Unicode coding system, which was created to support a number of different world languages, and is used to store letters and symbols in the character datatype.

There are a number of String methods I have mentioned a few of them with their examples so that you can understand them easily. By copying those examples on your compiler and running it you will see the output you can make a few changes in those inputs but be careful while making changes there is a chance you might change the String methods instead of the variables input. I hope you are getting through the blog if you have any doubt regarding the blog please let me know in the comment or you can contact me.