Split string literal into multiple lines

Is there a way to split a line of code so that it reads as continuous even though it was 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 it all on one line, everything works dandy, but when I try to do it on multiple lines, it doesn't work.

In python, I know that you are using \ to start printing on a new line, but printing as one line when executed.

An example in Python for clarification. 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 will see this as:

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

      

Are there any similar ways to do this in java? Thank!

+6


source to share


2 answers


Split a line on a new line using an operator +

.

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

      



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

+7


source


The following Java coding conventions:

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

      

Always have the concatenation operator at the start of a new line for readability.



https://www.oracle.com/technetwork/java/javase/documentation/codeconventions-136091.html#248

Hope this helps!

Brady

0


source







All Articles