String manipulation is done most often while programming. Like removing spaces in or around the string text. This also known as ‘strip’ping off spaces in the string. So up till now we are all aware of the different ways to remove spaces from string in java, namely trim, replaceAll. However, java 11 has made some new additions to these with methods like, strip, stripLeading , stripTrailing.

Majority of the times, we just use the trim method for removing spaces. We never stop and think is there may be a better way to suit our need? Sure, trim() works well for most of the cases, but there are many different methods in java. Each having its own advantages and disadvantages. How do we decide which method suits us best?

Well, in this blog we shall cover the different methods in detail.

    Different ways to remove spaces from string in java

  1. : Removing leading and trailing spaces from the string
  2. : Removes spaces at the beginning and end of the string. Strip method is Unicode charset aware
  3. : Differences between trim and strip method
  4. : Removes white spaces only from the beginning of the string
  5. : Removes white spaces only from ending of the string
  6. : Replaces all target characters with new character
  7. : Replaces all matched characters with new character. This method takes regular expression as input to identify target substring that needs to be replaced
  8. : Differences between replace and replaceAll method
  9. : Replaces only first occurrence of target substring with new replacement string

Most important point to note is that in java a string object is immutable. It means we cannot modify a string, hence all the methods returns new string with all the transformations.

trim() method in java

trim() is the most commonly used method by java developers for removing leading and trailing spaces. For trim method space character means any character whose ASCII value is less than or equal to 32 (‘U+0020’).

Example of trim method to remove spaces:

public class StringTrimTest {

    public static void main(String[] args) {
        String string = "    String    with    space    ";
        System.out.println("Before trim: \"" + string +"\"");
        System.out.println("After trim: \"" + string.trim() +"\"");
   }
}

Output:

Before trim: "    String    with    space    "
After trim: "String    with    space"

strip() method Java 11

In the release of Java 11 new strip() method was added to remove leading and trailing spaces from String.

This method was added as there are various space characters according to Unicode standards having ASCII value more than 32(‘U+0020’). Ex: 8193(U+2001).

To identify these space characters, new method isWhitespace(int) was added from Java 1.5 in Character class. This method uses unicode to identify space characters. You can read more about unicode space characters here.

The strip method uses this Character.isWhitespace(int) method to cover wide range of white space characters and remove them.

Example of strip():

public class StringStripTest {
    public static void main(String[] args) {
        String string = "    String    with    space    ";
        System.out.println("Before strip: \"" + string+"\"");
        System.out.println("After strip: \"" + string.strip()+"\"");
    }
}

Output:

Before strip: "    String    with    space    "
After strip: "String    with    space"

Difference between trim and strip method in java

trim()strip()
From Java 1From Java 11
Uses codepoint(ASCII) valueUses Unicode value
Removes leading and trailing character(space)Removes leading and trailing character(space)
Removes characters having ASCII value less than or equal to ‘U+0020’ or ’32’Removes all space characters according to unicode

Let’s look at the example where we will use white space character higher than 32 (‘U+0020’) unicode.

public class StringTrimVsStripTest {
    public static void main(String[] args) {
        String string = '\u2001'+"String    with    space"+ '\u2001';
        System.out.println("Before: \"" + string+"\"");
        System.out.println("After trim: \"" + string.trim()+"\"");
        System.out.println("After strip: \"" + string.strip()+"\"");
   }
}

Output:

Before: "  String    with    space  "
After trim: " String    with    space "
After strip: "String    with    space"

In the above example we can see that trim method is unable to remove space character added by ‘\u2001’ unicode character.

Note: If you are running on windows machine, you may not be able to see the similar output due to limited unicode set. You can use online compilers to run program. Some online compiler links are as below,
Java-8: https://www.jdoodle.com/online-java-compiler/
Java-11: https://www.tutorialspoint.com/compile_java_online.php

stripLeading() method Java 11

Added in Java 11, stripLeading() method removes all leading spaces from a String.

Similar to strip method stripLeading also uses Character.isWhitespace(int) for identifyng white spaces.

public class StringStripLeadingTest {
    public static void main(String[] args) {
        String string = "    String    with    space    ";
        System.out.println("Before: \"" + string+"\"");
        System.out.println("After : \"" + string.stripLeading()+"\"");
    }
}

Output:

Before: "    String    with    space    "
After : "String    with    space    "

stripTrailing() method Java 11

Added in Java 11, stripTrailing() method removes all ending spaces from a String.

Similar to strip method stripTrailing also uses Character.isWhitespace(int) for identifying white spaces.

public class StringStripTrailingTest {

    public static void main(String[] args) {
      String string = "    String    with    space    ";
      System.out.println("Before: \"" + string+"\"");
        System.out.println("After : \"" + string.stripTrailing()+"\"");
    }
}

Output:

Before:"    String    with    space    "
After :"    String    with    space"

replace(CharSequence target, CharSequence replacement):

Added from java 1.5, This method is used to replace each target substring with the specified replacement string.

This method replaces all matching target elements.

Note: One more method replace(char oldChar, char newChar) is present in java string class. The only differences is that this method takes single character as target and replacement. We cannot use this method to remove space, because we cannot have empty character as replacement.

Example to remove all spaces from string

public class StringReplaceTest {
 
    public static void main(String[] args) {
        String string = "    String    with    space    ";
        System.out.println("Before : \"" + string + "\"");
        System.out.println("Replace: \"" + string.replace(" ", "") + "\"");
    }
}

Output:

Before  : "    String    with    space    "
Replace : "Stringwithspace" 

replaceAll (String regex, String replacement)

Added in java 1.4, this is one of the most powerful method for string manipulation. We can use this method for many purposes.

Using replaceAll() method we can replace each matching regular expression substring with the given replacement string. For example for removing all spaces, removing leading spaces, removing trailing spaces and so on.

We just need to create correct regular expression with correct replacement parameter. Some regular expression examples as below:

\s+Find all space
^\s+Find all spaces at line beginning
\s+$Find all spaces at line ending

Example to replacing spaces in string,

Note: In java to add ‘/’ we have to use escape character so for “\s+” we have to use “\\s+”

public class StringReplaceAllTest {
    public static void main(String[] args) {
        String string = "    String    with    space    ";
        System.out.println("Before replaceAll : \"" + string+"\"");
        System.out.println("Replace all space : \"" + string.replaceAll(" ", "") + "\"");
        System.out.println("Replace all regex : \"" + string.replaceAll("\\s+", "") + "\"");
        System.out.println("Replace Leading   : \"" + string.replaceAll("^\\s+", "") + "\""); 
        System.out.println("Replace trailing  : \"" + string.replaceAll("\\s+$", "") + "\"");
    }
}

Output:

Before replaceAll : "    String    with    space    "
Replace all space : "Stringwithspace"
Replace all regex : "Stringwithspace"
Replace Leading   : "String    with    space    "
Replace trailing  : "    String    with    space"

As we can see that replaceAll() is pretty powerful method if we use it with proper regular expression.

Difference between replaceAll and replace method

replaceAll()replace()
From Java 1.4From Java 1.5
Accepts regular expression for target identificationAccepts string for target identification
Used for fix or dynamic string replacementUsed for fix string replacement
Removes characters having ASCII value less than or equal to ‘U+0020’ or ’32’Removes all space characters according to unicode

replaceFirst(String regex, String replacement)

Added in java 1.4, replaceFirst method replaces only the first match of given regular expression with replacement string.

This method can be very useful if you just need to replace only one first occurrence. For example if we just need to remove leading spaces we can use “\\s+” or “^\\s+”.

We can also use this method to remove trailing spaces by using “\\s+$” regular expression. As this expression will only match the last spaces in line. So last spaces are considered as the first match for this method.

Let’s take an example for removing leading and trailing spaces from string

public class StringReplaceFistTest {
      public static void main(String[] args) {
      String string = "    String    with    space    ";
      System.out.println("Before   : \"" + string+"\"");
        System.out.println("Replace  : \"" + string.replaceFirst("space", "update") + "\"");
        System.out.println("Leading  : \"" + string.replaceFirst("\\s+", "") + "\"");
        System.out.println("Trailing : \"" + string.replaceFirst("\\s+$", "") + "\"");    }
}

Output

Before   : "    String    with    space    "
Replace  : "    String    with    update    "
Leading  : "String    with    space    "
Trailing : "    String    with    space"

Fast track reading :

Related topics

Most of the java developers get confused when it comes to the question that, is Java ‘pass-by-value’ or ‘pass-by-reference’.

The answer is that Java is pass-by-value. We will verify that in this blog under the section Pass-by-value for Object data types. Before jumping straight to the conclusion, let’s understand in detail how different variables work in java.

Common mistake done by Java developers

There is one most common mistake that java developers do. They try to update object value using “=” or “new” keyword.

Let’s look at an example where we want to change the color of box and square a number.

// Wrong – this will not return the updated value to calling method

public void changeToPink(Box boxToChange){

boxToChange = new Box(“Pink”);

}

public void square(int value){

value   =  value*value;

}

Topics we will be discussing

What is pass-by-value?

Passing variable by value means the value of the variable is copied into another variable. This copies the data into new memory.

Hence modifying new variable only updates the copy. The original variable value is not changed.

We will look in detail with examples later in this blog.

What is pass by reference?

Passing variable by reference means actual object reference or pointer is passed.

This means modifying the new reference object will update the original object.

Pass-by-value in java for primitive data types

Primitive variables are not objects. So primitive data types are pass-by-value. Which means only value is passed to new variable.

Lets look at the example for better understanding

objects references in stack for pass by value

In the above code we can see that the value of number variable is 5. Then we call the square function.

Even after calling the square function value of number variable is 5 and does not change. Because, we just updated the local(new) variable in square function. This local variable is created in the scope of the function and hence the original number variable is not updated.

How to update primitive parameter from function call?

The only way to update the original primitive variable is by returning value from the function.

Following code will update the value of number variable after calling the function.

public class Tester{
  public static void main(String args[]){
    int number = 5;         // number =5
    number = square(number):
    System.out.println(number); // number = 25
  }

  public void square(int value){
    value = value*value;    // value= 25
    return value;
  }
}

How objects are updated?

If we update the properties of object using any reference variable, values of all reference variables are updated.
In other words if you update the object not the reference variable then original object is updated.

Example if we use following code to update the color of object userBox

public class Box{ 
  String color;
    Number(String color){
    this.color = color;
  }
}

public class Tester{
  public static void main(String args[]){
    Box userBox = new Box("Purple");
    changeToPink(userBox);
    System.out.println(userBox);   // Purple 
  } 
  public staticvoid changeToPink(Box boxToChange){
    System.out.println(boxToChange);    // Purple 
    boxToChange.color="Pink"; 
    System.out.println(boxToChange);     // Pink
  }	
}
Block diagram for object reference

Using above method the object userBox in main method is also updated to pink color.

Pass-by-value in java for Object data types

In java even objects are pass by value. In fact it is passing reference as value. Even if it sounds confusing don’t worry, we can explain it.

In java every object has reference variables. So when we pass object to another function the reference variable is passed. So the references to the actual object is copied.
Now two different reference variables point to the same object. Point to be noted here is that we have two different reference variables.

public class Box{ 
  String color;
  Box(String color){
    this.color = color;
  }
}

public class Tester{ 
  public static void main(String args[]){ 
    Box userBox = new Box("Purple");
    changeToPink(userBox);
    System.out.println(userBox);   // Purple
  }

  public void changeToPink(Box boxToChange){
    System.out.println(boxToChange); // Purple
    boxToChange = new Box("Pink"); 
    System.out.println(boxToChange); // Pink
  }
}
New object workflow

In the above code we have object userBox with color “purple”. Now call the function changeToPink(). Even after calling the function changeToPink(), color of the user box remains “Purple”.

When you use new keyword new object is created. The new box with pink color is stored in local/new variable(boxToChange). Original object userbox remains with old color purple.

Conclusion

As we can see that the updated reference variable does not update the original object. So we can say when we call the function new reference to same objecect is created, so only reference address is passed as value .

Fast track reading

Related topics

“This” keyword in java is one of the most used and very important keywords.
“This” keyword in java is used to refer current class objects.
We can use this keyword to access current class object members.

Image of boy for understanding this keyword in java

So you might be wondering if we can access the current class member directly, Why do we need this keyword?

One of the answer is that, if we have same name for method level and class level variable, then there is an ambiguity for JVM. JVM can not use class variable and uses the local variable by default. In such a case we can use “this” keyword for referring the class level variable.

6 uses of “this” keyword in java

  1. Accessing class level variable
  2. Accessing class methods – default
  3. For calling other constructor of same class
  4. Using ‘this’ keyword as return value
  5. Passing ‘this’ keyword as argument to method
  6. Passing this keyword as argument to constructor

1. Accessing class level variable

Assessing class level variable using this keyword is the most common use of “this” keyword.

Syntax: this.variableName

Most of the time we create some variable in class, then we can set the value from constructor or setter method. If we use same name for argument variable and class level variable then jvm will use local variable always, and it will not set the value to class level variable

lets take a look at example for better understanding,

public class Country{
private String name;
public Country(String name){
Wrong: name = name;
Right: this.name = name;
}
}

As shown in the above example if we just use name =name, value from argument will not be assigned to the class level variable. So the class level variable will always be null. This is because we set value to same variable not the class level variable.

The correct solution is to use this.name = name;

2. Accessing class methods using “this” keyword

For calling the same class method we can use this keyword.

However using this keyword for calling same class method is optional. Because even if you don’t use this keyword, jvm always calls the method from same class by default.

Syntax: this.methodName(arguments);

Following examples shows two cases of calling class method with and without this keyword. In both cases the same method is called.

public class Dog{
	public void testMethod(String[] args){
		printString();
		this.printString();
	}	
	public void printString(){
		System.out.println("Success);
	}
}

Output:

Success
Success

3. For calling other constructor of same class

“This” keyword in java can be used to call other constructor of same class.

Some times we have different constructors with different parameters then you can reuse existing constructor using “this” keyword.
We can call any type of constructor within any constructor. That is we can call default in parameterized, parameterized in defatul or parameterized in parameterized constructor.

Syntax: this() or this(args)

The most important thing to note is that the use of “this” for calling other constructor should be the first line in constructor.

Let’s assume we have a class, let’s call it SomeClass. In this class we have a default constructor and a constructor with variable.
There is some default code that is required for at object creation. So we have added this code in default constructor.
Now we need the same code from default constructor in parameterized constructor. So in this case we can call default constructor from another constructor using this();

public class SomeClass{
	private int variable ;

	public SomeClass(){
		// some code...
	}
	public SomeClass(int variable ){
		this()
		this.variable = variable ;
	}
}

Lets take look at real life examples for shape class. In this class we have length and breadth variables. we need two constructors.
Fist constructor will take two arguments for length and breadth.
Second constructor will take only one argument, this will be same value for length and breath.

public class Shape{
	private int length ;
	private int breadth;

	public Shape(int length ,int breadth){
		this.length = length ;
		this.breadth = breadth;
	}

	public Shape(int length ){
		this(length,length);
	}
}

In above examples we are reusing constructors using “this” keyword in java.

4. Using “this” keyword as return value in java

If you need to return current object instance we can use “this” keyword.
Builder design pattern is one of the most common example of this case.

Let’s look at an example for better understanding,

public class MenuBuilder{
	List<Menu> menus = new ArrayList<>();

	public MenuBuilder withAdd(){
		menus.add(new Menus("Add"))
		 return this;
	}
}

As you can see in the above example, we used “this” as return value in withAdd() Method. In above example withAdd() method returns the current class object.

5. Passing “this” keyword as argument to method

If we want to call some method and the method needs current class object as argument, we can use this keyword to pass the current class object instance.

We can pass this as argument to current class as well as another class methods.

public class City{
	private String name;
	private Country country;
	
	public City(String name){
		this.name= name;		
	}
	public void setCountry(Country country){
		this.country = country;		
	}
}
public class Country{
	private City capital;
	
	public void setCapital(String cityName){
		City capital = new City(cityName);

	// passing country class object using this keyword
		capital.setCountry(this);
		this.capital = capital;		
	}
}

As shown in the above example, we have City and Country class. In City class setCountry() method needs object of Country class. So we have passed Country class instance using “this” keyword from Country class.

6. Passing “this” keyword as argument to constructor

Similar to passing as argument to another method we can also pass “this” keyword as argument to constructor of another class.

We can pass this as argument to constructor of current class as well as to constructor of another class.

public class City{
	private String name;
	private Country country;
	
	public City(String name, Country country){
		this.name= name;		
		this.country = country;		
	}
}
public class Country{
	private City capital;
	
	public void setCapital(String cityName){
	// passing country class object using this keyword
		City capital = new City(cityName,this);
		this.capital = capital;	
	}
}

As shown in the above example, we have City and Country class. In City class constructor needs object of Country class. So we have passed Country class instance using “this” keyword from Country class.

Fast track reading

  • This keyword in java is used to refer current class objects
  • Using this keyword we can access current class instance variable, methods, or constructor
  • We can pass this keyword as argument to another method or constructor
  • We can return current class instance using this keyword

Related topics

Super keyword in java is one of the most used and very important keyword.

In java super keyword refers immediate super(parent) class objects.

Image of father and son for understanding super keyword in java

In java super keyword is only used in case of Inheritance. Whenever we create instance of class, parent class instance is also created. The parent class instance can be accessed by ‘ super’ keyword.

So you might be wondering, if we have inheritance then we can access the parent class member directly. So why do we need super keyword?

The answer is, if we have same member in derived(child) and parent class, then there is an ambiguity for JVM. JVM can not use parent class member so it uses the child class member by default. In such a case we can use super keyword for referring the parent object members.

3 use cases of super keyword in java

Accessing parent class

  1. Variables
  2. Methods
  3. Constructor

Accessing parent class variables

If we have variable with same name in parent and child class, then we need to use super keyword to access parent class variable.

Lets see an example for better understanding:

class Father {
    String hairColor = "Black";
}

class Son extends Father {
    String hairColor = "Blonde";

    public void printHairColor() {
        System.out.println("Parent hair color: " + super.hairColor);
        System.out.println("Child hair color: " + hairColor);
    }
}

public class Tester {
    
    public static void main(String[] args) {
        Son son = new Son();
        son.printHairColor();
    }
}

Output:

Parent hair color: Black
Child hair color: Blonde

In the above example we can see that we are having hairColor variable in Father and Son class. So in Son class we used super.hairColor to access variable from father class.

Accessing parent class methods

If we have any method with same name in parent and child class, then we need to use super keyword to access parent class method.

Lets see an example for better understanding:

class Father {
    String getHairColor(){
	return "Blonde";
    }
}

class Son extends Father {
    String getHairColor(){
	return "Blonde";
    }
    public void printHairColor() {
        System.out.println("Parent hair color: " + super.getHairColor());
        System.out.println("Child hair color: " + getHairColor());
    }
}
public class Tester {

    public static void main(String[] args) {
        Son son = new Son();
        son.printHairColor();
    }
}

Output:

Parent hair color: Black
Child hair color: Blonde

In the above example we can see that we are having getHairColor() method in Father and Son class. So in child class we have used super.getHairColor() to access method from father class.

Accessing parent class constructor

Super keyword can be used to call the parent class constructor. Using super we can call default or parameterized keyword.

In java every time we create an object of a class it calls the parent class constructor even if you don’t specify. This is called as constructor chaining.

If we specify which constructor (default or parameterized) from parent class to call, it will call the specified constructor of parent class. If you don’t specify which constructor to call, it always calls the default constructor of parent class. And if parent class does not have default constructor, then JDK throws compile time error.

We can call the parent class default constructor using super() similarly parameterized constructor using super(arg1, arg2…).

It is important that the super() should be the first line in the child class constructor.

Lets see an example for better understanding:

class Father {
    String hairColor = "Black";
	
    public Father(String hairColor) {
        this.hairColor = hairColor;
    }
    public void printHairColor() {
        System.out.println("Hair color is : " + hairColor);
    }
}
class Son extends Father {

    public Son() {
        super("Blonde");
    }
}

public class Tester {

    public static void main(String[] args) {
        Son son = new Son();
        son.printHairColor();
    }
}

Output:

Hair color is : Blonde

In the above example we can see that we are having public Father(String hairColor) in parent class. So in child Son class we used super(“Blonde”) to access parent class constructor.

Fast track reading

  • In java super keyword refers immediate parent class objects
  • In java super keyword is only used in case of Inheritance
  • Super keyword in java accesses parent class variables, methods or constructor
  • Super call for the parent class constructor should be the first line in the child class constructor
  • If you don’t specify super() in child class, JVM will provide it implicitly

References