Sun Java Solaris Communities My SDN Account Join SDN
 
Java Technology Fundamentals Newsletter Index

New-to-Java Programming Center Supplement

 

New-to-Java Programming Center
Programming Center Supplement

Welcome to the Java Developer ConnectionSM New to Java Programming Center Supplement!

This monthly supplement provides a way for you to learn the basics of the Java programming language, discover new resources, and keep up-to-date on the latest additions to the JDC's New to JavaTM Programming Center.

CONTENTS

1. Java Programming Language Basics

How to Use for Loops

2. Program Challenge

Using for Loops

3. Making Sense of the Java Class Libraries

The StringBuffer Class

4. Java Bits

Java Programming Shortcuts

5. New to the New to Java Programming Center

Keywords Crossword Puzzle

6. For More Information

Links to articles, Tech Tips, trails, and tutorials that provide more information on the topics discussed here.

7. Program Challenge Solution and Explanation

Possible Solution to Using for Loops

Java Programming Language Basics

How to use for loops

The Java programming language has three different looping constructs:

  • for loop
  • while loop
  • do-while loop

Each of these constructs repeatedly executes a block of code, until some condition is met. This article explains the structure of one of those constructs: the for loop.

The basic structure of a for loop consists of four parts:

  • Initialization section
  • Ending condition section
  • Update section
  • Loop body

This structure looks like the following:

for (initialization; ending condition; update) body;

Following the for keyword, the first three sections go in parenthesis, each section separated by a semicolon. The body is the part that repeatedly executes. It follows outside the parenthesis.

If you don't want any code to execute, besides the three internal sections, follow the closing parenthises with a semicolon. This is a common programming error, as it means there is no body to execute.

for (initialization; ending condition; update);
System.out.println("Executes after for loop is done.");

More commonly though, you enclose the body within curly braces { and } indicating multiple statements to execute.

If the body is not within curly braces, then only the statement immediately following the for loop construct is executed in each pass.

Here's what you see more commonly:

for (initialization; ending condition; update) {
   statement1;
   statement2;
   statement3;
   ...
   statementn;
}

  • The initialization section is the statement you want to run before the loop starts. Variables declared in the initialization section are local to the for loop, and are useful for the loop control variable.
  • The ending condition section holds the boolean expression checked to see if the body of the loop should execute if the condition is true.
  • The update section is the statement to run after the body but before the ending condition expression is checked for the next pass through the loop.

To demonstrate, the following loop sums the numbers from 1 to 3.

int sum = 0;
for (int i=1; i<=3; i++)
   sum += i;
System.out.println("The sum is " + sum);

The first line (int sum = 0;) declares a variable to hold the sum to be calculated. It needs to be declared outside the for loop block so you can print out the value when the for loop is done.

The next line for (int i=1; i<;=3; i++) is a little more complicated. First, the initialization section declares the variable i and sets it to the value 1.

The ending condition i<=3 runs the body of the for loop while the value i is less than or equal to 3. Originally if i were greater than 3, the loop body would never execute. Since i starts less then 3, it executes at least once.

Finally, the update section i++ says to increase the value of i by one after each execution of the loop body. The following line sum += i; is the loop body. It executes while the ending condition remains true.

The last line System.out.println("The sum is " + sum); is outside the for loop and executes when the loop is done. The whole loop code fragment executes as follows:

sum = 0;
int i = 1;
is i<=3?  1 is less then or equal
    to 3 so yes, okay to execute body
sum = sum + 1;
i++;  i is now 2
is i<=3?  2 is less then or equal
    to 3 so yes, okay to execute body
sum = sum + 2;
i++;  i is now 3
is i<=3?  3 is less then or equal
    to 3 so yes, okay to execute body
sum = sum + 3;
i++;  i is now 4
is i<=3?  4 is not less then or equal
        to 3 so no, stop the for loop
System.out.println("The sum is " +
       sum);  prints out The sum is 6

That's essentially it for the for loop. There are definitely more complicated things you can do with a for loop, but this framework will get you started.

Program Challenge

  1. Create a program that loops through all the command-line arguments to create a comma-delimited list.
  2. Use a StringBuffer as the holder of the list. Be sure there is no comma after the last element.
  3. Print out the list after all the arguments are combined.

When run with this sample command line:

java Append one two three

The results should be:

one, two, three

Answer to this challenge is at the end of this issue.

Making Sense of the Java Class Libraries

The StringBuffer class

Two common classes used to create and manipulate string objects are:

String -- creates objects that are constant and fixed in length. Once a String object is created, it can not be changed.

StringBuffer -- creates a StringBuffer object that is writable. Once a StringBuffer object is created, it can be changed.

So why not always use the StringBuffer class instead of String? Performance. Many references can refer to one String object, and because this object memory size is fixed, this is better on performance.

StringBuffer, on the other hand, can expand if its size or capacity is exceeded. Use StringBuffer when you need to add, delete, or replace substrings in a string. In these situations, using StringBuffer is more efficient.

To create a StringBuffer object, use the keyword new and call any of the available three constructors:

  • StringBuffer()
    Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
  • StringBuffer(int length)
    Constructs a string buffer with no characters in it and an initial capacity specified by the length argument.
  • StringBuffer(String str)
    Constructs a string buffer that represents the same sequence of characters as the string argument.

Methods from the StringBuffer class are used to manipulate the string, to add to, delete from, or insert text into the string.

For example:

public class UsingStringBuffers
{

public static void main(String [] args)
  {
  
    // Creates a StringBuffer object
    // with the third
    // constructor mentioned above.
    
    StringBuffer buf =
      new StringBuffer("Java technologies");

    // The append method adds text at the
    // end of the buffer.
    // Prints result to screen.
    
    buf.append(" are used on desktops and
                            the Internet.");
    System.out.println(buf);
    
    // Prints buf capacity and its actual
    // length, using
    // the length and capacity methods.
    
    System.out.println("This string is " +
                              buf.length() + 
    " in length.");
    
    System.out.println(
      "But the actual capacity of this
              buffer is " + buf.capacity());
 
    }
}

Results in:

Java technologies are used on desktops and the Internet. This string is 56 in length. But the actual capacity of this buffer is 68

You can change the length and capacity of a StringBuffer, and this class has other useful editing methods such as, insert, setCharAt, substring, and more.

Java Bits:

Java Programming Shortcuts

Example code is one of the most useful tools for learning the Java programming language, but it can also be confusing.

The Java programming language is a strictly typed language, meaning you always have to declare variables as a specific type, such as int, String, or JPanel. But that doesn't mean that there isn't some flexibility in the way your write your statements.

Shortcuts in programming are useful, but trying to understand them without explanation can be confusing.

Here are two common shortcuts you see in code and can use in your own development:

  • Variable Declarations

Variables must be declared with a type, but you can put variables of the same type in the same statement, separated by commas:

Instead of this:

int month;
int day;
int year;

Try this:

int month, day, year;

Some developers might prefer:

int month,
      day,
     year;
  • Creating Objects and Calling Methods

To create a Timestamp object that returns the current time can take three steps:

  1. Insantiate a Date object
    Date d = new Date();
  2. Call the getTime method on that object and assign it to a Timestamp reference Timestamp ts = (d.getTime());
  3. Return the time as a Timestamp return ts;

Instead you can create an object and call one of its methods in one step:

return new Timestamp(new Date().getTime());

Here it is in an example application you can run:

import java.sql.Timestamp;
import java.util.Date;

public class TimeTest
{ 
  // Method that returns a Timestamp
  // object.
  public static Timestamp getCurrentTime()
   { 
    // Instantiates a Date object and calls
    // the getTime method, and creates and
    // returns the Timestamp object with the
    // current time. In one line!
    return new Timestamp(new Date().getTime());
   }
    //The main method that calls the
    // getCurrentTime method and returns
    // the Timestamp object and prints
    // to screen
  public static void main(String[] args)
   {
   System.out.println(getCurrentTime());
   }
}

New to the New to Java Programming Center

Keywords Crossword Puzzle

Test your knowledge of Java keywords with this new online crossword puzzle applet.

To fill the puzzle, click where you want to insert letters, using the space bar to toggle between Across or Down, then type.

Troubleshooting Guide
Having troubles compiling or running the Dive Log application? Read this helpful addition to Building an Application, Part 1.

For More Information

The for Statement

Iterative Execution

Class StringBuffer

Creating Strings and StringBuffers

Modifying StringBuffers

Question of the Week: String versus StringBuffer

Tech Tips: January 20, 1998

Program Challenge Solution

This is one possible solution to the Program Challenge:

public class Append {
   public static void main(String args[]) {
     // Create a StringBuffer object and 
     // assign it to the variable buf.
     
     StringBuffer buf = new StringBuffer();
     
     // Initializes the for loop.
     // Checks for the number of arguments on 
     // the command line, then loops through them
     
     for (int i=0; i< args.length; i++) {
     
     // For each argument besides the first, 
     // append comma to end of buffer
     
       if (i != 0) {
         buf.append(", ");
       }
       
       // Add all arguments to the
       // StringBuffer object buf.
       
       buf.append(args[i]);
     }
     // Converts the StringBuffer arguments
     // to simple strings and prints to screen.
     
     System.out.println(buf.toString());
   }
}

Downloading the Java 2 Platform

For most Java development, you need the class libraries, compiler, tools, and run-time environment provided with the Java 2, Standard Edition development kit.

IMPORTANT: Please read our Terms of Use and Privacy policies:

Have a question about programming? Use Java Online Support.

- Note -

Sun respects your online time and privacy. The Java Developer Connection mailing lists are used for internal Sun Microsystems purposes only. You have received this email because you elected to subscribe.

- Unsubscribe -

To unsubscribe to this newsletter, go to the subscriptions page uncheck the "JDC New-to-Java Supplement" checkbox, and click "Update".

- Subscribe -

To subscribe to other JDC mailings, go to the subscriptions page choose the newsletters you want to subscribe, and click "Update".

- Feedback -

Comments? Send your feedback on the JDC Newsletter to: jdc-webmaster

- Copyright -

Copyright 2001 Sun Microsystems, Inc. All rights reserved.
901 San Antonio Road, Palo Alto, California 94303 USA

This document is protected by copyright.

JDC New-to-Java Programming Center Supplement
November 2001

Sun, Sun Microsystems, Java, and J2SE are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.


1 As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform. -->