Last Updated:

Java : How to remove the first character in a string

Often, you need to remove the first character in a string. This can be done very simply by using the standard methods of the String class.

How to remove the first character

Because strings in Java are immutable (their value cannot be changed), you will have to copy the entire string except for the first character to delete the string. This is a rather trivial task that can be solved using the substring method:

 

String s = "!hello, world";
String s2 = s. substring(1);
 
System. out. println(s2);

Result:

 

hello world

 

Here, we declared the variable s and set it to "pppyvet, peace." Then, using the substring method, we created a new line starting at the first position.

The numbering in the line goes from zero, that is, the zero position corresponds to the first symbol "!", the first position - the second symbol "p" and so on:

 

Item number01234567891011
Symbol!nRandinET, mandR

 

Improved version

To create a reusable method to remove the first character from a string, it is important to add null and line length checks:

 

public static String removeFirstChar(String s) {
return (s == null || s. length() == 0) ? "" : (s.substring(1));
}

This is a safe method that will not throw an exception due to the fact that incorrect data was transmitted to the input. If null or a single-character string was passed as an argument, an empty string will be returned as output

The complete source code of the example is:

 

public class RemoveFirstCharSubstring {
 
public static void main(String[] args) {
System. out. println(removeFirstChar("!hello, world"));
}
 
public static String removeFirstChar(String s) {
return (s == null || s. length() == 0) ? "" : (s.substring(1));
}
}

Conclusion

 

Use the substring method to copy part of the original string and get a new line. To write utilitarian methods, it is important to check the incoming data for correctness.