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

    if/else and switch statements

2. Making Sense of the Java Class Libraries

    The String class

3. Program Challenges

    A case of Strings

4. Java Bits

    The two types

5. New to Java Technology Forum Latest

    GUI Bulletin Board Question

6. New to the Center

    Crossword Puzzle #2

7. For More Information

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

8. Program Challenge Solution and Explanation

    A case of Strings

Java Programming Language Basics

if/else and switch statements

Some applications execute one command after another in a linear fashion. For instance, add a number with another number and print the result. More frequently, commands are executed based on certain conditions, or depending on actions initiated by the user or another part of the application. For the latter, conditional statements are used.

Conditional statements like if/else are commonly used to control the flow of execution in an application. Conditional statements check if a condition is true or false.

For instance, if the condition is true, then add the integers passed in. If the condition is false, then the program doesn't do anything if an else is not specified.

If statements are written similarly as follows:

if (condition is true) //Note the parentheses

do something here like printing to the screen;

You may want something specific to happen for else:

if (condition is true)
  {
  do something here;
  print this statement to the screen;
  }
  else
  {
  do something different;
  print this other statement to the screen;
  }

Notice complex statement blocks (more than one statement for each if or else) require the use of {}. Curly braces help code readability as well as letting the compiler know when it has completed a block. You don't have to use an else statement if you don't need the application to do something specific, like print an error message, if the condition is false.

If/else statements are sufficient for many situations in which flow control is needed. When there are a variety of actions an application can take, however, numerous if statements get long and tedious, such as when there are many buttons that can be clicked, or a menu with a list of options a user can choose.

To cover multiple possible choices, the switch statement, also known as a case statement, is used. Start a switch statement with a variable of type int, byte, short, long, or char, then pass it to switch.

For example, int is assigned a value of 2 in the variable menuItem. The variable menuItem is then passed into the switch statement:

int menuItem = 2;
switch (menuItem)

// Next create the choices and
// enclose them in curly braces.
{
  case 0:
    System.out.println("You chose 0!");
    break; // Jumps to the next case
           // when break is reached.
  case 1:
    System.out.println("You chose 1!");
    break;
  case 2:
    System.out.println("You chose 2!");
    break;
  case 3:
    System.out.println("You chose 3!");
    break;
  default:
    System.out.prinln("Oops,
                some error occurred!");
}

The result prints "You chose 2!"

In this example menuItem already has a value, but you can get the value from the command line or from a GUI component, such as buttons or menus. If none of the case labels match, then default is executed.

In the example above, only the case that is chosen through the variable is executed, then break forces the application flow go to the next case block. If you need the application to go through each case, omit the break:

char grade = 'B';
switch (grade)
{
  case 'A': 
  case 'B':
    System.out.println("Good work!"); 
    break;
  case 'C': 
  case 'D':
    System.out.println(
         "You need to study more!"); 
     break;
  default:
    System.out.println(
           "Big problems!");
}

Enter either A or B, and Good work, prints to the console.

Making Sense of the Java Class Libraries

The String class explained:

A string is a group characters strung together. You've seen strings in the examples above, but they are more accurately called objects of the String class.

The String class allows String objects to be created without having to use the keyword new. You can create String objects in two ways:

String example = "This is a string.";
String example = new String("This is a string.");

The String class provides programmers with a variety ways of to manipulate and work with strings:

  • Concatenate or join strings:
    //Variables declaring a String type with a string included
    String title1 = "Java";
    String title2 = "Developer Connection";
    //  The + symbol joins the variables,
    //  and a space is inserted
    //  between the quotes to be included
    //  between the two variables.
    String fulltitle = title1 + 
          " " title2; //Joins the Strings.
    System.out.println(fulltitle);
    

    Results in:
    Java Developer Connection
    
  • The length method returns the length of a String object. In other words, how many characters, including spaces, the String contains:
    // Variable declaring a String object,
    // with a string argument
    String title = "Java Developer Connection";
    System.out.println("Length of title is " +
                                title.length());
    

    Results in:
    Length of title is 25
    

The String class provides many other useful methods:

  • replace, which allows replacement of specific characters.
  • equals, which returns true if a String object has the same sequence of characters as another String object
  • charAt, which returns the character at a specified index

String methods are easily called by using the dot operator with the String object variable name, and String method with parameters:

title.length()
// Results in the length of a title object
name.equals("Java")
// Checks if the name objects is equal to the 
// String Java.
name.toUpperCase() 
//Converts name to uppercase 
// letters.

The methods of the String class are well worth reading about in the API documentation. See For More Information

Program Challenge

A case of Strings

Now that you've learned about if/else/switch statements, and the String class, try the following Program Challenge:

  1. Create a class called CaseofStrings
  2. Declare a variable of type String called sentence that says, "It's fun developing applications in the Java programming language."
  3. Use a switch statement to create a menu that takes the char A, B, C, D. When using type char, you must enclose the char in ''. For example, 'A'.
  4. For case A, have the application print out the length of the String, if the length is greater than 0. Otherwise, print a message saying there wasn't anything to count.
  5. For case B, print the String to all uppercase letters.
  6. For case C, print a substring, using the startIndex of 40 and an endIndex of 65 as the arguments.
  7. For case D, replace the letters t with Z throughout the String.
  8. Compile CaseofStrings and run. Change the variable menuItem to B, then recompile and run. Do the same for each letter to see the results:
    66
    IT'S FUN DEVELOPING APPLICATIONS IN THE JAVA PROGRAMMING 
    LANGUAGE.
    Java programming language
    IZ's fun developing applicaZions in Zhe Java programming 
    language.
      

Java Bits:

The two types

Before you use the name of a variable, you must declare its type. In Java programming, there are two types: Primitive and Reference.

Primitive Types

Primitive, or simple, types are not objects.

The following are primitives:

  • Integers, such as byte, short, int, and long
  • Floating-point numbers, such as double and float
  • Characters representing letters and numbers called char
  • Boolean, which is a type that represents true or false values

Because primitive types are not objects, declaring them is a one-step process:

int month;  //declaration without a value
int month = 10; //declaration with an
                //assigned value
Reference Types

Reference types frequently refer to prebuilt objects, such as classes or abstract classes that are a part of the Java 2 Platform, Standard Edition (J2SE library. Reference types may also refer to classes specifically designed by the programmer to go with an application. The term class type is often used synonymously with reference type.

As an example:

Font monoFont = new Font("Courier", Font.PLAIN, 12);

The reference variable name monoFont refers to the Font class. To declare and instantiate, or create the object, the keyword new is used.

Methods also are declared with a type. They are declared by the type of the value they return such as String or double. If they are declared void, this means they return nothing.

New to Java Technology Forum Latest

GUI Bulletin Board Question:

sspurcell wants to know how to create a Java GUI bulletin board, using Java I/O.

Can you advise sspurcell on the best ways to go about writing and reading files for this kind of application?


Crossword Puzzle #2

Test your terminology with this new crossword puzzle.

For More Information

For More Information

The Java Tutorial Trail: Lesson: Characters and Strings

The Java Tutorial Trail: Lesson: The if/else Statements

The Java Tutorial Trail: Lesson: The switch Statement

Class String:

jGuru, Language Essentials Short Course: Variable Definition and Assignment:

jGuru, Language Essentials Short Course: Strings:

jGuru, Language Essentials Short Course: Reference Variable Usage

Program Challenge Solution

This is one possible solution to the Program Challenge:

public class
CaseofStrings
{

             
  public static void main(String[] args)
   {
    String sentence = "It's fun developing applications" +
                 " in the Java programming language.";
    char menuItem = 'A';
    
    switch (menuItem)
    {
    
    case 'A':
         if (sentence.length() > 0)
         {
           System.out.println(sentence.length());
          }
           else
           {
           System.out.println("Nothing to count");
           }
           break;
    case 'B':
         System.out.println(sentence.toUpperCase());
         break;
    case 'C':
         System.out.println(sentence.substring(40, 65));
         break;
    case 'D':
         System.out.println(sentence.replace('t', 'Z'));
         break;
         
     }
   }
   
}

Results after changing the menuItem variable to A-D:

66
IT'S FUN DEVELOPING APPLICATIONS IN THE 
JAVA PROGRAMMING LANGUAGE.
Java programming language
IZ's fun developing applicaZions in Zhe 
Java programming language.

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.

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
September 2001


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