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

Java Technology Fundamentals Newsletter

 

New-to-Java Programming Center
Technology Fundamentals

Welcome to the Java Developer Connection Java Technology Fundamentals Newsletter.

This monthly newsletter 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

Defining Static or Instance Variables and Methods

2. Making Sense of the Java Class Libraries

Class Character

3. Program Challenge

Application Examine

4. Java Bits

Storing Information

5. New to the Programming Center

Unraveling Java Technology

6. For More Information

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

Java Programming Language Basics

Defining Static or Instance Variables and Methods

Class definitions begin with a basic structure of what a class extends and which interfaces are implemented. That's the basic framework. The interesting stuff happens beyond these basics.

Classes consist of variables and methods. Variables hold the state of the class and methods define the behavior. For instance, if you want to define a class that maintains a counter, you might define a class as such:

public class Counter {
   int count;
   void incrementCount() {
     count++;
   }
   int getCount() {
     return count;
   }
}

Here, there is one piece of state information, the count variable, and two pieces of behavior, the two methods. The variable is named count and has type int. The methods incrementCount and getCount increment the counter and the latter returns the current value.

The code defines the type of state and behavior information available for a class. In the definition of the Counter class, the count variable and associated methods are called instance methods. That means for each instance of the class, a separate value for the state information is maintained.

To demonstrate, the following code fragment creates two instances of the Counter class and increments each counter a few times. Notice that each count is maintained separately:

Counter counter1 = new Counter();
counter1.incrementCount();
counter1.incrementCount();
counter1.incrementCount();


Counter counter2 = new Counter();
counter2.incrementCount();
counter2.incrementCount();
// Prints "1: 3"
System.out.println("1: " + counter1.getCount());
// Prints "2: 2"
System.out.println("2: " + counter2.getCount());

The second state is class variables, and second behavior is class methods. With these types of variables, one copy of the variable exists for all instances of the class. For class methods, they can only access class variables.

The following class definition shows a counter maintained as a static value.

public class ClassCounter {
   static int count;
   static void incrementCount() {
     count++;
   }
   static int getCount() {
     return count;
   }
}

If you create multiple instances of the ClassCounter class defined and called incrementCount(), each instance updates the same class variable count, not the individual instance counts.

The following fragment demonstrates this updating:

ClassCounter counter1 = new ClassCounter();
counter1.incrementCount();
counter1.incrementCount();
counter1.incrementCount();
ClassCounter counter2 = new ClassCounter();
counter2.incrementCount();
counter2.incrementCount();
// Prints "1: 5"
System.out.println("1: " + counter1.getCount());
// Prints "2: 5"
System.out.println("2: " + counter2.getCount());

Why might you use class, or static, variables instead of instance variables? The key reason for using static data members is to maintain a value across all instances of a class.

For instance, one key reason to use them is for constants.

static final int LENGTH = 4;

By using the static and final keywords together, you've defined a class-level constant that can be used throughout the class definition. By defining constants, the compiler can perform certain optimizations and you can more clearly document your code, assuming proper variable names.

The use of static methods can be confusing at times. Since static methods work at the class level, they should be called with the class identifier, not with an instance of the class. A better way to write the earlier usage counter example is as follows:

ClassCounter counter1 = new ClassCounter();
ClassCounter.incrementCount();
ClassCounter.incrementCount();
ClassCounter.incrementCount();
ClassCounter counter2 = new ClassCounter();
ClassCounter.incrementCount();
ClassCounter.incrementCount();
// Prints "1: 5"
System.out.println("1: " + counter1.getCount());
// Prints "2: 5"
System.out.println("2: " + counter2.getCount());
// Prints "5"
System.out.println(ClassCounter.getCount());

By replacing the instance names with the class name you more clearly see why the results print out as they do. A third print statement is added to show the proper way of getting the count. True, you don't need to use the class name when calling static methods. However, there are times where certain method calls can be confusing without it.

For instance, what's the answer to the following statement?

System.out.println("12345".valueOf(54321));

Since "12345" is a String, you can call any String method on that string. Since valueOf is a static method, the actual value of the calling String is ignored, and the method just works on the argument. In this particular case, that means returning the quoted string of "54321", not the "12345" value.

When defining your own classes, examine the purpose of state and behavior information and use the static keyword when necessary.

Test your knowledge about static and instance variables and methods with this online quiz.

Making Sense of the Java Class Libraries

Class Character

The Character class is a wrapper class that wraps a value of a primitive type char in an object. In other words, it allows you to work with a primitive type as though it were an object. An object of type Character contains a single parameter of type char.

In addition, this class provides several methods for determining a character's category: lowercase letter, digit, and so forth for converting characters from uppercase to lowercase and vice versa.

Character information is based on the Unicode Standard, version 3.0.

The methods and data of class Character are defined by the information in the UnicodeData file that is part of the Unicode Character Database maintained by the Unicode Consortium. This file specifies various properties including name and general category for every defined Unicode code point or character range.

Class Character has many useful methods for checking the status of a char passed in:

  • isDefined(char ch)
    Determines if a character is defined in Unicode.
  • isLetter(char ch)
    Determines if the specified character is a letter.
  • isLetterOrDigit(char ch)
    Determines if the specified character is a letter or digit.
  • isWhitespace(char ch)
    Determines if the specified character is white space.

In addition, the Character class has many useful static fields you can use:

  • COMBINING_SPACING_MARK
    General category Mc in the Unicode specification.
  • CONTROL
    General category Cc in the Unicode specification.
  • CURRENCY_SYMBOL
    General category Sc in the Unicode specification.
  • LINE_SEPARATOR
    General category Zl in the Unicode specification.
  • LOWERCASE_LETTER
    General category Ll in the Unicode specification.

Read the class documentation for more methods and fields.

The following sample application demonstrates a few of the Character class methods:

public class Charactertest {
   public static void main(String args[]) {
     char letter = 'd';
     boolean lowerCase = Character.isLowerCase(letter);
     boolean upperCase = Character.isUpperCase(letter);
     boolean letterOrdigit = Character.isLetter(letter);
     System.out.println("Is this letter lowercase? " + lowerCase);
     System.out.println("Is this letter uppercase? " + upperCase);
     System.out.println("Is this a letter? " + letterOrdigit);
   }
}

Results in the following:

%java Charactertest
Is this letter lowercase? true
Is this letter uppercase? false
Is this a letter? true

This class is useful for verifying data before writing to files or databases, and has many other applications.

Program Challenge

Create a program that examines each character from a command line argument.

  • Use the static methods of class Character to report on the type of each character.

  • Check if each character is a digit, letter, or white space.

  • Report the specific type.

The result of your application should produce something similar to the following:

	%java Examine word
	Char: w
	        isDigit:        false
	        isLetter:       true
	        isWhitespace:   false
	        Type:           Lowercase Letter
	Char: o
	        isDigit:        false
	        isLetter:       true
	        isWhitespace:   false
	        Type:           Lowercase Letter
	Char: r
	        isDigit:        false
	        isLetter:       true
	        isWhitespace:   false
	        Type:           Lowercase Letter
	Char: d
	        isDigit:        false
	        isLetter:       true
	        isWhitespace:   false
	        Type:           Lowercase Letter

See a possible solution to Challenge.

Java Bits

Storing Information

Most applications store information created or configured by the user. The Java platform provides convenient packages that enable an application to write or store data, then read the information back into the application.

  • Java I/O (java.io and java.nio)

The classes in the java.io and java.nio packages allow you to create objects for sending and receiving by using objects called streams. In addition, the java.io and java.nio classes have methods for reading and writing data.

The classes you need to store data and objects on a file system come in the Java 2 Platform, Standard Edition J2SE download.

You can also write data or objects to a database. To do this you need to understand the JDBC technology, an API that provides a framework for accessing any data source using the Java programming language. The java.sql package provides the classes and interfaces for accessing and processing data stored in a data source (usually a relational database) using the Java programming language.

To store information in and retrieve from a database, you need the J2SE download, which includes the java.sql and java.io packages, and a database such as Cloudscape, MySQL, Oracle, or PointBase.

New to Java Programming Center

Unraveling Java Technology, an article that defines many Java acronyms and frequently used terminology, has been updated. http://java.sun.com/jdc/onlineTraining/new2java/programming/learn/unravelingjava.html

Building an Application Introduction
http://java.sun.com/jdc/onlineTraining/new2java/divelog/

For More Information

Understanding Instance and Class Members

Global variables

Calling Java Methods

Variable Assignments

Characters and Strings

20.5 The Class java.lang.Character

Class Character

Tech Tips (January 2001)

JDBC 2.0 Fundamentals

Duke's Bakery, Part 1

The Unicode Consortium

Program Challenge Solution

See one possible solution to the May Program Challenge.
http://java.sun.com/jdc/onlineTraining/new2java/supplements/solutions/May02.html

Downloading the Java 2 Platform

For most Java development, you need the class libraries, compiler, tools, and runtime environment provided with the 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

FEEDBACK

Tell us what you think of this supplement.

Duke

 Very worth reading  Worth reading  Not worth reading

If you have other comments or ideas for future technical content, please type them here:

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.

- 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.

New to Java Programming Center Supplement
May 2002

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