Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break up a string literal over multiple lines

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!

like image 282
ProFesh Avatar asked Apr 20 '17 00:04

ProFesh


People also ask

How do I split a string over multiple lines?

You can have a string split across multiple lines by enclosing it in triple quotes. Alternatively, brackets can also be used to spread a string into different lines. Moreover, backslash works as a line continuation character in Python. You can use it to join text on separate lines and create a multiline string.

How do you break a string literal?

Another way of splitting a string literal is to set the caret where you want to split the string, press Alt+Enter and choose Split string. This context action will also add necessary quotation marks and + , but both parts of the string will stay on the same line.

Is it possible to line break a string in JavaScript across several lines?

By using template literals, you can have a string divided across many lines. Alternatively, the + and \ operators can be used to divide a string into multiple lines. Multi-line strings in javascript were not allowed by 2015 until ES6 introduced string literals. In ES6, template literals were introduced.

How do you insert a line break in template literal?

New Line Using Template Literals : For creating a new line in the console, you can also insert a new line break by pressing Enter while using the template literals.


1 Answers

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]

like image 153
Devendra Lattu Avatar answered Sep 22 '22 00:09

Devendra Lattu