Practice Program

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   go to next page        

Do you think that the following is correct?

str1.length() = 12 ;  // change the length of str1

Answer:

No. The left side of an assignment statement must be a variable.

Practice Program

It has been a long time since you have had some blanks to fill in. I'm sure that you have missed them. Here is a program that will:

  1. Create two String objects
  2. The first String will hold the characters "Green eggs"
  3. The second String will hold the characters " and ham"
  4. The program will compute the length of each string, and then
  5. Write out the the sum of the individual lengths
class StringTester
{

  public static void main ( String[] args )
  {
    String str1;   // a reference to a String object.
    String str2;   // a reference to a second String object.

    int len1, len2;    // the length of str1 and the length of str2

    str1  =  ; // create the first String

    str2  =  ; // create the second String

    len1  = str1.length();    // get the length of the first string

    len2  =  . ;    // get the length of the second string

    System.out.println("The combined length of both strings is " +
         + " characters" );
  }
}

QUESTION 16:

Fill in the blanks of the program.