![]() 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
Using
3. Making Sense of the Java Class Libraries
The
4. Java Bits Java Programming Shortcuts
5. New to the New to Java Programming Center Keywords Crossword Puzzle 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 BasicsHow to use
|
for (initialization; ending condition; update) {
statement1;
statement2;
statement3;
...
statementn;
}
|
for loop, and are
useful for the loop control variable.
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.
StringBuffer as the holder of the list.
Be sure there is no comma after the last element.
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.
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()
StringBuffer(int length)
StringBuffer(String str)
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.
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:
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;
To create a Timestamp object that returns the
current time can take three steps:
Date objectDate d = new Date();
getTime method on that object and
assign it to a Timestamp reference
Timestamp ts = (d.getTime());
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());
}
}
|
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.
Creating Strings and StringBuffers
Question of the Week: String versus StringBuffer
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());
}
}
|
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.
|
| ||||||||||||