Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

How to Manipulate Strings in Java

Learn how to manipulate strings in java with clear steps, practical context, and useful troubleshooting guidance.

Table of Contents

This updated guide examines How to Manipulate Strings in Java and organizes the essential facts, background, and practical takeaways in clear American English.

Method 1

Create a String

  1. How to Manipulate Strings in Java — contextual image 1 Create a string using the constructor of the String class.
    Stringstr=newString("Hello!");
  2. How to Manipulate Strings in Java — contextual image 2 Create a string by directly assigning a string.
  3. How to Manipulate Strings in Java — contextual image 3 Try an example. Here is a sample program that creates a string in two different ways.
    publicclassStringManipulation{publicstaticvoidmain(String[]args){Stringstr1=newString("String created with a constructor!");Stringstr2="String created without a constructor!";System.out.println(str1);System.out.println(str2);}}

Method 2

Find the Length of a String

  1. Understand what it means to find the length of a string. The length of a string is the number of characters that the string contains. For example, the length of the string "Hello!" is 6 because it has 6 characters.
  2. How to Manipulate Strings in Java — contextual image 4 Invoke thelength()method on the String object and store the result in an integer variable.
    intstrLength=str.length();
  3. How to Manipulate Strings in Java — contextual image 5 Give it a go. Here is a sample program that finds the length of a string.
    publicclassStringManipulation{publicstaticvoidmain(String[]args){Stringstr="Hello!";intstrLength=str.length();System.out.println("The length of ""+str+"" is "+strLength+".");}}

Method 3

Reverse a String

  1. How to Manipulate Strings in Java — contextual image 6 Understand what it means to reverse a string. Reversing a string means to switch the ordering of the characters in a string. For example, the reverse of the string "Hello!" is "!olleH". There are many ways to reverse a string in Java.
  2. How to Manipulate Strings in Java — contextual image 7 Use the reverse method of the StringBuffer class. Create a StringBuffer object that takes in the string that you want to reverse as a parameter. Use the StringBuffer's reverse() method and then retrieve the newly reversed string by using the toString() method.
    publicclassStringManipulation{publicstaticvoidmain(String[]args){Stringstr="Hello!";StringBufferbuffer=newStringBuffer(str);StringreversedStr=buffer.reverse().toString();System.out.println("The reverse of the string ""+str+"" is ""+reversedStr+"".");}}
  3. How to Manipulate Strings in Java — contextual image 8 Iterate through the characters in a string in reverse, appending these characters to a StringBuffer at each iteration. Create a new StringBuffer object initialized with the length of the string that you wish to reverse as the parameter. Then use a for loop to iterate through the string, starting from the last character in the string and ending at the first character in the string. At each iteration, append the character at that index to the StringBuffer. Retrieve the newly reversed string by using the toString() method.
    publicclassStringManipulation{publicstaticvoidmain(String[]args){Stringstr="Hello!";StringBufferbuffer=newStringBuffer(str.length());for(inti=str.length()-1;i>=0;i--){buffer.append(str.charAt(i));}StringreversedStr=buffer.toString();System.out.println("The reverse of the string ""+str+"" is ""+reversedStr+"".");}}
  4. How to Manipulate Strings in Java — contextual image 9 Write a recursive function to reverse the string. In the recursive function, the base case / condition is if the string is null or if the length of the string is less than or equal to none. Otherwise, the reverse() method is called again with the string minus the first character, and the first character is tacked on at the end. So if we passed in the string "Hello!", the first reverse() call after that will have the parameter "ello!".
    publicclassStringManipulation{publicstaticvoidmain(String[]args){Stringstr="Hello!";StringreversedStr=reverse(str);System.out.println("The reverse of the string ""+str+"" is ""+reversedStr+"".");}privatestaticStringreverse(Stringstr){if(str==null||str.length()<=1)returnstr;returnreverse(str.substring(1))+str.charAt(0);}}
  5. How to Manipulate Strings in Java — contextual image 10 Convert the string to an array of characters and then swap the first and last, second and second to last, etc. characters. First convert the string to an array of characters by using the toCharArray() method on the string. Get the index of the last character in the array, which is equal to the length of the array minus one. Then iterate through the array, swapping the ithcharacter and the indexOfLastChar - ithcharacter at each iteration. Finally, convert the character array back to a string.
    publicclassStringManipulation{publicstaticvoidmain(String[]args){Stringstr="Hello!";char[]charArray=str.toCharArray();intindexOfLastChar=charArray.length-1;for(inti=0;i
    
  6. How to Manipulate Strings in Java — contextual image 11 Review your output. Here is the output that results from any one of these methods for string reversal.

Method 4

Trim White Space in a String

  1. How to Manipulate Strings in Java — contextual image 12 Understand what it means to trim white space in a string. Trimming a string in Java means to remove the leading and trailing white space in the string. For example, if you have the string "
     
    Hello, world!
     
    " and you want to have it say "Hello, world!" without the white space in the beginning and in the end, you can trim the string. The String class provides a method to trim() which returns a copy of the string with leading and trailing white space removed or the original string if it has no leading or trailing white space.
  2. How to Manipulate Strings in Java — contextual image 13 Use the trim() method of the String class on a String object to trim the white space. Note that the trim() method will throw an exception if the string is null. The trim() method will not change the contents of the original string because strings in Java are immutable, which means that a string's state cannot be modified after it is created. Rather, the trim() method will return a new string that has its whitespace trimmed off.
    StringtrimmedStr=str.trim();
  3. Try an example. Here is a sample program that trims the white space of a string:
    publicclassStringManipulation{publicstaticvoidmain(String[]args){Stringstr=" Hello! ";StringtrimmedStr=str.trim();System.out.println("Original String is ""+str+"".");System.out.println("Trimmed String is ""+trimmedStr+"".");}}

Method 5

Split a String

  1. How to Manipulate Strings in Java — contextual image 14 Understand what it means to split a string. Splitting a string in Java means to split a string by a certain delimiter into an array of substrings. For example, if I split the string "red,blue,green,yellow,pink" with a comma as the delimiter, I would get the array { "red", "blue", "green", "yellow", "pink" }. Here are three different ways to split a string.
  2. How to Manipulate Strings in Java — contextual image 15 UseStringTokenizerto tokenize the string. Importjava.util. StringTokenizer. Then create a new instance of aStringTokenizerwith the string to tokenize and the delimiter as parameters. If you do not enter the delimiter as a parameter, the delimiter will automatically default to white space. After you have theStringTokenizer, you can use thenextToken()method to get each token.
    importjava.util. Arrays;importjava.util. StringTokenizer;publicclassStringManipulation{publicstaticvoidmain(String[]args){Stringstr="red,green,blue,yellow,pink";StringTokenizertokenizer=newStringTokenizer(str,",");intnumberOfTokens=tokenizer.countTokens();String[]splitArr=newString[numberOfTokens];for(inti=0;i
    
    • Before Java 1.4, theStringTokenizerclass was used to split strings in Java. But now, the use ofStringTokenizeris discouraged and the use of thesplit()method in theStringclass or the use of thejava.util.regexpackage is encouraged.
  3. How to Manipulate Strings in Java — contextual image 16 Use theStringclass'ssplit()method. Thesplit()method will take in the delimiter as a param and return an array of sub-strings that are the same as the tokens from theStringTokenizer.
    importjava.util. Arrays;publicclassStringManipulation{publicstaticvoidmain(String[]args){Stringstr="red,green,blue,yellow,pink";String[]splitArr=str.split(",");System.out.println("nOriginal String: "+str);System.out.println("Split Array: "+Arrays.toString(splitArr)+"n");}}
  4. How to Manipulate Strings in Java — contextual image 17 Use regular expressions to split the string. Importjava.util.regex. Pattern. Use thecompile()method of thePatternclass to set the delimiter and then give thesplit()method the string that you want to split. ThePatternwill return an array of substrings.
    importjava.util. Arrays;importjava.util.regex. Pattern;publicclassStringManipulation{publicstaticvoidmain(String[]args){Stringstr="red,green,blue,yellow,pink";String[]splitArr=Pattern.compile(",").split(str);System.out.println("nOriginal String: "+str);System.out.println("Split Array: "+Arrays.toString(splitArr)+"n");}}
  5. How to Manipulate Strings in Java — contextual image 18 Review your output. Here is the output that results from any one of these methods for splitting strings.

FAQ

What is How to Manipulate Strings in Java about?

It provides a structured overview of string, explains the main context, and highlights practical takeaways for readers.

Why does this topic matter?

Understanding the main concepts helps readers evaluate the issue, avoid common mistakes, and make better-informed decisions.

How should readers use this information?

Use the guidance as a practical starting point, confirm details that may have changed, and follow current product, safety, or security recommendations.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.