Overview
In this post, we will learn basic String class methods that we use frequently when we deal with Strings in Java. Some of the methods are:
- length()
- substring()
- trim()
String basic handling can be found here: https://www.testingdocs.com/questions/string-handling-in-java/
length()
This method returns the length of the String. In other words, this method returns the number of characters ( Unicode code units) in the String.
For example:
String str=”abc”;
str.length() would return 3.
substring()
substring() String method will extract a portion of the original string. Let’s write a simple code to demonstrate the usage of the method.
package com.testingdocs.tutorial; public class StringDemo { public static void main(String[] args) { String str="abcdefghijklmnopqrstuvwxyz"; String newStr=str.substring(0,5); System.out.println("Original String str= "+ str); System.out.println("Substring of str, newStr = "+ newStr); } }
trim()
package com.testingdocs.tutorial; public class StringDemo { public static void main(String[] args) { //Adding 4 white spaces String str="abcdefghijklmnopqrstuvwxyz "; String newStr=str.trim(); System.out.println("Original String str= "+ str); System.out.println("Original String Length= "+ str.length()); System.out.println("Trimmed String of str, newStr = "+ newStr); System.out.println("Trimmed String Length= "+ newStr.length()); } }