Break up a string literal over multiple lines

13,585

Break up the string on the new line using + operator works.

public String toString() {
    return String.format("BankAccount[owner: %s, balance: "
            + "%2$.2f, interest rate:"
            + " %3$.2f]", 
            myCustomerName, 
            myAccountBalance, myIntrestRate);
}

Sample Output: BankAccount[owner: TestUser, balance: 100.57, interest rate: 12.50]

Share:
13,585
ProFesh
Author by

ProFesh

Coding enthusist

Updated on June 22, 2022

Comments

  • ProFesh
    ProFesh almost 2 years

    Is there a way to break up a line of code so that it is read as continuous despite being on a new line in java?

    public String toString() {
    
      return String.format("BankAccount[owner: %s, balance: %2$.2f,\
        interest rate: %3$.2f,", myCustomerName, myAccountBalance, myIntrestRate);
      }
    

    The code above when I do this all on one line everything works dandy but when I try to do this on multiple lines it doesn't work.

    In python I know you use a \ to start typing on a new line but print as one line when executed.

    A Example in Python to clarify. In python this will print on one line using a backslash or ():

    print('Oh, youre sure to do that, said the Cat,\
     if you only walk long enough.')
    

    the User would see this as:

    Oh, youre sure to do that, said the Cat, if you only walk long enough.
    

    Is there similar ways to do this in java?? Thank you!