Showing posts with label Java String. Show all posts
Showing posts with label Java String. Show all posts

Saturday, August 24, 2024

Convert String to Byte Array Java Program

In this post we'll see a Java program to convert a String to byte array and byte array to String in Java.


Converting String to byte[] in Java

String class has getBytes() method which can be used to convert String to byte array in Java.

getBytes()- Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

There are two other variants of getBytes() method in order to provide an encoding for String.

  • getBytes(Charset charset)
  • getBytes(String charsetName)
import java.util.Arrays;

public class StringToByte {
 public static void main(String[] args) {
  String str = "Example String";
  byte[] b = str.getBytes();
  System.out.println("Array " + b);
  System.out.println("Array as String" + Arrays.toString(b));
 }
}

Output

Array [B@2a139a55
Array as String[69, 120, 97, 109, 112, 108, 101, 32, 83, 116, 114, 105, 110, 103]

As you can see here printing the byte array gives the memory address so used Arrays.toString in order to print the array values.

Conversion of string to byte array with encoding

Suppose you want to use "UTF-8" encoding then it can be done in 3 ways.

String str = "Example String";
byte[] b;
try {
 b = str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}
b = str.getBytes(Charset.forName("UTF-8"));
b = str.getBytes(StandardCharsets.UTF_8);

Using str.getBytes("UTF-8") method to convert String to byte array will require to enclose it in a try-catch block as UnsupportedEncodingException is thrown. To avoid that you can use str.getBytes(Charset.forName("UTF-8")) method. Java 7 onward you can also use str.getBytes(StandardCharsets.UTF_8);

Converting byte array to String in Java

String class has a constructor which takes byte array as an argument. Using that you can get the String from a byte array.

String(byte[] bytes)- Constructs a new String by decoding the specified array of bytes using the platform's default charset.

If you want to provide a specific encoding then you can use the following constructor-

String(byte[] bytes, Charset charset)- Constructs a new String by decoding the specified array of bytes using the specified charset.

public class StringToByte {
 public static void main(String[] args) {
  String str = "Example String";
  // converting to byte array
  byte[] b = str.getBytes();
  
  // Getting the string from a byte array
  String s = new String (b);
  System.out.println("String - " + s);
 }
}

Output

String - Example String

That's all for this topic Convert String to Byte Array Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Convert String to int in Java
  2. Java Program to Find The Longest Palindrome in a Given String
  3. Find All Permutations of a Given String Java Program
  4. Check Given Strings Anagram or Not Java Program
  5. Add Double Quotes to a String Java Program

You may also like-

  1. Find Duplicate Elements in an Array Java Program
  2. How to Convert Date And Time Between Different Time-Zones in Java
  3. Association, Aggregation and Composition in Java
  4. Difference Between Abstract Class And Interface in Java
  5. Multi-Catch Statement in Java Exception Handling
  6. How ArrayList Works Internally in Java
  7. Difference Between ReentrantLock and Synchronized in Java
  8. Java ThreadLocal Class With Examples

Tuesday, August 20, 2024

Count Number of Words in a String Java Program

Write a Java program to count the number of words in a String is asked quite frequently in Java interviews. To test the logical thinking of the candidates it is often asked to write this program without using any of the String functions.

Java Program to count number of words in a String

Here three ways are given to count number of words in a String in Java. All of these ways take care of any number of spaces in between the words even the spaces at the beginning or at the end.

  • First method countWords() uses charAt() method to get each character of the String. Logic used in the method works fine even if there are extra spaces in the passed String and the correct count of the words in the String is given.
  • Second method countWordsUsingSplit() uses the String split() method to count number of words.
  • Third method countWordsUsingStream() uses the Java Stream API to count number of words.

Let's see the Java code first and later explanation of the code logic.

public class StringWordCount {
  public static void main(String[] args) {
    System.out.println("Word Count- " + countWords("   Life    is    beautiful  "));
        
    System.out.println("Count using split logic " + countWordsUsingSplit("         Life     is       beautiful  "));
    
    System.out.println("Count using Java Stream " + countWordsUsingStream("   Life    is    beautiful  "));
  }
    
  private static int countWords(String str){        
    
    if(str.isBlank()) {
      return 0;
    }
    int c = 0;
    for(int i = 0; i < str.length(); i++){
     
      /**
       * logic here is if the current character is not a space and the character read before the 
       * current char was a space that means one whole word is read so increment the count.  
       * Or part is to ensure correct working even if there are spaces in the beginning
      */
      if((i > 0 && (str.charAt(i) != ' ') && (str.charAt(i-1) == ' ' ))
          || ((i == 0) && (str.charAt(0) != ' ')))
        c++;
    }
    return c;
  }
    
  /**
  * This method counts using String split method 
  * @param str
  * @return
  */
  private static int countWordsUsingSplit(String str){
    // here split method is used with regex pattern of any number of spaces
    // so it will retrun a string array with the words
    String[] test = str.trim().split("\\s+");
    return test.length;
  }
  
  /**
  * This method counts using Java Stream API
  * @param str
  * @return
  */
  private static long countWordsUsingStream(String str){
	  // here split method is used with regex pattern of any number of spaces
	  // trim() is used to remove spaces in the beginning and at the end
	  long count = Stream.of(str.trim().split("\\s+")).count();
	  
	  return count;
  }
}

Output

Word Count- 3
Count using split logic 3
Count using Java Stream 3

Count number of words in a String program logic

In the first method countWords() the idea is; if the current character is not a space and the character read before the current char was a space that means one whole word is read so increment the count. This is the condition doing that

(str.charAt(i) != ' ') && (str.charAt(i-1) == ' ' )

For example if program is reading the string “life is” when the index comes to 'i' (in "is") the character before 'i' would be either space or tab, that means one word is already read (which in this case would be "life") thus count will be incremented.

We may miss to count the first word, this condition (i == 0) && (str.charAt(0) != ' ')) takes care of that.

Second way of counting number of words in a String uses the split method of string. Split() method takes a regex pattern as a parameter here we are passing “//s+” which will mean any number of spaces. So the condition becomes; split the word on any number of spaces in between. It returns a String array whose length will be the count of words in a string.

In the third method, String array that is returned by the split method is used to create a Stream using Stream.of() method. Then count() method of Java Stream API is used to return the count of elements in this stream.

That's all for this topic Count Number of Words in a String Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Check if Given String or Number is a Palindrome Java Program
  2. Count Number of Times Each Character Appears in a String Java Program
  3. Find All Permutations of a Given String Java Program
  4. Check Given Strings Anagram or Not Java Program
  5. Java Program to Check Prime Number

You may also like-

  1. Bubble Sort Program in Java
  2. Matrix Subtraction Java Program
  3. Package in Java
  4. Encapsulation in Java
  5. Marker interface in Java
  6. Creating Custom Exception Class in Java
  7. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  8. Race Condition in Java Multi-Threading

Wednesday, January 3, 2024

Count Number of Times Each Character Appears in a String Java Program

In this post we'll see a Java program to count the total number of times each character occurs in the given String. Here three ways are given for counting the occurrences of each character in the given String;

  1. Program using HashMap
  2. Program using char array
  3. Program using Java Stream

Counting the frequency of characters in String using HashMap

Here it is done using HashMap provided by Java Collection framework. Logic is to read one character at a time from the string and put it in HashMap; character as key, count as value (Initial value will be 1).

With every character that is read from the String check in the HashMap, if it already exists as a key or not. If it exists then increment the count otherwise add the key in HashMap with value 1.

public class CountCharacters {    
  // method used to count characters in a String
  public void countChars(String message){
    Map<Character, Integer> numCharMap = new HashMap<Character, Integer>();
    for(int i = 0; i < message.length(); i++){
      // Take one character 
      char c = message.charAt(i);
      // We don't need to count spaces
      if(c == ' ')
        continue;
      // If that character is already there in the map
      // then increase the value by 1
      if(numCharMap.containsKey(c)){
        numCharMap.put(c, numCharMap.get(c) + 1);
      }else{
        // otherwise put that character in the map
        // with the value as 1
        numCharMap.put(c, 1);
      }
    }
    // Displaying the map values
    Set<Map.Entry<Character, Integer>> numSet = numCharMap.entrySet();
    for(Map.Entry<Character, Integer> m : numSet){
      System.out.println("Char- " + m.getKey() + " Count " + m.getValue());
    }
  }
    
  public static void main(String[] args) {
    CountCharacters cc = new CountCharacters();
    cc.countChars("I am an Indian");
  }
}

Output

Char- a Count 3
Char- d Count 1
Char- I Count 2
Char- i Count 1
Char- m Count 1
Char- n Count 3

Values are displayed by looping the HashMap, entrySet is used to iterate the map, which gives the key value pair as Entry object.

Counting the frequency of characters in String using char array

In the Java program to count total number of occurrences of each character in a String using char array, given String is converted to char array then you need to iterate the array starting from first index and check if that character is found again in the char array. If yes then increase the count. One thing you need to do is to remove all the occurrences of that character from the string after counting is done for that specific character.

public class CountCharacters {
  public static void main(String[] args) {
    CountCharacters cc = new CountCharacters();
    cc.countChars("I am an Indian");
  }
    
  public void countChars(String str){
    char[] strArr;
    while(str.length() != 0){
      strArr = str.toCharArray();
      char ch = strArr[0];
      int count = 1;
      for(int i = 1; i < strArr.length; i++){
        if(ch == strArr[i]){
          count++;
        }
      }
      // We don't need to count spaces
      if(((ch != ' ') && (ch != '\t'))){
        System.out.println(ch + " - " + count);
      }
      // replace all occurrence of the character 
      // which is already iterated and counted
      str = str.replace(""+ch, "");
    }    
  }
}
Output
I - 2
a - 3
m - 1
n - 3
d - 1
i - 1

Counting the frequency of characters in String using Java Stream

In this way, String array that is returned by the split method is used to create a Stream using Stream.of() method. Then Collectors.groupingBy() of Java Stream API is used to group characters of the String and Collectors.counting() is also passed to perform a reduction operation. Collectors.groupingBy() returns a Map (key is char, value is count in our case) which is again iterated by getting the Set view of the Map using entrySet() method. filter() method is used to remove space character.

import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CountCharacters {

  public static void main(String[] args) {
    String str = "I am an Indian";
    Stream.of(str.trim().split(""))
          .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
          .entrySet()
          .stream()
          .filter(e -> !e.getKey().equals(" "))
          .forEach(e -> System.out.println(e.getKey() + " - " + e.getValue()));
  }
}

Output

a - 3
d - 1
i - 1
I - 2
m - 1
n - 3

That's all for this topic Count Number of Times Each Character Appears in a String Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Count Number of Words in a String Java Program
  2. Java Program to Find The Longest Palindrome in a Given String
  3. Add Double Quotes to a String Java Program
  4. How to Reverse a String in Java
  5. Convert String to Byte Array Java Program

You may also like-

  1. Reading File in Java Using Files.lines And Files.newBufferedReader
  2. Find Maximum And Minimum Numbers in a Given Matrix Java Program
  3. Access Modifiers in Java - Public, Private, Protected and Default
  4. Marker Interface in Java
  5. How LinkedList Class Works Internally in Java
  6. Functional Interfaces in Java
  7. ConcurrentSkipListMap in Java With Examples
  8. Dependency Injection in Spring Framework

Monday, March 13, 2023

String in Java Tutorial

This post talks about one of the very important class; String in Java. In Java String class represents character strings which means; Strings in Java are objects and all created strings are instances of the String class in Java. In String class strings are internally stored as character array.


How to create String in Java

You can create a String object using-

  • new operator
  • Using String literal

1. Using new operator

Since strings are objects so strings can of course be created using new operator. String class has more than 10 constructors to create Strings in Java which ranges from taking nothing as parameter to taking char array, StringBuffer, StringBuilder, another String as argument. For Example

String str = new String(“abc”);

2. Using String literal

Preferred way to create Strings is to assign String literal directly to a String reference as you will do for any primitive type. For every String literal Java automatically constructs a String object. For Example

String str = “abc”;

String pool in Java

But having String literals brings another dimension to storing String in Java. If String objects are created using new operator, objects will go in the heap with their own space. String literals are treated differently they are stored in a String pool and that is a common pool; which means if there are two strings literals having the same content then those string will share the space in the pool.

When String object is created by assigning a string literal, pool will be checked to verify if there is any existing object with the same content if there is then that existing reference is used, no new object is created in that case. If no object is found with the same content then this new literal will be added in the pool.

For example, if two strings str1 and str2 are created as follows-

String str1 = "abc";
String str2 = "abc";

Then the string object reference is shared between these two literals.

String pool in Java
String pool in Java

Let’s see it with an example

In this program two string literals will be created with the same content and then these two string objects are checked for reference equality. Since we are not comparing the content but the references of two objects so “==” operator will be used.

public class StringDemo {
 public static void main(String[] args) {
  String str1 = "abc";
  String str2 = "abc";
  if(str1 == str2){
   System.out.println("str1 and str2 are same");
  }else{
   System.out.println("str1 and str2 are not same");
  }
 }
}

Output

str1 and str2 are same

Refer String Pool in Java to know more about String pool.

Java String intern() method

Using Java String's intern() method you can still get string object from the pool (if it exists) even if new operator is used to create a string.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String  object is added to the pool and a reference to this String object is returned.

In the previous Java program if str4 is changed to have interned string then the code will look like–

public class StringDemo {

 public static void main(String[] args) {
  String str1 = "abc";
  String str2 = "abc";
  if(str1 == str2){
   System.out.println("str1 and str2 are same");
  }else{
   System.out.println("str1 and str2 are not same");
  }
  String str3 = new String("abc");
  String str4 = new String("abc").intern();
  if(str3 == str4){
   System.out.println("str3 and str4 are same");
  }else{
   System.out.println("str3 and str4 are not same");
  }
  
  if(str1 == str4){
   System.out.println("str1 and str4 are same");
  }else{
   System.out.println("str1 and str4 are not same");
  }
 }
}

Output

str1 and str2 are same
str3 and str4 are not same
str1 and str4 are same

It can be seen that str1 and str4 are having the same reference now.

Java String is immutable

Once you create a String object the content of that string cannot be modified. As we have already seen Java maintains a string pool where references are shared thus changing content of any of the String will also affect the other strings sharing the same references that’s one reason why String is immutable in Java.

Here being immutable means whenever you perform any operation on string which alters its content a new string object is created which contains the modified string. Original string is left as it is. If there are no references to the original string it is garbage collected.

Using any of the methods that modify the original String like toLowerCase, toUpperCase, concatenating using concatenate() method or ‘+’ operator will result in creation of a new string object.

Let's try to see the immutability of the String using as example.

String str = "hello";
str.concat("world");
System.out.println("Value of str- " + str);

Output

Value of str- hello

You can see that the original String is not changed, when the concatenation is done a new String object is created.

Refer Why is String Immutable in Java to know more about immutable strings and why are strings immutable in Java.

String class in Java is final

As already mentioned above whenever you perform any operation on string which alters its content a new string object is created containing the modified string. Which means all the methods of the String class in Java that modify the content in any way return a new String object with the modified content.

Now, what if you can override the method of the String class and provide an implementation to modify the content of the String and return the original String itself? What will happen to the String pool then where strings having the same data share the same reference?

Another scenario- You extend the String class and override hashCode() and equals() method in such a way that two dissimilar strings return the same hashCode and at the same time equals() return true. Then you can have different strings sharing the same reference in the String pool.

To avoid these kind of scenarios String class is declared as final in Java and it can’t be overridden.

String and thread-safety

Since String objects are immutable thus thread-safe.

Refer Is String Thread Safe in Java to know more about String and thread safety.

Overloaded operators in String

Apart from using concatenate method to concatenate two strings ‘+’ operator can be used to do the same. Actually + and += are two operators which are overloaded for String in Java.

So, if you have two strings
String str1 = "Hi";
String str2 = "Hello";

You can use ‘+’ operator to concatenate them

str1 = str1 + str2;
System.out.println("str1 " + str1);

Or, to make it more concise

str1 += str2;
System.out.println("str1 " + str1);

Comparing Strings using .equals method

In the section about string pool we used == to compare references but what if you want to compare content of two strings even if their references are different. You will have to use .equals method in that case.

public class StringDemo {

 public static void main(String[] args) {
  String str1 = "abc";
  String str4 = new String("abc");
  // comparing content
  if(str1.equals(str4)){
   System.out.println("str1 and str4 are same");
  }else{
   System.out.println("str1 and str4 are not same");
  }
  // comparing references
  if(str1 == str4){
   System.out.println("str1 and str4 are same");
  }else{
   System.out.println("str1 and str4 are not same");
  }
 }
}

Output

str1 and str4 are same
str1 and str4 are not same

Though str1 and str4 have same content but they will have different references as str4 is created using new operator. That is why comparing using "==" prints "str1 and str4 are not same" as references are different but comparing using .equals prints "str1 and str4 are same", as content is compared in that case.

Java String class methods

String class has lots of methods for various operations. These String class methods can be grouped as per functionality.

  1. Methods for String comparison- In Java String class there are methods like equals, compareTo, regionMatches for comparing strings. Refer String Comparison in Java to see examples of comparing strings in Java.
  2. Methods for searching in String- If you want to find characters or substrings within a String you can use methods like indexOf() and lastIndexOf(). Refer Searching Within a String Using indexOf(), lastIndexOf() And contains() Methods to see examples of searching with in a String.
  3. Getting specific character from String- If you are trying to get specific character from a String then you can use charAt() method. Refer Java String charAt() Method With Examples to see examples of getting characters from a String.
  4. Getting a substring- If you are trying to get substring with in a String then you can use substring() method. Refer Getting Substring - Java String substring() Method to see examples of getting substring from a String.
  5. Splitting a String- If you want to split a string into one or more substrings then you can use split() method. Refer Splitting a String Using split() Method in Java to see examples of splitting a String in Java.
  6. Merging Strings- For merging multiple strings in Java you can use join() method. Refer String join() Method in Java to see examples of joining Strings in Java.
  7. Checking String null or empty- For checking if the String is null or empty you can use isEempty(), length() or isBlank() method. Refer Check String Null or Empty in Java to see examples.
  8. intern() Method- For interning strings in Java you can use intern() method. Refer intern() Method in Java String to know more about interning Strings.
  9. matches() Method- Using matches() method you can check whether or not this string matches the given regular expression. Refer matches() method in Java String to see examples of matches() method.

Points to note about Java String

  1. Internally in String class, Strings are stored as character array.
  2. Strings in Java are objects and all strings are instances of the String class.
  3. Strings can be created by assigning String literal directly to a String reference like String str = “abc”; which may look like assigning to a primitive data type but don't forget Strings are objects.
  4. String literals in Java are treated differently, they are stored in a String pool and that is a common pool.
  5. If there are two strings literals having the same content then those string will share the space in the pool.
  6. String is immutable in Java once you create a String object the content of that string cannot be modified.
  7. Since String is immutable in Java whenever you perform any operation on string which alters its content a new string object is created which contains the modified string. Original string is left as it is.
  8. Since String is immutable it is also thread safe.
  9. String class is declared as final and it can’t be overridden.
  10. "+" operator is overloaded for String and it is used for concatenating strings.
  11. Using intern() method you can still get string object from the pool (if it exists) even if new operator is used to create a string.
  12. For comparing the content of two strings .equals() method is used. If you want to ignore case then use .equalsIgnoreCase().
  13. From Java 7 string can also be used in switch case statement.
  14. join() method is added in String class in Java 8 which makes it very easy to join multiple strings.

That's all for this topic String in Java Tutorial. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. StringBuffer Class in Java With Examples
  2. Converting Char to String And String to Char in Java
  3. Converting String to int in Java
  4. How to Create Immutable Class in Java
  5. Java String Interview Questions And Answers

You may also like-

  1. Marker interface in Java
  2. Array in Java With Examples
  3. How and why to synchronize ArrayList in Java
  4. LinkedHashMap in Java With Examples
  5. Java Exception Handling And Method Overriding
  6. finally Block in Java Exception Handling
  7. Java BlockingQueue With Examples
  8. Java ReentrantLock With Examples

Saturday, March 11, 2023

Java Program to Find The Longest Palindrome in a Given String

This post is about writing a Java program to find the longest palindrome in a given String.

Logic for finding the longest palindrome in a given string

The solution given here works on the logic that in a palindrome, starting from the center, if two cursors are moved left and right respectively one character at a time, those values should be equal. This holds true if the length of the string is odd.

For example, if string is 121 then centre is 2. Character at the left and character at the right, if checked for equality should be equal. You can check for 24642, aba, malayalam.

If the length of the string is even then you have to take 2 characters as center, and then check the character at the left and character at the right for equality. Of course two characters considered as center should be equal too.

For example, if string is 1221, then centre is 22 from there you move one character to left and one character to right. You can check for toppot, abba.

Punctuation, capitalization, and spaces are usually ignored, in the given code it is not done though.

Note that this Java program is to find the longest palindrome in the given string. For example- bananas, in this string "ana", "ana" and "anana" three palindromes are present but the longest is "anana".

If you are looking for Java program to find whether given string is palindrome or not refer this link- Check if Given String or Number is a Palindrome Java Program

Java code for finding the longest palindromic String

public class PalDemo {

  public static void main(String[] args) {
    PalDemo pd = new PalDemo();
    
    String pal = pd.findLongestPalindrome("bananas");
    System.out.println("" + pal);
    
    pal = pd.findLongestPalindrome("abaradar121");
    System.out.println("" + pal);
  }
    
  public String findLongestPalindrome(String s) {
    // Validations
    if (s.isEmpty()) {
      return "Please enter a String";
    }

    if (s.length() == 1) {
      return s;
    }
    // Validations end
    // Start with one char (starting) as a longest palindrome
    String longest = s.substring(0, 1);
    for (int i = 0; i < s.length(); i = i+1) {        
      // get longest palindrome for odd length (center is i)
      String tmp = checkForEquality(s, i, i);
      if (tmp.length() > longest.length()) {
        longest = tmp;
      }

      // get longest palindrome for even length (center is i, i+1)
      tmp = checkForEquality(s, i, i + 1);
      if (tmp.length() > longest.length()) {
        longest = tmp;
      }
    }
    return longest;
  }
    
    
  /**
  * In this method equality is checked starting from
  * the center moving one character left and one character
  * right from the center. If both chars are equal then the
  * next set of chars are checked.  
  *     
  */
  public String checkForEquality(String s, int begin, int end) {
    while (begin >= 0 && end <= s.length() - 1 && s.charAt(begin) == s.charAt(end)) {
      begin--;
      end++;
    }
    return s.substring(begin + 1, end);    
  }
}
 

Output

anana
radar

Let's try to have a dry run with 121 as the entered string and trace the steps-

  1. After checking if String is empty or having just one character, first character of the string is stored as the longest.
  2. From the for loop, in the first call to method checkForEquality() entered String is passed as the first param. Other two params begin and end will be 0 and 0.
  3. In the while loop in the method checkForEquality(), begin >= 0 && end <= s.length() - 1 condition will pass as begin = 0 and end is less than 2 (length of string – 1). s.charAt(begin) == s.charAt(end) condition will also pass as both begin and end are pointing to same char. So begin has a value -1 and end has a value 1 now. With that while loop will fail.
    Only first char of the string will be returned as s.substring(begin + 1, end) will be translated as s.substring(0, 1) for begin = -1 and end = 1.
  4. Again checkForEquality() method will be called with 0 and 1 (this is to check for even case). With these values while loop will fail for the condition s.charAt(begin) == s.charAt(end) as both values will be different.
  5. Now i is 1, in that case s.charAt(begin) == s.charAt(end) condition will pass as value will be 2 for both. So begin-- gives begin = 0 and end++ gives end = 2. Again s.charAt(begin) == s.charAt(end) will pass as value will be 1 for both. So begin-- gives begin = -1 and end++ gives end = 3. With these values it will come out of while loop and returns s.substring(0, 3) which is 121.
  6. Since this returned value's length is greater than the current longest string so returned value becomes the longest.

Time complexity of the solution

Program given here to find the longest palindrome in a string in Java has a time complexity of O(N2), there is also a linear solution known as Manacher's algorithm

That's all for this topic Java Program to Find The Longest Palindrome in a Given String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Check if Given String or Number is a Palindrome Java Program
  2. Count Number of Words in a String Java Program
  3. Add Double Quotes to a String Java Program
  4. Convert String to int in Java
  5. Print Odd-Even Numbers Using Threads And Semaphore - Java Program

You may also like-

  1. How to Format Date in Java Using SimpleDateFormat
  2. How to Read File From The Last Line in Java
  3. Abstraction in Java
  4. Race Condition in Java Multi-Threading
  5. Callable and Future in Java concurrency
  6. Java ReentrantLock With Examples
  7. Dependency Injection in Spring Framework
  8. Spring Component Scan to Automatically Discover Beans

Saturday, February 25, 2023

Reverse Each Word in a String Java Program

Write a Java program to reverse a String is asked in many interviews, there is another version similar to it where developers are asked to write a Java program to reverse each word of a given String.

If you notice the Java program to reverse each word of a String is a combination of two programs- How to split a string in Java and how to reverse a String.

Java program to reverse each word in a String

First the passed string is split using split() method of the String class that returns an array having the words. Then iterate through the array and reverse each word, keep appending each reversed word to another string.

For reversing a String there are both recursive and iterative logic, in the code both are shown.

public class ReverseWord {

  public static void main(String[] args) {
    // /Using recursive logic
    String str = "Reverse each word of this string";
    StringBuilder sb = new StringBuilder();
    // For splitting on spaces
    String[] strArr = str.split("\\s+");
    // reversing and appending to StringBuffer
    for(String s : strArr) {
      sb.append(reverseString(s)).append(" ");
    }
    System.out.println("Original String- " + str);
    System.out.println("Reversed String- " + sb.toString());
    
    // Using iterative logic
    str = "This is reverse program";
    sb = new StringBuilder();
    strArr = str.split("\\s+");
    for(String s : strArr) {
      sb.append(reverseStringItr(s)).append(" ");
    }
    System.out.println("Original String- " + str);
    System.out.println("Reversed String- " + sb.toString());
  }
    
  // Recursive logic to reverse a String
  private static String reverseString(String str) {
    // validation & base case
    if((str == null) || (str.length() <= 1)){
      return str;
    }
    // recursive call
    return reverseString(str.substring(1)) + str.charAt(0);  
  }
    
  // Using iteration - Non Recursive
  private static String reverseStringItr(String str){
    // validation
    if((str == null) || (str.length() <= 1)){
      return str;
    }
    
    StringBuilder sb = new StringBuilder();
    for(int i = str.length() - 1; i >= 0; i--){
      sb.append(str.charAt(i));
    }
    return sb.toString();
  }
}

Output

Original String- Reverse each word of this string
Reversed String- esreveR hcae drow fo siht gnirts 
Original String- This is reverse program
Reversed String- sihT si esrever margorp 

That's all for this topic Reverse Each Word in a String Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Java Program to Find The Longest Palindrome in a Given String
  2. Converting Char to String And String to Char in Java
  3. Find Duplicate Characters in a String With Repetition Count Java Program
  4. Java Program to Reverse a Number
  5. Find The Maximum Element in Each Row of The Matrix - Java Program

You may also like-

  1. Java Lambda Expression Callable Example
  2. How to Read Properties File in Java
  3. How to Display Time in AM-PM Format in Java
  4. Running Dos/Windows Commands From Java Program
  5. How ArrayList Works Internally in Java
  6. Synchronization in Java - Synchronized Method And Block
  7. Access Modifiers in Java - Public, Private, Protected and Default
  8. How MapReduce Works in Hadoop

Friday, January 27, 2023

Find All Permutations of a Given String Java Program

Java program to find all the permutations of a given String can be written using both recursive and non-recursive methods. In this post we'll see both kind of solutions.

Recursive is easy to code but a little difficult to visualize where as non-recursive is a little difficult to code but once you know the logic it is easy to visualize what code is doing.

Java program for finding permutations of a String - Non Recursive

Logic for the non recursive solution is as follows-

  1. First thing to do is to sort the given string in ascending order that is the first permutation so print it.
  2. Now we have to generate all the other permutations until the string is sorted in descending order. That becomes the last permutation to be printed and signals the end of the program.
  3. For every permutation previous permutation becomes the starting point and from there the steps are-
    1. Find the rightmost char in the String which is smaller than the next character.
      For example, if String is BCDA then you need to scan through the chars, B is smaller than the next char 'C' but remember you have to find the rightmost character and 'C' is also smaller than the next character 'D' that means 'C' is the char you are looking for. Let's call this char as 'CHAR1'.
    2. Second step is to find the ceiling of the 'CHAR1' starting from the index of the 'CHAR1'. Ceiling here means starting from the index of the 'CHAR1' you have to find the smallest character which is greater than the 'CHAR1'. Let's call this char as 'CHAR2'.
      As exp. If string is BCDAE and C is 'CHAR1' then you are looking for the smallest character with in the String "DAE" which is greater than C. So it should be D so D is 'CHAR2' in this case.
    3. Swap these 2 characters found using Step1 and Step2 i.e. CHAR1 and CHAR2.
    4. In the resultant string take the substring after the index of 'CHAR1' till end and sort it.

Let's see all the steps with an example- If passed String is 'ABCDEF' and at some point the permutation is 'CFADEB' then in order to find the next permutation.

In Step1 it will go through the following combinations to find the 'CHAR1' CFADEB - C-F, F-A, A-D, D-E, E-B So CHAR1 is D.

In Step2 we have to find the smallest char which is greater than D with in the substring EB. So 'CHAR2' is E.

In Step3 - Swapping these will give the String CFAEDB.

In Step 4 - if we use 0 based index then the original index of 'CHAR1' was 3. In String CFAEDB if we take the sub string after index 3 then DB is the resultant string which has to be sorted.

So the end string is CFAEBD and that is the next permutation.

Note that this logic take cares of the duplicate chars too. If you enter "DDDD" as string it will give you only one String "DDDD" as output.

import java.util.Arrays;

public class PermNR {

  public static void main(String[] args) {     
    permute("ABCDEF");
  }
    
  public static void permute(String str){
    char[] temp = str.toCharArray();
    // Step 1. Sort the string
    Arrays.sort(temp);
    System.out.println("String " + String.valueOf(temp));
    int index = 0;
    int lowest = 0;
    while(true){
      // Step 2. Rightmost char smallest than its neighbour
      for(int i = 0; i < temp.length - 1; i++){
        if(temp[i] < temp[i+1]){
          lowest = i;               
        }
      }
      // index of CHAR1
      index = lowest;
      // Step3. Find the ceiling of the 
      int j = findCeiling(temp, index);
      // Breaking condition at this juncture
      // all permutations are printed
      if(j == index) break;
        
      swap(temp, index, j);
      String a = String.valueOf(temp);
      // Step4. Sort the substring
      char[] b = a.substring(index + 1).toCharArray();
      Arrays.sort(b);
      a = a.substring(0, index + 1) + String.valueOf(b);
      temp = a.toCharArray();
      System.out.println( "String " + String.valueOf(temp));
      //}
    }                        
  }
    
  /**
  * 
  */
  public static int findCeiling(char[] temp, int index){
    int k = index;
    char test = temp[index];
    while (k < temp.length - 1){
      if(temp[index] < temp[k + 1]){
        index = k + 1;
        break;
      }
      k++;
    }
    k = index;
    while (k < temp.length - 1){
      if((temp[index] > temp[k + 1]) && (temp[k + 1] > test)){
        index = k + 1;
      }
      k++;
    }
    return index;
  }
    
  /**
  * Method used for swapping the char
  */
  private static void swap(char[] str, int i, int j){
    char temp = str[i];
    str[i] = str[j];
    str[j] = temp;
  }
}

Permutations of a String - Recursive Java code

Here the method will call itself, keeping portion of a string as constant. A base condition is also needed which is when string length is 0.

public class PermDemo {
  public static void main(String[] args) {
    permutation("abcde");
  }
  public static void permutation(String str) {
    permutation("", str);
  }
  // recursive method
  private static void permutation(String prefix, String str) {
    int n = str.length();
    if (n == 0){
      System.out.println(prefix);
    }
    else {
      for (int i  = 0;  i < n;  i++){
        //System.out.println("prefix " + prefix + " i " + i);
        permutation(prefix + str.charAt(i), str.substring(0, i) 
          + str.substring(i+1, n));
      }
    }
  }
}

Source for recursive code is : http://introcs.cs.princeton.edu/java/23recursion/Permutations.java.html

Explanation

After first base point when n becomes 0 we'll have these 3 calls. Note that for all these calls i will be 0 as permutation method is called again.

permutation("a", "bc");
permutation("ab", "c");
permutation("abc", "");

Since method calls follow stack data structure so LIFO (Last In First Out) will be followed. Let's lay out our method calls in that way.

permutation("abc", "");
permutation("ab", "c");
permutation("a", "bc");

Now first call will print the String "abc", second call permutation("ab", "c") will go in the for loop with i = 1 and n = 1 so it will come out and won’t print anything as for loop has condition (i < n). Third call permutation(“a”, “bc”); will go in the for loop with i =1 and n=2. Which will lead to following calls again following that same pattern as explained above it will print acb.

Permutation("a", "bc");
Permutation("ac", "b");
Permutation("acb", "");

That's all for this topic Find All Permutations of a Given String Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Check if Given String or Number is a Palindrome Java Program
  2. Java Program to Find First Non-Repeated Character in a Given String
  3. Add Double Quotes to a String Java Program
  4. Count Number of Words in a String Java Program
  5. Print Odd-Even Numbers Using Threads And wait-notify Java Program

You may also like-

  1. Fibonacci Series Program in Java
  2. Find Largest and Second Largest Number in Given Array Java Program
  3. How to Convert Date And Time Between Different Time-Zones in Java
  4. Polymorphism in Java
  5. How ArrayList Works Internally in Java
  6. Race condition in Java multi-threading
  7. Callable and Future in Java With Examples
  8. Autodiscovery of Bean Using component-scan in Spring

Wednesday, January 4, 2023

Add Double Quotes to a String Java Program

You may come across a scenario where you would want to add double quotes to a String, but Java uses double quotes while initializing a String so it won't recognize that double quotes have to be added to the String.

You should have guessed what needed to be done in case you want to display double quotes with in a String in Java. Yes you need escape character "\" to escape quotes. So let's see an example.

Displaying double quotes Java example

public class SetQuote {
  public static void main(String[] args) {
    // escaping the double quotes as quotes are
    // needed with in the String
    String value = "\"Ram\"";
    System.out.println("Value - " + value );
  }
}

Output

Value - "Ram"

Let's take another example. You have got a String and you want to enclose part of it in double quotes.

For example let's say you are reading an XML in which first line has no double quotes.

Which means you got it as-

<?xml version=1.0 encoding=UTF-8?>

but it should be

<?xml version="1.0" encoding="UTF-8"?>

That can be done by using replace method of the String and escaping double quotes.

public class SetQuote {
  public static void main(String[] args) {
    SetQuote setQuote = new SetQuote();
    setQuote.replaceQuote();
  }

  public void replaceQuote(){
    String xmlString = "<?xml version=1.0 encoding=UTF-8?>";
    xmlString = xmlString.replace("1.0", "\"1.0\"").replace("UTF-8", "\"UTF-8\"");
    System.out.println("xmlString - " + xmlString);
  }
}

Output

xmlString - <?xml version="1.0" encoding="UTF-8"?>

That's all for this topic Add Double Quotes to a String Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Count Number of Words in a String Java Program
  2. If Given String Sub-Sequence of Another String in Java
  3. Convert String to Byte Array Java Program
  4. How to Convert Date And Time Between Different Time-Zones in Java
  5. How to Sort ArrayList of Custom Objects in Java

You may also like-

  1. How to Read File From The Last Line in Java
  2. Marker Interface in Java
  3. How LinkedList Class Works Internally in Java
  4. Functional Interfaces in Java
  5. Difference Between Checked And Unchecked Exceptions in Java
  6. Synchronization in Java - Synchronized Method And Block
  7. Race Condition in Java Multi-Threading
  8. Java Concurrency Interview Questions And Answers

Thursday, September 8, 2022

matches() Method in Java String

String class in Java is one of the most important and one of the most used class too. To make the usage of String class easier for developers it has many utility methods that can be used out of the shelf. One such method is the matches() method in Java String class that is used to match a string against the given regular expression.

Java String matches() method

  • boolean matches(String regex)- Tells whether or not this string matches the given regular expression.

Method returns true if this string matches the given regular expression otherwise false. If the passed regular expression's syntax is invalid then the method throws PatternSyntaxException.

matches() method examples

1. If you have a list of cities and you want to print only those cities that start with “L” then you can pass a regex in matches() method to match that pattern.

import java.util.Arrays;
import java.util.List;

public class StringMatching {
  public static void main(String[] args) {
    List<String> strList = Arrays.asList("Chicago", "London", "Lisbon", "Mumbai");
    for(String str : strList) {
      if(str.matches("L.*"))
        System.out.println(str);            
    }
  }
}

Ouput

London
Lisbon

2. Let's say there is a String array with some strings and you want to match and print only those strings which doesn't contain any digit or special character. Then using matches method and providing a regular expression [a-z]+ which will match one or more chars it can be done as follows.

public class StringComparison {
  public static void main(String[] args) {
    String[] words = {"a123","*67t","test","54&ty"};
    for(String str : words){
      if(str.matches("[a-z]+")){
        System.out.println("matched string - " + str);
      }
    }
  }
}

Ouput

matched string - test

3. In the same scenario as example 2 if you want to get only those string which are alphanumeric (i.e. no special characters) then using String matches() method it can be done as

public class StringMatching {
  public static void main(String[] args) {
    String[] words = {"a123","*67t","test","54&ty"};
    for(String str : words){
      if(str.matches("\\w+")){
        System.out.println("matched string - " + str);
      }
    }
  }
}

Ouput

matched string - a123
matched string - test

That's all for this topic matches() method in Java String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. How to Create Immutable Class in Java
  2. Java String Interview Questions And Answers
  3. Java String Search Using indexOf(), lastIndexOf() And contains() Methods
  4. String Vs StringBuffer Vs StringBuilder in Java
  5. Java Program to Find The Longest Palindrome in a Given String

You may also like-

  1. Java for Loop With Examples
  2. Java Abstract Class and Abstract Method
  3. TreeSet in Java With Examples
  4. Thread States (Thread Life Cycle) in Java Multi-Threading
  5. Java Stream API Tutorial
  6. DataSource in Java-JDBC
  7. Spring Web MVC Tutorial
  8. Class And Object in Python

Tuesday, September 6, 2022

Java join() Method - Joining Strings

Though String is a very important class and it provides a lots of methods for comparison of strings, searching with in string but somehow there was no method for joining multiple strings in Java. In Java 8 join() method has been added in the String class which makes it very easy to join the multiple strings. There is also a StringJoiner class in Java 8 that can be used for joining the Strings.

There are many scenarios when you want to join multiple strings to create a new string may be with a delimiter too between two strings, like pipe (|) or comma (,). Before Java 8 you would have used StringBuilder or StringBuffer class in Java to append the string one by one for joining or may be you would have used any third party library like Apache Commons which has StringUtils class.

Code snippet using StringBuilder to join Strings in Java

StringBuilder sb = new StringBuilder();
boolean firstFlg = true;
String delimiter = “,”;
for (String str: strArray){
  if (firstFlg){
    firstFlg = false;
  }
  else{       
    sb.append(delimiter);
  }
  sb.append(str);
}
return
sb.toString();

join() Method in Java String Class

With the addition of join() method in the String class it has become easy to join multiple strings.

There are two overloaded variants of join() method-

  • public static String join(CharSequence delimiter, CharSequence... elements)- Returns a new String composed of copies of the CharSequence elements joined together using the specified delimiter.
  • public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) – Here elements is an Iterable that will have its elements joined together and delimiter is a sequence of characters that is used to separate each of the elements in the resulting String

join() method Java examples

Let's see some examples of joining strings in Java using join() method.

  1. If you have 3 string variables which you want to join with space in between or with '-' in between then it can be done using the following Java code-
    public class StringJoin {
     public static void main(String[] args) {
      String str1 = "An";
      String str2 = "example";
      String str3 = "string";
      
      // joining with space
      String finalStr = String.join(" ", str1, str2, str3);
      System.out.println("str - " + finalStr);
      // joining with hyphen
      finalStr = String.join("-", str1, str2, str3);
      System.out.println("str - " + finalStr);
     }
    }
    

    Output

    str - An example string
    str - An-example-string
    
  2. If you have 3 string variables day, month and year which you want to join to create a date in format dd/mm/yyyy, then using join() method you can do it as follows.
    public class StringJoin {
     public static void main(String[] args) {
      String str1 = "26";
      String str2 = "06";
      String str3 = "2019"; 
      String finalStr = String.join("/", str1, str2, str3);
      System.out.println("str - " + finalStr);  
     }
    }
    

    Output

    str - 26/06/2019
    
  3. If you have list of Strings then you can use the second join method (where Iterable is passed as parameter) to join all the strings with in the list.
    import java.util.ArrayList;
    import java.util.List;
    
    public class ListJoin {
      public static void main(String[] args) {
        List<String> strList = new ArrayList<String>();
        strList.add("An");
        strList.add("example");
        strList.add("string");
        // joining with comma as delimiter
        String finalStr = String.join(",", strList);
        System.out.println("str - " + finalStr);
      }
    }
    

    Output

    str – An,example,string
    
  4. Using join() method to join all the elements of a Set.
    public class JoinSet {
     public static void main(String[] args) {
      Set<String> strings = new LinkedHashSet<>(List.of("An", "example", "string"));
      String joinedStr = String.join(":", strings);
      System.out.println("Joined String- " + joinedStr);
     }
    }
    

    Output

    Joined String- An:example:string
    

That's all for this topic Java join() Method - Joining Strings. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. String in Java Tutorial
  2. String Vs StringBuffer Vs StringBuilder in Java
  3. Java String substring() Method - Getting Substring
  4. How to Create Immutable Class in Java
  5. Java String Interview Questions And Answers

You may also like-

  1. Find All Permutations of a Given String Java Program
  2. Check Given Strings Anagram or Not Java Program
  3. Difference Between Checked And Unchecked Exceptions in Java
  4. static block in Java
  5. this Keyword in Java With Examples
  6. Dependency Injection in Spring Framework
  7. TreeSet in Java With Examples
  8. Java Exchanger With Examples

Monday, September 5, 2022

Java split() Method - Splitting a String

split() method in Java String class is used to split the string into one or more substring based on the given regular expression.

Java split() method has 2 variants-

  • split(String regex)- Splits this string around matches of the given regular expression. This method returns an array containing each substring of this string that matches the given expression.
  • split(String regex, int limit)- The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

String's split() method examples

  1. If you have a string where one (or more) spaces are used and you want to split this String around those spaces. Here passed regex "\\s+" means one or more spaces.
    public class StringSearch {
     public static void main(String[] args) {
      String str1 = "split example    program";
      String[] strArray = str1.split("\\s+");
      System.out.println("Words in array- " + strArray.length);
      for(String w : strArray){
       System.out.println("words - " + w);
      }
     }
    }
    

    Output

    Words in array- 3
    words - split
    words - example
    words – program
    
  2. If you have a date in dd/mm/yyyy format and you want to split this date String into day, month and year.
    public class StringSearch {
     public static void main(String[] args) {
      String date = "20/01/2016";
      String[] dateArr = date.split("/");
      System.out.println("" + dateArr.length);
      System.out.println("day " + dateArr[0] + " Month " + dateArr[1] +
        " Year " + dateArr[2]);
     }
    }
    

    Output

    3
    day 20 Month 01 Year 2016
    

Using split() method with limit argument

Suppose you just want the day part of the date then you can use the split() method which also passes limit as argument-

public class StringSearch {

 public static void main(String[] args) {
  String date = "20/01/2016";
  String[] dateArr = date.split("/", 2);
  System.out.println("" + dateArr.length);
  System.out.println("day " + dateArr[0]);
 }
}

Output

2
day 20

That's all for this topic Java split() Method - Splitting a String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. String Comparison in Java equals(), compareTo(), startsWith() Methods
  2. Java String substring() Method - Getting Substring
  3. String Vs StringBuffer Vs StringBuilder in Java
  4. Find All Permutations of a Given String Java Program
  5. Java String Interview Questions And Answers

You may also like-

  1. Count Number of Words in a String Java Program
  2. Java Program to Find The Longest Palindrome in a Given String
  3. Multi-Catch Statement in Java Exception Handling
  4. final Vs finally Vs finalize in Java
  5. Java Pass by Value or Pass by Reference
  6. finalize() Method in Java
  7. Difference Between HashMap And Hashtable in Java
  8. Callable and Future in Java With Examples

Sunday, September 4, 2022

Removing Spaces Between Words in a String Java Program

If you need to remove spaces between words in a String in Java then there are the following two options-

  • Using replaceAll() method of the Java String class.
  • Using StringUtils.normalizeSpace() method that requires Apache Commons Lang.

Remove spaces between words using replaceAll() method

  • replaceAll(String regex, String replacement)- Replaces each substring of this string that matches the given regular expression with the given replacement.

Here "\\s+" is passed as regular expression that matches any number of whitespaces and single space (" ") is passed as replacement string to replace matched spaces with a single space.

public class StringSpaceRemoval {

 public static void main(String[] args) {
  String str = "  Example   String   ";
  // regex to match any number of spaces
  str = str.replaceAll("\\s+", " ");
  System.out.println(str);
 }
}

Output

 Example String 

Here leading and trailing spaces are also replaced with a single space. You may want to completely remove any leading and trailing spaces and normalize the spaces in between the words for that you can use trim() method along with replaceAll().

public class StringSpaceRemoval {

 public static void main(String[] args) {
  String str = "  Example   String   ";
  // regex to match any number of spaces
  str = str.trim().replaceAll("\\s+", " ");
  System.out.println(str);
 }
}

Output

Example String

Remove spaces between words using StringUtils.normalizeSpace()

Use of this method requires commons-lang jar, Maven dependency for that is as given below-

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

StringUtils.normalizeSpace() method takes care of removing any leading and trailing spaces and normalizes the spaces between the words.

import org.apache.commons.lang3.StringUtils;

public class StringSpaceRemoval {

 public static void main(String[] args) {
  String str = "  Example   String   ";
  str = StringUtils.normalizeSpace(str);
  System.out.println(str);
 }
}

Output

Example String

That's all for this topic Removing Spaces Between Words in a String Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. If Given String Sub-Sequence of Another String in Java
  2. How to Find Common Elements Between Two Arrays Java Program
  3. Convert String to int in Java
  4. How to Display Time in AM-PM Format in Java
  5. Creating PDF in Java Using Apache PDFBox

You may also like-

  1. Running Dos/Windows Commands From Java Program
  2. Linked List Implementation Java Program
  3. How to Read File From The Last Line in Java
  4. finally Block in Java Exception Handling
  5. Java PriorityBlockingQueue With Examples
  6. Spring Batch Processing With List of Objects in batchUpdate() Method
  7. Spring MVC Exception Handling - @ExceptionHandler And @ControllerAdvice Example
  8. Removing Spaces From String in Python

Wednesday, August 31, 2022

Java trim(), strip() - Removing Spaces From String

In this post we’ll see what all options are there in Java String class to remove leading, trailing spaces from a String, even spaces from in between the words in a String.

String class methods for removing spaces

  • trim()- Returns a string whose value is this string, with all leading and trailing space removed, where space is defined as any character whose codepoint is less than or equal to 'U+0020'
  • strip()- Java 11 onward there is also a strip() method which does the same task of removing all leading and trailing white spaces. How it differs from trim() is that in strip() method whether the specified character is white space or not is determined by internally using Character.isWhitespace() method which also considers unicodes like \u2007, \u202F as whitespaces (greater than 'U+0020')
  • stripLeading()- Variant of strip() method that removes all leading white spaces.
  • stripTrailing()- Variant of strip() method that removes all trailing white spaces.
  • replaceAll()- To remove spaces any where in a string; leading, trailing or between words replaceAll() method can be used with regular expression “\\s+” as parameter to match any numbers of spaces anywhere.

Removing spaces from Java string examples

Let us see examples using the methods mentioned above.

1. Using trim() method to remove spaces from a String in Java. This method removes leading and trailing spaces not the spaces between words.

public class StringSpaceRemoval {

 public static void main(String[] args) {
  String str = "  Example String ";
  str = str.trim();
  System.out.println("String- " + str);
 }
}

Output

String- Example   String

2. Using strip() method to remove spaces. This method is added in Java 11 and it takes into account unicodes categorized as space separator having value greater than '\u0020

public class StringSpaceRemoval {

 public static void main(String[] args) {
  String str = '\u2001'+"Example String";
  System.out.println("String- " + str);
  System.out.println("String after trim- " + str.trim());
  str = str.strip();
  System.out.println("String after strip- " + str);
 }
}

Output

String-  Example String
String after trim-  Example String
String after strip- Example String

As you can see trim() method is not able to remove space created by ‘\u2001’ but strip() method could.

3. If you have to remove all the spaces; leading, trailing and spaces between the words then you can use replaceAll() method.

public class StringSpaceRemoval {

 public static void main(String[] args) {
  String str = "  Example   String   ";
  // regex to match any number of spaces
  str = str.replaceAll("\\s+", "");
  System.out.println(str);
 }
}

Output

ExampleString

That's all for this topic Java trim(), strip() - Removing Spaces From String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. Compact Strings in Java
  2. Check String Null or Empty in Java
  3. String Comparison in Java equals(), compareTo(), startsWith() Methods
  4. Java Program to Find The Longest Palindrome in a Given String
  5. Java String Interview Questions And Answers

You may also like-

  1. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  2. Creating Custom Exception Class in Java
  3. Java Pass by Value or Pass by Reference
  4. ArrayList in Java With Examples
  5. Java StampedLock With Examples
  6. Optional Class in Java With Examples
  7. Namespace And Variable Scope in Python
  8. Spring Object XML Mapping (OXM) JAXB Example