Sorry, Java's substring is not as flexible as Python's slice notation.

In particular:

  • You can give it just a begin, or a begin and end, but not just an end. (Also, no step, but you don't miss that as much.)
  • Negative indices are an error, not a count from the end.

You can see the docs here.

However, it's not hard at all to write this on your own:

public String slice_start(String s, int startIndex) {
    if (startIndex < 0) startIndex = s.length() + startIndex;
    return s.substring(startIndex);
}

public String slice_end(String s, int endIndex) {
    if (endIndex < 0) endIndex = s.length() + endIndex;
    return s.substring(0, endIndex);
}

public String slice_range(String s, int startIndex, int endIndex) {
    if (startIndex < 0) startIndex = s.length() + startIndex;
    if (endIndex < 0) endIndex = s.length() + endIndex;
    return s.substring(startIndex, endIndex);
}

Put those as static methods of some utility class.

Obviously this isn't exactly the same as Python, but it probably handles all the cases you want, and very simple. If you want to handle other edge cases (including things like step and passing slices around and so on), you can add whatever additional code you want; none of it is particularly tricky.


Other sequences are basically the same, but there you're going to want subSequence instead of substring. (You can also use subSequence on strings, because a String is a CharSequence.)

Arrays aren't actually a type of sequence at all; you'll need to write code that explicitly creates a new Array and copies the sub-array. But it's still not much more complicated.


Note that you may want to look for a library that's already done this for you. There are at least three linked in other answers on this page, which should make your search easy. :) (You may still want to do it for yourself once, just to understand how those libraries work—but for production code, I'd rather use a library where someone else has figured out and tested all of the edge cases than to reimplement the wheel and deal with them as they get caught in unit tests, or errors in the field…)

Answer from abarnert on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java string › java equivalent to python’s easy string slicing
Java Equivalent to Python’s Easy String Slicing | Baeldung
March 25, 2025 - We can use a simple loop to perform step-slicing of any string in Java. In Python, we can efficiently use [::-1] to reverse a string:
Top answer
1 of 8
25

Sorry, Java's substring is not as flexible as Python's slice notation.

In particular:

  • You can give it just a begin, or a begin and end, but not just an end. (Also, no step, but you don't miss that as much.)
  • Negative indices are an error, not a count from the end.

You can see the docs here.

However, it's not hard at all to write this on your own:

public String slice_start(String s, int startIndex) {
    if (startIndex < 0) startIndex = s.length() + startIndex;
    return s.substring(startIndex);
}

public String slice_end(String s, int endIndex) {
    if (endIndex < 0) endIndex = s.length() + endIndex;
    return s.substring(0, endIndex);
}

public String slice_range(String s, int startIndex, int endIndex) {
    if (startIndex < 0) startIndex = s.length() + startIndex;
    if (endIndex < 0) endIndex = s.length() + endIndex;
    return s.substring(startIndex, endIndex);
}

Put those as static methods of some utility class.

Obviously this isn't exactly the same as Python, but it probably handles all the cases you want, and very simple. If you want to handle other edge cases (including things like step and passing slices around and so on), you can add whatever additional code you want; none of it is particularly tricky.


Other sequences are basically the same, but there you're going to want subSequence instead of substring. (You can also use subSequence on strings, because a String is a CharSequence.)

Arrays aren't actually a type of sequence at all; you'll need to write code that explicitly creates a new Array and copies the sub-array. But it's still not much more complicated.


Note that you may want to look for a library that's already done this for you. There are at least three linked in other answers on this page, which should make your search easy. :) (You may still want to do it for yourself once, just to understand how those libraries work—but for production code, I'd rather use a library where someone else has figured out and tested all of the edge cases than to reimplement the wheel and deal with them as they get caught in unit tests, or errors in the field…)

2 of 8
11

Java Boon Slice Notation allows all of that and with Strings, Lists, Sets, Maps, etc.

Many languages have slice notation (Ruby, Groovy and Python). Boon adds this to Java.

Boon has three slc operators: slc, slc (start only), and slcEnd.

With Boon you can slice strings, arrays (primitive and generic), lists, sets, tree sets, tree map's and more.

Slice notations - a gentle introduction

The boon slice operators works like Python/Ruby slice notation:

Ruby slice notation

 arr = [1, 2, 3, 4, 5, 6]
 arr[2]    #=> 3
 arr[-3]   #=> 4
 arr[2, 3] #=> [3, 4, 5]
 arr[1..4] #=> [2, 3, 4, 5]

Python slice notation

string = "foo bar" 
string [0:3]  #'foo'
string [-3:7] #'bar'

What follows is derived from an excellent write up on Python's slice notation:

The basics of slice notations are as follows:

Python Slice Notation

     a[ index ]       # index of item
     a[ start : end ] # items start through end-1
     a[ start : ]     # items start through the rest of the array
     a[ : end ]       # items from the beginning through end-1
     a[ : ]           # a copy of the whole array

Java Slice Notation using Boon:

      idx( index )         // index of item
      slc( a, start, end ) // items start through end-1
      slc( a, start )      // items start through the rest of the array
      slcEnd( a, end )     // items from the beginning through end-1
      copy( a )            // a copy of the whole array

slc stands for slice idx stands for index slcEnd stands for end slice. copy stands for well, err, um copy of course

The key point to remember is that the end value represents the first value that is not in the selected slice. So, the difference between end and start is the number of elements selected. The other feature is that start or end may be a negative number, which means it counts from the end of the array instead of the beginning.

Thus:

Python slice notation with negative index

         a[ -1 ]    # last item in the array
         a[ -2: ]   # last two items in the array
         a[ :-2 ]   # everything except the last two items

Java negative index

         idx   ( a, -1)     // last item in the array
         slc   ( -2 )       // last two items in the array
         slcEnd( -2 )       // everything except the last two items

Python and Boon are kind to the programmer if there are fewer items than you ask for: Python does not allow you to go out of bounds, if you do it returns at worse an empty list. Boon follows this tradition, but provides an option to get exception for out of bounds (described later). In Python and Boon, if you go to far, you get the length, if you try to go under 0 you get 0 (under 0 after calculation). Conversely, Ruby gives you a null pointer (Nil). Boon copies Python style as one of the goals of Boon is to avoid ever returning null (you get an exception, Option). (Boon has second operator called zlc which throws an out of bounds index exception, but most people should use slc.)

For example, if you ask for slcEnd(a, -2) (a[:-2]) and a only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, and with Boon you have that option.

More slicing

Here are some basic Java types, list, array, veggies, primitive char array, and a primitive byte array.

Declare variables to work with in Boon

//Boon works with lists, arrays, sets, maps, sorted maps, etc.
List<String> fruitList;
String [] fruitArray;
Set<String> veggiesSet;
char [] letters;
byte [] bytes;
NavigableMap <Integer, String> favoritesMap;
Map<String, Integer> map;

//In Java a TreeMap is a SortedMap and a NavigableMap by the way.

Boon comes with helper methods that allow you to easily create lists, sets, maps, concurrent maps, sorted maps, sorted sets, etc. The helper methods are safeList, list, set, sortedSet, safeSet, safeSortedSet, etc. The idea is to make Java feel more like list and maps are built in types.

Initialize set, list, array of strings, array of chars, and array of bytes

veggiesSet  =  set( "salad", "broccoli", "spinach");
fruitList   =  list( "apple", "oranges", "pineapple");
fruitArray  =  array( "apple", "oranges", "pineapple");
letters     =  array( 'a', 'b', 'c');
bytes       =  array( new byte[]{0x1, 0x2, 0x3, 0x4});

There are even methods to create maps and sorted maps called map, sortedMap, safeMap (concurrent) and sortedSafeMap(concurrent). These were mainly created because Java does not have literals for lists, maps, etc.

Java: Use map operator to generate a SortedMap and a Map

 favoritesMap = sortedMap(
      2, "pineapple",
      1, "oranges",
      3, "apple"
 );


 map =    map (
    "pineapple",  2,
    "oranges",    1,
    "apple",      3
 );

You can index maps, lists, arrays, etc. using the idx operator.

Java: Using the Boon Java idx operator to get the values at an index

 //Using idx to access a value.

 assert idx( veggiesSet, "b").equals("broccoli");

 assert idx( fruitList, 1 ).equals("oranges");

 assert idx( fruitArray, 1 ).equals("oranges");

 assert idx( letters, 1 ) == 'b';

 assert idx( bytes, 1 )      == 0x2;

 assert idx( favoritesMap, 2 ).equals("pineapple");

 assert idx( map, "pineapple" )  == 2;

The idx operators works with negative indexes as well.

Java: Using idx operator with negative values

         //Negative indexes

          assert idx( fruitList, -2 ).equals("oranges");

          assert idx( fruitArray, -2 ).equals("oranges");

          assert idx( letters, -2 ) == 'b';

          assert idx( bytes, -3 )   == 0x2;

Ruby, Groovy and Python have this feature. Now you can use this in Java as well! The Java version (Boon) works with primitive arrays so you get no auto-boxing.

Something that Ruby and Python don't have is slice notation for SortedSets and SortedMaps. You can use slice notation to search sorted maps and sorted sets in Java

Slice notations works with sorted maps and sorted sets.

Here is an example that puts a few concepts together.

          set = sortedSet("apple", "kiwi", "oranges", "pears", "pineapple")

          slcEnd( set, "o" )      //returns ("oranges", "pears", "pineapple")
          slc( set, "ap", "o" )   //returns ("apple", "kiwi"),
          slc( set, "o" )         //returns ("apple", "kiwi")

You are really doing with slicing of sorted maps and sorted sets is a between query of sorts. What item comes after "pi"?

          after(set, "pi") //pineapple

And before pineapple?

          before(set, "pi")

Ok, let go through it step by step....

  NavigableSet<String> set =
          sortedSet("apple", "kiwi", "oranges", "pears", "pineapple");

  assertEquals(

          "oranges", idx(set, "ora")

  );

Remember: TreeSet implements NavigableSet and SortedSet.

This was derived from my blog....

http://rick-hightower.blogspot.com/2013/10/java-slice-notation-to-split-up-strings.html

More examples are there.

I derived some of the verbiage from this discussion on Python slicing.

Explain Python's slice notation

Here is the Boon project link:

https://github.com/RichardHightower/boon

Now let's continue to SLICE!

We can look up the first fruit in the set that starts with 'o' using:

idx(set, "o")

Here is is with the set of fruit we created earlier (set is a TreeSet with "apple", "kiwi", "oranges", "pears", "pineapple" in it).

      assertEquals(

          "oranges", idx(set, "o")

      );

We found oranges!

Here it is again but this time we are searching for fruits that start with "p", i.e., idx(set, "p").

      assertEquals(
          "pears",
          idx(set, "p")
      );

Yeah! We found pears!

How about fruits that start with a "pi" like "pineapple" - idx(set, "pi")

  assertEquals(
          "pineapple",
          idx(set, "pi")
  );

You could also ask for the item that is after another item. What is after "pi"? after(set, "pi")

  assertEquals(

          "pineapple",
          after(set, "pi")

  );

The "pineapple" is after the item "pi". after and idx are the same by the way. So why did I add an after? So I can have a before!!! :) What if you want to know what is before "pi"?

before(set, "pi")

 
Discussions

Slice string in java - Stack Overflow
How slice string in java? I'm getting row's from csv, and xls, and there for example data in cell is like 14.015_AUDI How can i say java that it must look only on part before _ ? So after manipu... More on stackoverflow.com
🌐 stackoverflow.com
How to slice a string based on the Nth occurrence of a certain character
You want String.split(). public static void main(String[] args) { String s = "test1.test2.test3.test4"; // First parameter is the delimiter, second parameter is the size of the array that you want returned. String splitString = s.split("\\." , 2); //The last string in this array will be the one that you want. String myString = splitString[splitString.length-1]; System.out.println(myString); } The output is: test2.test3.test4 In your case, if you want everything AFTER the n th period, then the size of your array would need to be 1 higher than n. So if you wanted everything after the 2nd period, you would use: s.split("\\." , 3); Again, you would still want the last String in the array, since the array that's returned would be: ["test1" , "test2" , "test3.test4"] More on reddit.com
🌐 r/learnjava
4
2
September 27, 2016
Java string slice
please i have been try to slice a string on java but the statement are not correct can anyone tell me where i have made a mistake. var name = "caleb"; var cut More on sololearn.com
🌐 sololearn.com
7
1
March 4, 2024
Question about string sequencing and slicing
Hi I’ve just begun learning how to code in python and have come across string sequencing and slicing. I’m having trouble understanding the concept of the 0. For example, If I were to sequence the string “Michael Jackson” the python would assign the M=0 I=1 C=2 H=3 A=4 and so and so forth. More on discuss.python.org
🌐 discuss.python.org
19
0
July 16, 2022
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Java String Slicing Example - Java Code Geeks
March 21, 2025 - Python provides a powerful and concise way to slice Strings using simple syntax. However, Java does not have built-in String slicing like Python.
🌐
W3Schools
w3schools.com › python › python_strings_slicing.asp
Python - Slicing Strings
Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... You can return a range of characters by using the slice syntax.
🌐
Coding Champ
coding-champ.com › tutorials › java › string-slicing
Java - String Slicing
Another example which throws exception is using positive index that's outside of the string bounds. Practice with tests, puzzles and battles with our mobile app! Python · Java · JavaScript · C++ C# PHP · Data Types · Calculations · Assignments · If Statement ·
Find elsewhere
🌐
W3Schools
w3schools.com › python › gloss_python_string_slice.asp
Python Slice Strings
Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... You can return a range of characters by using the slice syntax.
🌐
W3Schools
w3schools.com › jsref › jsref_slice_string.asp
JavaScript String slice() Method
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
🌐
Programiz
programiz.com › python-programming › methods › built-in › slice
Python slice()
Now we know about slice objects, let's see how we can get substring, sub-list, sub-tuple, etc. from slice objects. # Program to get a substring from the given string py_string = 'Python' # stop = 3 # contains 0, 1 and 2 indices
🌐
W3Schools
w3schools.com › java › ref_string_substring.asp
Java String substring() Method
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
🌐
GeeksforGeeks
geeksforgeeks.org › python › string-slicing-in-python
String Slicing in Python - GeeksforGeeks
A positive value slices from left to right, while a negative value slices from right to left. If omitted, it defaults to 1 (no skipping of characters). Return Type: The result of a slicing operation is always a string (str type) that contains a subset of the characters from the original string.
Published: July 12, 2025
🌐
InterServer
interserver.net › home › python › how to slice strings in python: step-by-step tutorial
How to Slice Strings in Python: Step-by-Step Tutorial - Interserver Tips
April 23, 2026 - Strings are one of the most common data types in Python, and you will use them in almost every program. String slicing is a way to get a part of a string. Instead of using the whole text, you can extract exactly what you need. This makes your code cleaner and more efficient. Slicing is useful for many tasks, like picking certain letters, reversing words, or breaking data into pieces. In this tutorial, you will learn step by step how to slice strings in Python.
🌐
Real Python
realpython.com › lessons › string-slicing
String Slicing (Video) – Real Python
Python also allows a form of indexing syntax that extracts substrings from a string. It’s known as string slicing. The syntax that you use looks really similar to indexing. Instead of just one value being put in the square brackets, you put ...
Published: October 1, 2019
🌐
EyeHunts
tutorial.eyehunts.com › home › string slicing in python | example code
String slicing in Python | Example code
February 20, 2023 - JAVA · Python · Contact US · Interview Puzzle · by Rohit · November 8, 2021February 20, 2023 · Getting a substring from a given string is called String slicing in Python. A simple way to do this is to use the simple slicing operator. Python ...
🌐
Medium
medium.com › @ghoshsiddharth25 › python-strings-slicing-methods-formatting-internals-c0d407fa1646
Python Strings — Slicing, Methods, Formatting & Internals | by Siddharth Ghosh | Medium
July 25, 2026 - A string is a sequence of Unicode characters. ... Single, double, and triple quotes all work. ... text = "Python Programming" print(text[0:6]) # Python print(text[:6]) # Python print(text[7:]) # Programming… ... Software professional skilled in Java, Python, Scala, Big Data & Android.
🌐
AlgoCademy
algocademy.com › link
String Slicing in Java | AlgoCademy
Assignment Follow the Coding Tutorial and let's slice some strings! Hint Look at the examples above if you get stuck. String slicing is a fundamental concept in Java programming that allows you to extract a portion of a string.
🌐
Python Central
pythoncentral.io › cutting-and-slicing-strings-in-python
Cutting and slicing strings in Python - Python Central
September 6, 2023 - An overview on all of the ways you can cut and slice strings with the Python programming language. With lots of examples/code samples!
🌐
Python.org
discuss.python.org › python help
Question about string sequencing and slicing - Python Help - Discussions on Python.org
July 16, 2022 - Hi I’ve just begun learning how to code in python and have come across string sequencing and slicing. I’m having trouble understanding the concept of the 0. For example, If I were to sequence the string “Michael Jackson” the python would assign the M=0 I=1 C=2 H=3 A=4 and so and so forth.