Skip to main content
OCA Java Programmer 1Z0-803

JAVA Manipulate data with java.lang.StringBuilder

By November 12, 2013September 12th, 2022No Comments

The class StringBuilder in Java can be very important in your code as it allows you to deal with any

data type and produce a combined string without having to explicitly cast each item that you add to the String. The importance of StringBuilder is identified by the fact that Oracle have one exam objective for this individual class.

Print an IP Address Range

For out example with StringBuilder we are going to use the features it offers to combine integer data into a string so we can print out hosts on a given IP Address range. To emphasize StringBuilder we hard code the Network values and generate the host values; the reality is though we could easily pass the Network values through to the method.

Within our method we define a new instance of the StringBuilder class

StringBuilder sb = new StringBuilder();

At this stage the sb object will have no length, there being no data. We can use sb.append() to add data of any type to the string.

sb.append(192);
sb.append(".");

In these lines we see that it is easy to append integer and string data to the string. The print the current string we could use:

System.out.println(sb);

To revers a string we could use:

sb.reverse();

To clear the content of the StringBuffer string we can use:

sb.setLength(0);

Of course all of this can sit inside a for loop so we can loop around to create full IP Address with both network and host.

package jvp;
public class StrBuild {

    public void doSB(){
       StringBuilder sb = new StringBuilder();
       int oct1 = 192;
       int oct2 = 168;
       int oct3 = 1;
       String dot = ".";
        for (int i = 1; i < 255; i++) {
            sb.append(oct1);
            sb.append(dot);
            sb.append(oct2);
            sb.append(dot);
            sb.append(oct3);
            sb.append(dot);
            sb.append(i);
            System.out.println(sb);
            sb.setLength(0);

        }

    }

}

class Sbc {

    public static void main(String[] args){

        new StrBuild().doSB();

    }
}