Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java substring not working

Tags:

java

string

Forgive me, I'm new to Java and have an extremely basic question. I have a string and want a substring of it, for example:

String str = "hello";
str.substring(1);
System.out.println(str);

Instead of getting "ello" I get the original "hello", any idea why this is? Thanks.


2 Answers

Strings in Java are immutable. I believe you want to do this:

String str = "hello";
str = str.substring(1);
System.out.println(str);
like image 110
MAV Avatar answered Mar 20 '26 12:03

MAV


Strings cannot be changed in Java, so you will need to re-assign the substring as such:

str = str.substring(1)

as opposed to calling the method by itself.

like image 20
arshajii Avatar answered Mar 20 '26 12:03

arshajii