
Programming Supplement
Supplements Index
March 2002
Java Platform Overview |
Getting Started |
Step-by-Step Programming
Learning Paths |
References & Resources |
Certification
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 Java Programming Center.
CONTENTS
1. Java Programming Language Basics
Casting
2. Making Sense of the Java Class Libraries
Collection, Iterator and List Interfaces
3. Program Challenge
Casting Application
4. Java Bits
Good Programming Practices
5. New to the Programming Center
Building an Application Quiz
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 the Casting Application
Java Programming Language Basics
Casting
Casting is the process of taking a variable declared as one data type and telling the compiler that you want to treat it as another. Casting does not change the original item. It just tells the compiler to treat it differently. Casting can be done with both primitive types like int and float, as well as with object types like java.lang.Object and java.lang.String.
The general form of the casting operation is as follows:
(datatype)expression
where "data type" is the new type for how you want to treat the value of the expression.
In the case of primitive data, casting is necessary when going between data types and there is a chance of losing information. For instance, if you have an int and want to treat it as a double, no casting is necessary because a double can hold the full range of values available to an int. In the following operations, no casting is necessary. The value of i is promoted to the type of d.
int i = 5;
double d = i;
Going in the reverse direction requires casting. Because a double variable can hold data with values beyond the decimal point, an int can't hold all the values of a double. The range of possible numbers is also greater for a double than an int. Because of these two specific problems, trying to go from a double to an int requires casting:
double d = 5.0;
int i = (int)d;
The use of the (int) here says "Yeah, I know this can lose information, but I really do want to treat the double variable as an int."
With objects, casting is sometimes also necessary. Casting with object references says to treat the variable declared to be of type X to be of type Y. It is important to know that when casting an object reference, the data type of the object does not change, only how the compiler treats the object.
Frequently, methods are declared to be generic, possibly accepting (or returning) an Object type. It then becomes necessary to access the variable as its specific type. That is when casting is necessary. If you know a parameter is supposed to be a specific type, you can just cast, as in the following example:
public void myMethod(Object param) {
Number num = (Number)param;
double d = num.doubleValue();
System.out.println("Value is: " + d);
}
|
If however you don't know the specific type, you can use the instanceof keyword. This allows you to check the type first, before casting.
public void myMethod(Object param) {
if (param instanceof Number) {
Number num = (Number)param;
double d = num.doubleValue();
System.out.println("Value is: " + d);
} else {
logError(param);
}
}
|
If you don't use the instanceof keyword to check the type and try to perform a cast between incompatible types, then a ClassCastException is thrown at runtime. This is shown in the following example code fragment:
// Create object
Object o = new Object();
// The cast
String s = (String)o;
// The object s refers to is not really a String
// so a ClassCastException is thrown
System.out.println(s.length());
|
The statement would be valid if the object referenced by the variable o were a String, as in this code fragment:
// Create object
Object o = "Hello";
// The cast
String s = (String)o;
// The object s refers to really is a String
// so no ClassCastException is thrown
System.out.println(s.length());
|
Making Sense of the Java Class Libraries
Collection, Iterator, and List Interfaces
The Collections Framework provides a set of interfaces and classes for storing and manipulating groups of data as a single unit, or a collection. A collection is an object that represents a group of objects. Specific interfaces describe the different types of groups, such as sets, lists and maps.
You have used some collection objects in past issues of the supplement such as arrays and ArrayList. See For More Information below to review past issues.
The Collection interface is used to represent any group of objects, or elements. You use this interface when you want to work with a group of elements in as general a manner as possible.
This interface has two methods you should understand:
add(Object obj)
Adds an object to the collection. The add method returns true if adding the object changed the collection and false if the collection is unchanged.
Iterator iterator
Returns an object that implements the Iterator interface.
Iterator interface methods allow you to step through each element in a collection from start to finish. You can use an iterator to retrieve or to remove objects in a collection one by one. The three methods of Iterator interface methods you can use are:
hasNext
Returns true if the iteration has more elements. Returns true if next returns an element rather than throwing an exception.
next
Returns the next element in the iteration. Throws NoSuchElementException if iteration has no more elements.
remove
Removes the last element returned by the iterator. This method can be called only once per call to next.
The List interface extends the Collection interface to define an ordered collection, a sequence of elements, allowing duplicates. The interface adds position-oriented operations, as well as the ability to work with just a part of the list. This interface gives you control over where each element is inserted, and you can access elements by their integer index position in the list, and search for elements in the list.
Some of the List interface methods are detailed below:
add(int index, Object element)
Inserts the specified element at the specified position in this list (optional operation).
add(Object o)
Appends the specified element to the end of this list (optional operation).
clear()
Removes all of the elements from this list (optional operation).
get(int index)
Returns the element at the specified position in this list.
The following application demonstrates the concepts above:
// The Collection, List, and Iterator interfaces are a
// part of the java.util package.
import java.util.*;
public class CreatingCollections
{
public static void main(String args[])
{
// Creates a collection object
List list = new ArrayList();
// Uses the add method to add
// each element
list.add("This is a String");
list.add(new Short((short)12));
list.add(new Integer(35));
// Get an iterator for the input list
// and step through each element within the
// for statement.
for (Iterator i = list.iterator(); i.hasNext(); )
{
System.out.print(i.next());
}
}
}
|
Results in:
This is a String1235
Program Challenge
Casting Application
- Create a program that takes a
List of objects as input.
- Make half of the objects strings.
- Make half of the objects numbers.
- Add another element that is neither a
String nor a number.
- Iterate through the elements.
- Concatenate the strings.
- Sum the numbers.
- Ignore the rest.
- Use
instanceof to determine what type each element is.
- Cast the element to the appropriate type before you access the data.
- Output the concatenated strings.
- Output the sum of the numbers.
Java Bits
Good Programming Practices
Writing code that compiles and runs is only a part of software development. You also need to debug applications, add to them, make changes, and share parts of the code. In other words, your code must be written legibly so it is easy to understand and is consistent.
You can do this by following these good programming practices:
-
Comment completely but not excessively.
Don't explain the obvious, but do explain the purpose of complex methods. This is helpful to other developers and to yourself if much time has passed since you wrote the code.
For example:
// Creates a new entry in the jiveForum database
// table and inserts the forum object into memory
// cache for future fast access:
try {
Forum newForum = factory.createForum(
"New Forum Name",
"Some description for new forum.");
}
|
-
Create meaningful method and parameter names.
Meaningful method names describe the functionality of a method, and help prevent the need for long comments.
For instance:
public void getLastVisited(request,response){}
-
Keep methods as short as possible. A method requiring many parameters may be doing more than it should. Consider breaking such methods into several methods that perform several tasks.
For instance:
private void buildImagePanel()
{ // Opens method
images = new JPanel();
// Sets the color, layout, and adds the
// seahorse object
images.setLayout(new FlowLayout() );
images.setBackground(Color.white);
images.add(seahorse);
} // Closes method
|
-
Indent the statements in the body of control statements.
This makes is easier to follow what each control statement is doing, and makes it easy to locate the next.
For instance:
if (!str1.equals(str2)) {
System.out.println("str1/str2 mismatch");
}
You'll see more good programming practices in future issues of the supplement.
New to the Programming Center
Test what you learned from the Building an Application tutorial series parts 1 and 2 about basic Java programming fundamentals.
For More Information
Creating an Array (July '01)
Classes File and BufferedReader (February '02)
The ArrayList Class Explained (August '01)
Numbers
Java Collections: Chapter 9, Lists
Introduction to the Collections Framework
The Collections Framework
Trail: Collections
Conversions and Promotions
Java 2 Platform, Standard Edition Product Family
J2SE, version 1.4 Summary of New Features and Enhancements
New to Java Programming Center
Building an Application Introduction
Program Challenge Solution
This is one possible solution to the Program Challenge Casting Application:
import java.util.*;
public class Cast {
public static void main(String args[]) {
// Configure the "input"
List list = new ArrayList();
list.add("The ");
list.add(new Integer(35));
list.add("quick ");
list.add(new Double(Math.PI));
list.add("brown ");
list.add(new java.awt.Point(1, 2));
list.add("fox ");
list.add(new Float(89.124f));
list.add("jumps ");
list.add("over ");
list.add(new Short((short)14));
list.add("the ");
list.add(new Byte((byte)12));
list.add("lazy ");
list.add("sleeping ");
list.add(new Long(9012));
list.add("dog.");
// Get an iterator for the input list
Iterator it = list.iterator();
// Create a StringBuffer to store
// the concatenated elements
StringBuffer sb = new StringBuffer();
// Initialize a variable to store the sum
double sum = 0;
// Loop through the list using the iterator
while(it.hasNext()) {
// Get the next element
Object next = it.next();
// Check for type
if (next instanceof Number) {
// Sum up the numbers.
Number num = (Number)next;
sum += num.doubleValue();
} else if (next instanceof String) {
// Combine the strings
sb.append((String)next);
} else {
// ignore
}
}
// Display the results
System.out.println("Sentence: " + sb.toString());
System.out.println("Sum: " + sum);
}
}
|
Downloading the Java 2 Platform
For most Java development, you need the class libraries, compiler, tools, and runtime environment provided with the Java 2, Standard Edition (J2SE) development kit.
IMPORTANT: Please read our Terms of Use and Privacy policies:
Copyright 2002 Sun Microsystems, Inc. All rights reserved.
901 San Antonio Road, Palo Alto, California 94303 USA
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.
- Feedback -
Comments? Send your feedback on the New to Java Programming
Center Supplement to: dana.nourie@sun.com
- Subscribe/Unsubscribe -
To subscribe, go to the subscriptions page, choose the newsletters you want to subscribe to and click
Update
To unsubscribe, go to the subscriptions page,
uncheck the appropriate check box, and click Update
This document is protected by copyright.
JDC New-to-Java Programming Center Supplement
March 2002
Sun, Sun Microsystems, Java and J2SE are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.
|