Forum Stats

  • 3,874,191 Users
  • 2,266,681 Discussions


String Format Appending in Java

User_SQDZD Member Posts: 9 Green Ribbon
edited Aug 12, 2022 7:05AM in Java Programming

I wrote the following code in Java, and the getter methods return Strings:

String stringbuilder="";
stringbuilder = String.format("%d/%d\n", this.getSlotNum(), this.getPortNum());
stringbuilder = stringbuilder+String.format(" " + this.getPortSpeed() +"\n");
stringbuilder = stringbuilder+String.format("%d\n", this.getPortMode());

C# offers a StringBuilder class with an AppendFormat() function that allows me to attach a formatted string straight to the StringBuilder instance without having to concatenate it first. In the Java StringBuilder class, I find an AppendFormat() function.

After looking at this article from Scaler. It suggested the use of the isEmpty() method to check whether the StringBuilder object contains any sequence or not.

StringBuilder ob=new StringBuilder("");

Is there a better method to do what I'm attempting? Please, suggest!


  • BluShadow
    BluShadow Member, Moderator Posts: 42,555 Red Diamond

    * Moderator Note: Question moved to Java Programming for better question alignment, as this is not a C# question - please pick the most appropriate forum for your question in future.

  • User_CTCZS
    User_CTCZS Member Posts: 17 Red Ribbon


    Depending how Your output should looks like You may use the { code } String.isBlank() { code } which check for whitespaces as well. Also You should use { code } StringBuilder.append() { code } for concatenation instead of '+' operator.

    Here's sample code:


    public class StringAppending {

       public StringAppending() {

          String stringbuilder = "";

          stringbuilder = String.format("%d/%d\n", this.getSlotNum(), this.getPortNum());

          stringbuilder = stringbuilder + String.format(" " + this.getPortSpeed() + "\n");

          stringbuilder = stringbuilder + String.format("%d\n", this.getPortMode());


          StringBuilder sb = new StringBuilder(

                getBlankOrNull(String.format("%d/%d\n", this.getSlotNum(), this.getPortNum())));

          sb.append(getBlankOrNull(String.format(" " + this.getPortSpeed() + "\n")))

                .append(getBlankOrNull(String.format("%d\n", this.getPortMode())));



       private String getBlankOrNull(String inStr) {

          try {

             return inStr.isBlank() ? "" : inStr;

          } catch (Exception e) {


             return "";



       public static void main(String[] args) {

          new StringAppending();


       private int getSlotNum() {  return 1;  }

       private int getPortNum() {     return 2;  }

       private String getPortSpeed() {  return " ";  }

       private int getPortMode() {  return 0x001;  }