Correct way to trim a string in Java

// Java program to demonstrate working
// of java string trim() method

class DID{

// driver code
public static void main(String args[])

	// trims the trailing and leading spaces
	String s = " the tapacademy has all java functions to read ";

	// trims the leading spaces
	s = " Chetna loves reading books";


I have learned this from here, just want to know if I am correct or not.

As per the String Javadoc, there are three different methods that will trim whitespace: trim(), stripLeading() and stripTrailing(). Depending on what you want to do, you need to use different methods. Your first example looks correct because you commented that you wanted to trim the leading and trailing whitespace. The second example may or may not be correct depending on what you wanted to demonstrate. For that particular string, trimming the leading whitespace and trimming both leading and trailing whitespace have the same effect. If you only wanted to trim leading whitespace (as your comment suggests) you should have used stripLeading() instead of trim().

So let me give an example that demonstrates all of the different cases:

public static void main(String[] args) {
  String example = " ABC ";
  var leading = example.stripLeading(); // "ABC "
  var trailing = example.stripTrailing(); // " ABC"
  var trim = example.trim(); // "ABC"
    "leading='%s', trailing='%s', trim='%s'", leading, trailing, trim);

Hope that helps to improve your understanding!