Using Several Lines per Statement

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

Yes.

Using Several Lines per Statement

You can use several lines for a statement. Anywhere a space character is OK you can split a statement. This means you can't split a statement in the middle of a name, nor between the quote marks of a string literal, nor in the middle of a numeric literal. Here is the program with some statements correctly put on two lines:

class Example
{
  public static void main ( String[] args )
  {
    long   hoursWorked = 40;    
    double payRate = 10.0, 
           taxRate = 0.10;    

    System.out.println("Hours Worked: " + 
hoursWorked );
    System.out.println("pay Amount  : " 
+ (hoursWorked * payRate) );
    System.out.println("tax Amount  : " + (hoursWorked 
* payRate * taxRate) );
  }
}

Although correct, the division of statements is confusing to humans. It is also true that anywhere one space is OK any number of spaces are OK. Here is a better style for the program:

class Example
{
  public static void main ( String[] args )
  {
    long   hoursWorked = 40;    
    double payRate = 10.0, 
           taxRate = 0.10;    

    System.out.println("Hours Worked: " + 
        hoursWorked );
    System.out.println("pay Amount  : " +
       (hoursWorked * payRate) );
    System.out.println("tax Amount  : " + 
       (hoursWorked * payRate * taxRate) );
  }
}

It is a good idea to indent the second half of a split statement further than the start of the statement.

QUESTION 9:

Is the following correct?

cla
   ss Example
{

  public static void main ( String[] args )
  {
    long   hoursWorked = 40;    
    double payRate = 10.0, taxRate = 0.10;    

    System.out.println("Hours 
        Worked: " + hoursWorked );

    System.out.println("pay Amount  : " + (hours
        Worked * payRate) );

    System.out.println("tax Amount  : " + (
        hoursWorked * payRate * taxRate) );
  }
}