Examveda

What is the purpose of the trim() method of a String object in Java?

A. To remove all spaces from the string

B. To concatenate two strings

C. To extract a substring from the string

D. To remove leading and trailing whitespace

Answer: Option D

Solution (By Examveda Team)

The trim() method in Java is used to remove whitespace characters from the beginning and end of a string.

It does not remove spaces or whitespace characters that are in the middle of the string.

For example:

String s = " Hello World ";
System.out.println(s.trim()); // Output: "Hello World"

Therefore, the correct purpose of the trim() method is to remove leading and trailing whitespace only, not all spaces, not concatenation, and not substring extraction.

This Question Belongs to Java Program >> Strings

Join The Discussion

Comments (1)

  1. Trilochan Pradhan
    Trilochan Pradhan:
    2 months ago

    In Java, the trim() method is used to remove leading and trailing whitespaces from a string.

    It does not remove spaces in the middle of the string.
    It returns a new string (since String is immutable).

Related Questions on Strings