Skip to content
JackSparrow414
Go back

Java Development Details (Part 3)

Table of contents

Open Table of contents

Article body

  1. 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.

Java substring code extracting the last five characters using the string length

  1. 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:

Java nested loops using label a and break a to exit the outer loop

This exits the outermost loop directly.


Share this post:

Continue this series

Java Development Details

  1. Java Development Details (Part 1)
  2. Java Development Details (Part 2): Configuration Mistakes
  3. Java Development Details (Part 3)You are here

Comments

Questions, corrections, and experiences are welcome. Sign in with GitHub to comment; both language versions share this discussion.

Comments are available on the live site only.