Table of contents
Open Table of contents
Article body
- Today I needed to extract the last few characters of a Java string. I thought of substring. We probably use substring(begin index,end index) most often, but it did not suit this case: the prefix could vary in length, while only the suffix had a fixed length. Using fixed indices would therefore be unreliable. Instead, I used substring(begin index), which extracts everything from the given position to the end of the string. By calculating that position from the string’s length, I could extract the suffix.
For example, model.getName().length()-5 gives the starting position for extracting the last five characters of the name.

- When we have nested loops, for example:
for(int i=0;i<10;i++){
for(int a=0;a<10;a++){
if(a==3){
}
}
}
Suppose we want to exit the outer loop as well when a==3. I did not previously know how to do this. A plain break exits the inner loop but leaves the outer one running. Today I found the solution: give the for loops labels and use break LABEL to exit the labeled loop.
A label follows Java’s naming rules and ends with a colon. For example, firstLoop: is a label.
Here is a screenshot:

This exits the outermost loop directly.