Sun Microsystems Logo

 

 
LAB-1005: Java Programming Basics I

Expected duration:  10 hours

Lab exercises and homeworks:
Other Online Resources:
Hardware and OS requirement:
OS platforms you can use for taking this course:

Software needed for the lab:

Please download and install the following set of software. If you have any questions on installation, please feel free to send them to the email alias mentioned below.

NetBeans Lab Project Files:
Other sample codes:

One of the most effective ways to learn Java programming is to see what others have done.  Please feel free to see and learn from the sample codes below.  By the way, I found grep utility on both Unix and Windows are quite useful in searching for string fragment at the command line.
What is and how to submit homework:
  • Each exercise below contains homework.  It also explains what to submit and how to submit homework.



Exercise 0:  Things to check before you start the lab



   Exercise 3.1: Write, Compile, and Run Hello Java Program (30 minutes)


Introduction:

The goal of this exercise is to let you experience a complete development cycle  - writing, compiling, and running a simplest possible Java program - using command line tools.  If you have done any programming in the past using different programming languages such as C or C++, this is not that much different from it. (There is a slight difference, however.  In Java, the compiler javac compiles the Java source code into what is called bytecode which can be run on any Java compliant platform, thus provides the portability of the Java programs. The bytecode is the same thing as Java class file, which is represented by *.class file notation.)

You will also get some exposure to the concept of the classpath.  The classpath is the most basic but essential concept you  will need to understand - it is basically a location where *.class files reside.   If the classpath is not set up correctly, you will experience the infamous "java.lang.NoClassDefFoundError: <name of the class file>" exception.

Steps to follow:

1. mkdir c:\myjavaprograms (to create a directory of your choice - this is the directory where you are going to write Java programs)
2. cd \myjavaprograms (this directory becomes the current directory)
3. Write Hello.java using your editor of choice (in this example, I am using jedit) as shown in Code-3.1-a below.  You can cut and paste the code from the Code-3.1-a but I encourage you to write the code line by line yourself manually just to experience some compile errors.
  • jedit Hello.java
public class Hello {
   
    /**
     * My first Java program
     */
    public static void main( String[] args ){
       
        // Print the string "Hello world" on screen
        System.out.println("Hello world");
       
    }

}
Code-3.1-a: Hello.java

4. Compile Hello.java using javac compiler.  The javac compiler comes with J2SE SDK you've download.  It resides in %JAVA_HOME%\bin (Windows) or $JAVA_HOME/bin (Solaris/Linux) directory. The result of compilation will be the creation of Hello.class file.
  • javac Hello.java
Trouble-shooting 3.1.a: If you experience the following error condition, it means the %JAVA_HOME%\bin for Windows platform or $JAVA_HOME/bin for Solaris/Linux platform is not set in your path.  You can try C:\Program Files\Java\jdk1.5.0_06\bin\javac Hello.java (for Windows) if you want to proceed without setting the path.
  • C:\myjavaprograms>javac Hello.java
    'javac' is not recognized as an internal or external command,
    operable program or batch file.
Trouble-shooting 3.1.b: If your Hello.java program contains a problem such as a typo or missing semi-colon after each statement, you will experience compile errors like an example compile error below (I misspelled it - it should have been System.out.println("Hello world"); instead of Syste.out.println("Hello world");.
  • C:\myjavaprograms>javac Hello.java
    Hello.java:9: package Syste does not exist
            Syste.out.println("Hello world");
                 ^
    1 error
Trouble-shooting 3.1.c: If you name your file as hello.java (instead of Hello.java), you will experience the following problem.  It is because the file name, hello.java,  and the class name inside the code does not match.  Inside the code, you use Hello in "public class Hello" statement and you name your file as hello.java.  They have to match.  And Java is case sensitive.  hello.java and Hello.java are different files as far as Java is concerned.  So rename the file to Hello.java and do the compilation again.
  • C:\myjavaprograms>javac hello.javahello.java:1: class Hello is public, should be declared in a file named Hello.java
    public class Hello {
           ^
    1 error

Experimentation 3.1.d
: Try "javac -verbose Hello.java" to see what is happening when you run javac. You really don't need to understand what is happening underneath at this point, however, except that it reads Hello.java file and then created Hello.class at the end.
  • C:\myjavaprograms>javac -verbose Hello.java
    [parsing started Hello.java]
    [parsing completed 31ms]
    [search path for source files: [C:\Program Files\Java\jre1.5.0_05\lib\ext\QTJava.zip]]
    [search path for class files: [C:\Program Files\Java\jdk1.5.0_06\jre\lib\rt.jar,C:\Program Files\Java\jdk1.5.0_06\jre\lib\jsse.jar, C:\Program Files\Java\jdk1.5.0_06\jre\lib\jce.jar, C:\Program Files\Java\jdk1.5.0_06\jre\lib\charsets.jar, C:\Program Files\Java\jdk1.5.0_06\jre\lib\ext\dnsns.jar, C:\Program Files\Java\jdk1.5.0_06\jre\lib\ext\localedata.jar, C:\Program Files\Java\jdk1.5.0_06\jre\lib\ext\sunjce_provider.jar, C:\Program Files\Java\jdk1.5.0_06\jre\lib\ext\sunpkcs11.jar, C:\Program Files\Java\jre1.5.0_05\lib\ext\QTJava.zip]]
    [loading C:\Program Files\Java\jdk1.5.0_06\jre\lib\rt.jar(java/lang/Object.class)]
    [loading C:\Program Files\Java\jdk1.5.0_06\jre\lib\rt.jar(java/lang/String.class)]
    [checking Hello]
    [loading C:\Program Files\Java\jdk1.5.0_06\jre\lib\rt.jar(java/lang/System.class)]
    [loading C:\Program Files\Java\jdk1.5.0_06\jre\lib\rt.jar(java/io/PrintStream.class)]
    [loading C:\Program Files\Java\jdk1.5.0_06\jre\lib\rt.jar(java/io/FilterOutputStream.class)]
    [loading C:\Program Files\Java\jdk1.5.0_06\jre\lib\rt.jar(java/io/OutputStream.class)]
    [wrote Hello.class]
    [total 266ms]
Experimentation 3.1.e: Try "javac -help" to see what options you can specify when you compile Java code using javac compiler.  You don't need to understand every option right now but the important options are "-classpath <path>", "-cp <path>", "-sourcepath <path>", "-d <directory>".  Please feel free to play around with these options.  Among these four, "-classpath <path>", "-cp <path>" are more important to understand.  By the way, "-classpath <path>", "-cp <path>" are the same thing. 
  • C:\myjavaprograms>javac -help
    Usage: javac <options> <source files>
    where possible options include:
      -g                         Generate all debugging info
      -g:none                    Generate no debugging info
      -g:{lines,vars,source}     Generate only some debugging info
      -nowarn                    Generate no warnings
      -verbose                   Output messages about what the compiler is doing
      -deprecation               Output source locations where deprecated APIs are used
      -classpath <path>          Specify where to find user class files
      -cp <path>                 Specify where to find user class files
      -sourcepath <path>         Specify where to find input source files
      -bootclasspath <path>      Override location of bootstrap class files
      -extdirs <dirs>            Override location of installed extensions
      -endorseddirs <dirs>       Override location of endorsed standards path
      -d <directory>             Specify where to place generated class files
      -encoding <encoding>       Specify character encoding used by source files
      -source <release>          Provide source compatibility with specified release

      -target <release>          Generate class files for specific VM version
      -version                   Version information
      -help                      Print a synopsis of standard options
      -X                         Print a synopsis of nonstandard options
      -J<flag>                   Pass <flag> directly to the runtime system

5. Make sure Hello.class file has been created.  The Hello.class file contains bytecode representation of the Hello class.
  • dir Hello.class
6. Run the Hello program using java command. The java command starts the Java Virtual Machine and runs the Hello program in this example.  A Java program can be made of multiple Java classes and and a set of libraries.  In this example, the Hello program just contains a single class called Hello.class. You can regard the java command as Java interpreter.
  • java Hello
You should see either of the following results.
  • C:\myjavaprograms>java Hello
    Hello world
    or
  • C:\myjavaprograms>java Hello
    Exception in thread "main" java.lang.NoClassDefFoundError: Hello
Trouble-shooting 3.1.g: If you experience the "Exception in thread "main" java.lang.NoClassDefFoundError: Hello" exception as shown above, it is highly likely because you are using predefined or wrong (at least for running this program) CLASSPATH environment variable. You can find out whether CLASSPATH environment variable is set or not as following - in the example below, the CLASSPATH is set to C:\Program Files\Java\jre1.5.0_05\lib\ext\QTJava.zip. (You can type jar tvf "C:\Program Files\Java\jre1.5.0_05\lib\ext\QTJava.zip" at the command line to see what Java classes make up  the zip file.)
  • C:\myjavaprograms>set CLASSPATH
    CLASSPATH=C:\Program Files\Java\jre1.5.0_05\lib\ext\QTJava.zip
The "Exception in thread "main" java.lang.NoClassDefFoundError: Hello" means that the Java interpreter, java, could not find the Hello.class file in the classpath. (Please be warned this will be the most frequently encountered error condition you will be experiencing the first time you learn Java programming using command line tools such as javac and java. The NetBeans IDE handles all this for you.) 

One way to solve the problem is unsetting the CLASSPATH environment variable for now as described below and run the Hello program again as following.  (In this case, the classpath is the current directory which contains the Hello.class file. I will explain how Java interpreter finds which classpath to use shortly.)

  • C:\myjavaprograms>java Hello
    Exception in thread "main" java.lang.NoClassDefFoundError: Hello
  • C:\myjavaprograms>set CLASSPATH=
  • C:\myjavaprograms>set CLASSPATH
    Environment variable CLASSPATH not defined
  • C:\myjavaprograms>java Hello
    Hello world
Experimentation 3.1.h: You can also explicitly specify the classpath by using -classpath and -cp option.  Try "java -classpath . Hello" and "java -cp . Hello" as shown below. (There is a dot . between -classpath and Hello and -cp and Hello.) It should work as following.  What you did is basically specifying that the current directory, which is represented by the dot ., is the classpath you want to use.
  • C:\myjavaprograms>java -classpath . Hello
    Hello world
  • C:\myjavaprograms>java -cp . Hello
    Hello world
Experimentation 3.1.i: Try to set the classpath with full directory path, C:\myjavaprograms in this example.  It should work as well.
  • C:\myjavaprograms>java -classpath C:\myjavaprograms Hello
    Hello world
  • C:\myjavaprograms>java -cp C:\myjavaprograms Hello
    Hello world
Important: The "-classpath <path>" or "-cp <path>" option specifies the location where the class files (in this example, we have only a single class file called Hello.class) reside.  When you don't specify the classpath option, the Java interpreter tries to find the class files in the directories specified in the CLASSPATH environment variables or in a current directory.  In fact,  the Java interpreter tries to find the class files in the following order.
  1. In the directories you specify with -classpath or -cp option. 
  2. In the directories that are specified in the CLASSPATH environment variable (If you have not specified the -classpath or -cp option)
  3. In the currently directory (If you have not specified the -classpath or -cp option and the environment variable CLASSPATH is not set)
Online resource: For more detailed description on classpath, please see "Setting the class path" from java.sun.com.

Experimentation 3.1.j: Try "java -classpath .. Hello" to see if it still works. (Instead of single dot ., you specify double dots .. between -classpath and Hello.  The double dot .. specifies a parent directory, C:\ in this example while single dot . specifies the current directory, c:\myjavaprograms in this example.) It should fail as following.  It is because you set the classpath to a parent directory, C:\, which does not contain Hello.class file.
  • C:\myjavaprograms>java -classpath .. Hello (this should fail because you are the parent directory C:\ as classpath here)
    Exception in thread "main" java.lang.NoClassDefFoundError: Hello
Now try to copy the Hello.class file to the parent directory and try the above command again.  You should see the following result.  Try to think why this works. 
  • C:\myjavaprograms>move Hello.class ..  (move the Hello.class to parent directory)
    C:\myjavaprograms>java -classpath .. Hello (run the program using the classpath set to the parent directory)
    Hello world
    C:\myjavaprograms>java -classpath C:\ Hello (same as above, you the classpath explicitly)
    Hello world
    C:\myjavaprograms>java -classpath . Hello (this should fail because you no longer have Hello.class in the current directory)
    Exception in thread "main" java.lang.NoClassDefFoundError: Hello
Important: As is mentioned above, you can set system wide classpath via CLASSPATH environment variable. This classpath gets applied system-widely meaning it gets applied to all Java programs running on that platform.  Of course, you can override it via -classpath or -cp option when you run a particular program.
 
Experimentation 3.1.k: Try to set the environment variable CLASSPATH first to the directory that contains Hello.class file and then run the program as following.  It should work.
  • C:\myjavaprograms>set CLASSPATH=c:\myjavaprograms
    C:\myjavaprograms>java Hello  (You are going to experience the following Exception because you don't have Hello.class in the currently anymore since you moved it to a parent directory in the previous experimentation)
    Exception in thread "main" java.lang.NoClassDefFoundError: Hello
    C:\myjavaprograms>move ..\Hello.class . (So move the Hello.class back to the currently directory)
    C:\myjavaprograms>java Hello
    Hello world
Experimentation 3.1.l: Try to set the environment variable CLASSPATH to a bogus directory and then run the program as following:
  • C:\myjavaprograms>set CLASSPATH=c:\tmp (set the CLASSPATH environment variable to a bogus directory, c:\tmp)
    C:\myjavaprograms>java Hello (should fail since the c:\tmp directory does not contain Hello.class file)
    Exception in thread "main" java.lang.NoClassDefFoundError: Hello
    C:\myjavaprograms>java -cp . Hello (now you are overriding the CLASSPATH with your own classpath)
    Hello world
Experimentation 3.1.m: Try to set the environment variable CLASSPATH to a set of directories and then run the program as following:
  • C:\myjavaprograms>set CLASSPATH=c:\tmp;c:\myjavaprograms
    C:\myjavaprograms>java Hello
    Hello world
Important: As you've seen above, you can set the environment variable CLASSPATH to a set of directories.  For Windows, you use semi-colon ; while on Solaris/Linux platform, you use colon : as a delimiter.  You can also specify multiple directories when you specify -classpath or -cp option as following:
  • C:\myjavaprograms>java -classpath c:\tmp Hello (this should fail since c:\tmp does not contain Hello.class file)
    Exception in thread "main" java.lang.NoClassDefFoundError: Hello
    C:\myjavaprograms>java -classpath c:\tmp;c:\myjavaprograms Hello (the classpath is set to two directories c:\tmp and c:\myjavaprograms - they will be searched in sequence)
    Hello world
    C:\myjavaprograms>java -classpath c:\tmp;. Hello
    Hello world
Homework:

1. Modify, compile, and run the Hello program so that it prints the following
  • "This is my first Java program" (instead of "Hello world")
2. Please play around with the classpath settings with -classpath or -cp option and CLASSPATH environment variable.

What and how to submit:

1. Email modified Hello.java file as an attachment to javaintro1homework@sun.com with subject line as HWExercise3.1. (Please make sure you use the correct subject line.)  No need to make it a zip file.

                                                                                                                            return to the top


   Exercise 3.2:  Write, Compile, and Run Hello Java Program using NetBeans (30 minutes)


Introduction


In this exercise, you are going to build the same application you built in Exercise 3.1 using NetBeans IDE.  You are going to use the built-in editor, compiler, and JVM.

Steps to follow:


1. Start the NetBeans IDE.
  • Windows: Start > All Programs > NetBeans 5.0 Beta > NetBeans IDE or click NetBeans IDE desktop icon
  • Solaris/Linux: <NETBEANS50_HOME>/bin/netbeans or click NetBeans IDE desktop icon
2. Create a new NetBeans project and Hello main class. By main class, I mean a class that contains the main(..) method.
    • Select File from the menu bar and select New Project.
    • Under Choose Project pane, select General  under Categories: and Java Application under Projects: (Figure-3.2-a below)

Figure-3.2-a: Create a new NetBeans project
    • Click Next.
    • Under Name and Location pane, (Figure-3.2-b below)
      • For Project Name field, fill it with Hello.
      • For Create Main Class field, change it to hello.Hello (from hello.Main).  The hello part of the hello.Hello is a package name and Hello part of the hello.Hello is the class name.  In this case, the Hello class belongs to hello package.  We are going to learn the concept of package later on but for now you can think of a package as a container of Java classes.
      • Click Finish.

Figure-3.2-b: Enter project name and create Hello class under hello package
Note that the IDE generated Hello.java code gets displayed in the source editor.  Also the Hello.java source code is generated under the hello directory.  Under Java programming environment, the package structure matches the directory structure. (We will learn more on this later on.)
3. Modify the IDE generated Hello.java
  • Replace the code of  Hello class of IDE generated Hello.java code in the source editor with the one of Code-11 above while leaving the package statement at the top of the file. (Figure-3.2-c below)

Figure-3.2-c: Hello.java
4. Run Hello program
  • Right click Hello project node and select Run Project from the contextual menu. ((Figure-3.2-d below)

Figure-3.2-d: Run Hello Program
  • Note that the Output window displays the result (Figure-3.2-e below)

Figure-3.2-e: Output of running Hello program

Homework:

1. Create a new NetBeans project called "MyOwnHelloWorld" from scratch.
2. The program should display the following text when it runs.
  • This is my own NetBeans project, and I am damn proud of it.
What and how to submit:

1. Screen-capture of the NetBeans that contains the output. Name the file as HWExercise3.2.gif or HWExercise3.2.jpg or HWExercise3.2.png or what ever popular format modern browsers can take.
  • Under Windows, you can do the screen capture by taking steps below
    • Press Alt+PrtSc key combination to copy the current window image to the clipboard
    • Select Start / All Programs / Accessories / Paint
    • Ctrl+V to paste into Paint. 
    • File / New, then Ctrl+V
    • File / Save As - pull down "Save As Type" to be GIF or JPG, then save
  • Under Linux/Solaris, you can take one of the following two approaches.
    • Option 1: Type "import HWExercise3.2.jpg" in a terminal window and then you can select the area of the screen that you want with the mouse.
    • Option 2: Use gimp program.  It has screen capture functionality.
2. Email it as an attachment to javaintro1homework@sun.com with subject line as HWExercise3.2.

                                                                                                               return to the top



   Exercise 4.1: Declaring,  Initializing, Printing Variables (30 minutes)


Introduction:

In this exercise, you are going to learn how to declare, initialize a variable.  You also learn how to modify and display a value of a variable.

Steps to follow:


1. Write OutputVariable.java as shown in Code-4.1-a below. (You are welcome to do this work using either command line tools or NetBeans. The instruction here is given using command line tools.  In general, using NetBeans is highly recommended.)
  • cd \myjavaprograms
  • jedit OutputVariable.java
public class OutputVariable {

    public static void main( String[] args ){

        // Variable value is int primitive type and it is initialized to 10
        int value = 10;
    
        // Variable x is char primitive type and it is initialized to 'A'
        char x;
        x = 'A';
       
        // Display the value of variable "value" on the standard output device
        System.out.println( value );

        // Display the value of variable "x" on the standard output device
        System.out.println( "The value of x=" + x );

    }

}
Code-4.1-a: VariableSamples.java

2. Compile and run the code
  • javac OutputVariable.java
  • java -classpath . OutputVariable
3. Verify that the result is as following
  • C:\myjavaprograms>java OutputVariable
    10
    The value of x=A
Homework:

1. Modify OutputVariable.java as following and compile and run the code
  • Define another primitive type as following
    • double grade = 11;
  • Print out the value of variable "grade" using the following statement.
    • System.out.println( "The value of grade =" + grade );

What and how to submit:

1. Email modified OutputVariable.java file as an attachment to javaintro1homework@sun.com with subject line as HWExercise4.1.

                                                                                                               return to the top

    Exercise 4.2: Rebuilding the above program using NetBeans (30 minutes)

Introduction:

In this exercise, you are going to rebuild the same application you built in Exercise 4.1 using NetBeans.  The steps you need to follow are pretty much the same ones as in Exercise 3.2.

Steps to follow:


1. Start the NetBeans IDE (if you have not done so yet.)
  • Windows: Start > All Programs > NetBeans 5.0 Beta > NetBeans IDE or click NetBeans IDE desktop icon
  • Solaris/Linux: <NETBEANS50_HOME>/bin/netbeans or click NetBeans IDE desktop icon
2. Create a new NetBeans project and OutputVariable main class. 
  • Select File from the menu bar and select New Project.
  • Under Choose Project pane, select General  under Categories: and Java Application under Projects:
3. Modify the IDE generated OutputVariable.java
  • Replace IDE generated OutputVariable.java code in the source editor with the one of Code-4.1-a above while leaving the package statement at the top of the file.
4. Run OutputVariable program
  • Right click OutputVariable project node and select Run Project from the contextual menu.
  • Note that the Output window displays the result
Homework:

1. Do the homework of Exercise 4.1 above using NetBeans.

What and how to submit:

1. Screen-capture of the NetBeans that contains the output. Name the file as HWExercise4.2.gif or HWExercise4.2.jpg.
2. Email it to javaintro1homework@sun.com with subject line as HWExercise4.2.



 Exercise 4.3: Conditional Operator (30 minutes) 

Introduction:

In this exercise, you are going to write a Java program which uses conditional operators.

Steps to follow:

1. Write ConditionalOperator.java.  (You are welcome to do this work using either command line tools or NetBeans. The instruction here is given using command line tools.  In general, using NetBeans is highly recommended.)
  • cd \myjavaprograms
  • jedit ConditionalOperator.java

public class ConditionalOperator {

    public static void main( String[] args ){

        // Declare and initialize two variables, one String type variable
        // called status and the other int primitive type variable called
        // grade.
        String status = "";
        int grade = 80;

        // Get status of the student.
        status = (grade >= 60)?"Passed":"Fail";

        // Print status.
        System.out.println( status );
    }

}
Code-4.3-a: ConditionalOperator.java

2. Compile and run the code
  • javac ConditionalOperator.java
  • java -classpath . ConditionalOperator
3. Verify that the result is as following
  • C:\myjavaprograms>java ConditionalOperator
    Passed
Homework:

1. Modify ConditionalOperator.java as adding the following lines of code at the appropriate place, compile and run the code
  • int salary = 100000;
  • Print "You are rich!" if the salary is over 50000. Print "You are poor!" otherwise.
2. Do the homework both using command line tools and using NetBeans.

What and how to submit:

1. Modified ConditionalOperator.java and screen-capture of the NetBeans that contains the output. Name the screen capture file as HWExercise4.3.gif or HWExercise4.3.jpg.
2. Email the above files as attachments to javaintro1homework@sun.com with subject line as HWExercise4.3.

                                                                                                               return to the top


  Exercise 4.4: Building and running AverageNumber sample program (30 minutes)


Introduction

In this exercise, you are going to build and run a sample Java program called AverageNumber using NetBeans.  The sample program can be built and run as NetBeans project.  So you are going to open an existing NetBeans project rather than creating a new project.

Steps to follow:

0. If you have not downloaded and unzipped the NetBeansFiles.zip file as described above, please do that first.
1. Start NetBeans (if you have not done so.) 
2. Open an existing AverageNumber sample NetBeans project.
  • Select File from menu bar.
  • Select Open Project  (Crtl+SHift+O).

Figure-X: Open an existing project
  • In the Open Project window, browse to C:\NetBeansFiles\Chapter 4\4.2 directory and select AverageNumberProject. (The small bookmark on the AverageNumberProject file folder indicates that this directory contains NetBeans project meta files and ready to be opened as NetBeans project.)
  • Click Open Project Folder button.

Figure-X: Open AverageNumberProject
  • Expand AverageNumberProject project node.
  • Expand Source Packages.  (The Source Packages node contains all the packages.)
  • Expand <default package>. (If you create Java code without a package statement, it belongs to a default package.)
  • Double click AverageNumber.java to open it in the Editor window.

Figure-X: Open AverageNUmber.java

3. Run the program.
  • Right click AverageNumber.java node and select Run File (Shift+F6).  Since the source file contains the main(..) method, you can do this.  You should see the result in the Output window.  (Or you can right click the AverageNumberProject project node and then select Run Project.)

Figure-X: Run File

Homework

1. Add another number with the following statement and compute a new average.
  • int num4 = 100;
What and how to submit

1. No need to submit this homework

                                                                                                               return to the top


 Exercise 4.5: Building and running GreatestValue sample program (30 minutes)


Introduction

In this exercise, you are going to build and run a sample Java program called GreatestValue using NetBeans.  The sample program can be built and run as NetBeans project.  So you are going to open an existing NetBeans project rather than creating a new project.

Steps to follow

0. If you have not downloaded and unzipped the NetBeansFiles.zip file as described above, please do that first.
1. Start NetBeans (if you have not done so.)
2. Open an existing GreatestValue sample NetBeans project.
  • Select File from menu bar.
  • Select Open Project  (Crtl+SHift+O).
  • In the Open Project window, browse to C:\NetBeansFiles\Chapter 4\4.3 directory and select GreatestValueProject.
  • Click Open Project Folder button.
  • Expand GreatestValueProject project node.
  • Expand Source Packages.  (The Source Packages node contains all the packages.)
  • Expand <default package>. (If you create Java code without a package statement, it belongs to a default package.)
  • Double click GreatestValue.java to open it in the Editor window.
3. Run the program.
  • Right click GreatestValue.java node and select Run File (Shift+F6) to run the program.
Homework

1. Modify GreatestValue.java code so that it displays the greatest number as well as smallest number as well.

What and how to submit

1. Screen-capture of the NetBeans IDE that contains the output. Name the screen capture file as HWExercise4.5.gif or HWExercise4.5.jpg.
2. Email the above file as attachments to javaintro1homework@sun.com with subject line as HWExercise4.5.

                                                                                                               return to the top


 Exercise 5.1: Getting Input From Keyboard via BufferedReader & JavaDoc Online (30 minutes)


Introduction:

In this exercise, you are going to build a simple interactive Java application, which gets user entered input data from keyboard. The program will use BufferedReader and InputStreamReader classes to receive the intput data. (You don't really need to understand in detail how these classes work, however.)

Feel free to use NetBeans to do this work (assuming you are reasonably comfortable using the basic features of NetBeans by now) even though the instruction below is based on command line.

Steps to follow:

1. Write GetInputFromKeyboard.java as shown in Code-5.1.a below.  (You are welcome to do this work using either command line tools or NetBeans. The instruction here is given using command line tools.  In general, using NetBeans is highly recommended.) If you are using NetBeans, you will have the "package getinputfromkeyboard" statement at the top.
  • cd \myjavaprograms
  • jedit GetInputFromKeyboard.java
// Import the classes you need in this program
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class GetInputFromKeyboard {
   
    public static void main( String[] args ){

        BufferedReader dataIn = new BufferedReader(new
                InputStreamReader( System.in) );
       
        String name = "";
        System.out.println("Please Enter Your Name:");
        try{
            name = dataIn.readLine();
        }catch( IOException e ){
            System.out.println("Error!");
        }
        System.out.println("Hello " + name +"!");
    }

}
Code-5.1.a: GetInputFromKeyboard.java

2. Compile and run the program.
  • javac GetInputFromKeyboard.java
  • java -classpath . GetInputFromKeyboard
You should have the following interaction.  In this example, I typed Sang Shin.
  • C:\myjavaprograms>java -classpath . GetInputFromKeyboard
    Please Enter Your Name:Sang Shin
    Hello Sang Shin!
3. Modify the GetInputFromKeyboard.java to read your age as shown in Code 5.1.b below. The code fragment that needs to be added is highlighted in bold font.

// Import the classes you need in this program
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class GetInputFromKeyboard {
   
    public static void main( String[] args ){

        BufferedReader dataIn = new BufferedReader(new
                InputStreamReader( System.in) );
       
        String name = "";
        System.out.println("Please Enter Your Name:");
        try{
            name = dataIn.readLine();
        }catch( IOException e ){
            System.out.println("Error!");
        }
        System.out.println("Hello " + name +"!");
       
        String age= "";
        System.out.println("Please Enter Your Age:");
        try{
            age = dataIn.readLine();
        }catch( IOException e ){
            System.out.println("Error!");
        }
        System.out.println("Hello " + name +"!" + " " + "Your age is " + age);

    }

}
Code 5.1.b: Modified code in which your age is prompted

4. Compile and run the code.
  • javac GetInputFromKeyboard.java
  • java -classpath . GetInputFromKeyboard
5. You should have the following interaction. 
  • C:\myjavaprograms>java -classpath . GetInputFromKeyboard
    Please Enter Your Name:Sang Shin
    Hello Sang Shin!
    Please Enter Your Age:99
    Hello Sang Shin! Your age is 99
6. Now suppose you want to add the following logic to the program. 
  • If the entered age is over 100, display
    • Hello <name>! You are old!
  • Otherwise
    • Hello <name>! You are young!
Notice in the previous code, your program received the age in the form of String type.  And you cannot compare String type "99" with int primitive type of 100.  In other words, you have to convert the String type of "99" to int type of 99 before you compare it against another int type 100.

Fortunately, there is a method called parseInt() in the Integer class for converting String type into int type.  Try to see the JavaDoc of Integer class from the following J2SE 5.0 Javadoc website. (You have to scroll down in order to see the Integer class in the lower left box. 
Click Integer class to display Javadoc information of the class on the right side of the browser. (Figure 5.1.c below)

o scroll Figure 5.1.c: Integer class

7. Scroll down detailed information pane o the the Integer class to see the parseInt(String s) method. (Figure 5.1.d below)


Figure 5.1.d: parseInt(String s) method of Integer class

8. Click parseInt(String s) method to see the detailed information. (Figure 5.1.e below)  The parseInt(String s) method of the Integer class lets you convert a String type value to int type.  (Also note that parseInt(String s) method is a static method.  A a static method can be called without creating an object instance. We will talk about this later.)


Figure 5.1.e: Detailed information on parseInt(String s) method of Integer class

9. Modify the GetInputFromKeyboard.java to read Your age as shown in Code 5.1.f below. The code fragment that needs to be added is highlighted in bold font.

// Import the classes you need in this program
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class GetInputFromKeyboard {
   
    public static void main( String[] args ){

        BufferedReader dataIn = new BufferedReader(new
                InputStreamReader( System.in) );
       
        String name = "";
        System.out.println("Please Enter Your Name:");
        try{
            name = dataIn.readLine();
        }catch( IOException e ){
            System.out.println("Error!");
        }
        System.out.println("Hello " + name +"!");
       
        String age= "";
        System.out.println("Please Enter Your Age:");
        try{
            age = dataIn.readLine();
        }catch( IOException e ){
            System.out.println("Error!");
        }
        System.out.println("Hello " + name +"!" + " " + "Your age is " + age);

        // Convert the String type of age variable into int primitive type variable ageint.
        int ageint = Integer.parseInt(age);

        // Now you can compare the int primitive type against int type value 100
        if (ageint > 100){
            System.out.println("Hello " + name +"!" + " " + "You are old.");
        }
        else{
            System.out.println("Hello " + name +"!" + " " + "You are young.");
        }

    }

}
Code 5.1.f: Modified code

10. Compile and run the code.
  • javac GetInputFromKeyboard.java
  • java -classpath . GetInputFromKeyboard
11. You should have the following interaction. 
  • C:\myjavaprograms>java -classpath . GetInputFromKeyboard
    Please Enter Your Name:Sang Shin
    Hello Sang Shin!
    Please Enter Your Age:10
    Hello Sang Shin! Your age is 10
    Hello Sang Shin! You are young.

    C:\myjavaprograms>java -classpath . GetInputFromKeyboard
    Please Enter Your Name:Sang Shin
    Hello Sang Shin!
    Please Enter Your Age:120
    Hello Sang Shin! Your age is 120
    Hello Sang Shin! You are old.
12. Now try to enter non-number value such as "NotANumber" string.  You will experience the following error condition.  This is expected. (We have not learned error handling yet - error handling is sometimes called exception handling. What happened is that the parseInt() method of Integer class throws an exception - By the way, an exception is an error condition - when it encountered a situation where it cannot perform the conversion. Good progamming practice of course is to catch this exception and handle it accordingly,  You will do that in the next step.  Try to read the Javadoc of NumberFormatException from http://java.sun.com/j2se/1.5.0/docs/api/.  We will also deal with this later on so if you don't understand, that is fine.)
  • C:\myjavaprograms>java -classpath . GetInputFromKeyboard
    Please Enter Your Name:Sang Shin
    Hello Sang Shin!
    Please Enter Your Age:NotANumber
    Hello Sang Shin! Your age is NotANumber
    Exception in thread "main" java.lang.NumberFormatException: For input string: "NotANumber"
            at java.lang.NumberFormatException.forInputString(Unknown Source)
            at java.lang.Integer.parseInt(Unknown Source)
            at java.lang.Integer.parseInt(Unknown Source)
            at GetInputFromKeyboard.main(GetInputFromKeyboard.java:32)
13. (This is optional homework meaning you don't have to do this part) Modify the GetInputFromKeyboard.java to read Your age as shown in Code 5.1.g below. The code fragment that needs to be added is highlighted in bold font.

// Import the classes you need in this program
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class GetInputFromKeyboard {
   
    public static void main( String[] args ){

        BufferedReader dataIn = new BufferedReader(new
                InputStreamReader( System.in) );
       
        String name = "";
        System.out.println("Please Enter Your Name:");
        try{
            name = dataIn.readLine();
        }catch( IOException e ){
            System.out.println("Error!");
        }
        System.out.println("Hello " + name +"!");
       
        String age= "";
        System.out.println("Please Enter Your Age:");
        try{
            age = dataIn.readLine();
        }catch( IOException e ){
            System.out.println("Error!");
        }
        System.out.println("Hello " + name +"!" + " " + "Your age is " + age);

        try{
            // Convert the String type of age variable into int primitive type variable ageint.
            int ageint = Integer.parseInt(age);

            // Now you can compare the int primitive type against int type value 100
            if (ageint > 100){
               System.out.println("Hello " + name +"!" + " " + "You are old.");
            }
            else{
                System.out.println("Hello " + name +"!" + " " + "You are young.");
            }
        }
        catch (NumberFormatException e){
               
System.out.println("Please enter a number!");
        }

    }

}
Code 5.1.g: Handle an error condition

14. (This is optional homework meaning you don't have to do this part) Compile and run the code.
  • javac GetInputFromKeyboard.java
  • java -classpath . GetInputFromKeyboard
15. (This is optional homework meaning you don't have to do this part) You should have the following interaction.
  • C:\myjavaprograms>java -classpath . GetInputFromKeyboard
    Please Enter Your Name:IdiotOftheWorld
    Hello IdiotOftheWorld!
    Please Enter Your Age:NotANumber
    Hello IdiotOftheWorld! Your age is NotANumber
    Please enter a number!

Homework:

1. Modify GetInputFromKeyboard.java as following, compile and run the code
  • Make the program to ask the following question
    • Please enter your mother's age:
  • Display added value of your age and your mother's age as following:
    • The added value of your age and your mother's age is <whatever number>!
  • Implement the following logic
    • If the added value is over 200, display
      • Hello <name>! You and your mother must be old!
    • Otherwise
      • Hello <name>! You and your mother must be young!
2. Do the homework either at the command line or using NetBeans.

What and how to submit:

1. Modified GetInputFromKeyboard.java (if you are doing the work using command line tool) or screen-capture of the NetBeans that contains the output (if you are using NetBeans). Name the screen capture file as HWExercise5.1.gif or HWExercise5.1.jpg.
2. Email it to javaintro1homework@sun.com with subject line as HWExercise5.1.

                                                                                                               return to the top


  Exercise 5.2:  Building and running LastThreeWords sample program & JavaOne NetBeans  (30 minutes)


Introduction:

In this exercise, you are going to build and run a sample Java program called LastThreeWords using NetBeans.  The sampleprogram can be built and run as NetBeans project.  So you are going to open an existing NetBeans project rather than creating a new project. (This is a similar setup as in Exercise 4.4 and Exercise 4.5 above.)

You will also install Java document zip file of J2SE SDK 5.0 to the NetBeans, which will enable context sensitive display of Javadoc of any standard Java class. The Java document zip file is the file you have downloaded previously as described above.

Steps to follow

0. If you have not downloaded and unzipped the NetBeansFiles.zip file as described above, please do that first.
1. Start NetBeans (if you have not done so.)
2. Open an existing LastThreeWords sample NetBeans project.
  • Select File from menu bar.
  • Select Open Project  (Crtl+SHift+O).
  • In the Open Project window, browse to C:\NetBeansFiles\Chapter 5\5.1 directory and select LastThreeWordsProject.
  • Click Open Project Folder button.
  • Expand LastThreeWordsProject project node.
  • Expand Source Packages.  (The Source Packages node contains all the packages.)
  • Expand <default package>. (If you create Java code without a package statement, it belongs to a default package.)
  • Double click LastThreeWords.java to open it in the Editor window.
3. Run the program.
  • Right click LastThreeWords.java node and select Run File (Shift+F6).  Since the source file contains the main(..) method, you can do this to run the program.  Another way to run your program is by right-clicking LastThreeWorksProject project node and then select Run Project.
  • You should see Input field being displayed at the bottom of the IDE.  Enter your first name and press Enter key. (Figure 5.2.a below)

Figure 5.2.a: Enter value to the Input field
  • Enter your last name and press Enter key.  Enter "Happy" and press Enter key.
  • You should see the following result. (Figure 5.2.b below)  (Yes, I understand the output is somewhat misleading in that the all the prompts are written to output after all of the inputs are entered.  This is a known issue. It is because the NetBeans uses ant as project meta data and the ant sends only complete lines to the output window. This is an ant issue that cannot be fixed in netbeans.  You can change the System.out.print(..) to System.out.println(..) to bypass this problem.)

Figure 5.2.b: Result of running the application

4.  Install Java document zip file of J2SE SDK 5.0 with NetBeans.  Once Java document zip file is installed, you should be able to display Java documentation of any class in a context sensitive manner.
  • Select Tools from the top-level menu bar.
  • Select Java Platform Manager. (Figure 5.2.c below)

Figure 5.2.c: Select Java Platform Manager
  • In the Java Platform Manager dialog box, select Javadoc tab.
  • Click Add ZIP/Folder button.  (Figure 5.2.d below)

Figure 5.2.d: Get ready to add the Java document zip file
  • Browse down to the directory where you have downloaded Java document zip file (jdk-1_5_0-doc.zip) as you did above.
  • Select jdk-1_5_0-doc.zip.  (If you have unzipped the zip file, then you can choose api directory under docs.)
  • Click Add ZIP/Folder button. (Figure 5.2.e below)

Figure 5.2.e: Add jdk-1_5_0-doc.zip
  • In the Java Platform Manager dialog box, click Close button. (Figure 5.2.f below)

Figure 5.2.f: Close the Java Platform Manager

5. Display Java document of the BufferedReader class in a context-sensitive manner.
  • Move your cursor to any position of the "BufferedReader" string.
  • Right click and choose Show Javadoc (Alt+F1) or click Alt+F1 key combination. (Figure 5.2.g below)

Figure 5.2.g: Display Java document of the BufferedReader class
  • The Java document of the BufferedReader class will be displayed in the default browser of your platform. (Figure 5.2.h below)

Figure 5.2.h: Java document of BufferedReader class
  • Read the description of the BufferedReader class.  (I don't expect you to understand everything about BufferedReader class.  Just get a sense of how to read Java document of a class.)
  • Click through the hyper links in the page. Again the goal of this exercise is to get some exposure on how to read Javadoc document.
Homework

1. Try to display the Java document of String class either from online version of J2SE SDK Javadoc  or in a context sensitive manner within NetBeans.  The String class is one of the most frequently used class when you are leaning Java progamming.  So please spend some time browsing various methods of the class.
2. Modify the LastThreeWords project above to use a method of String class so that the words that were entered by a user get displayed in all upper case first and then in all lower case.
  • Hint: You have to find out which method of a String class you will have to use by looking at the Javadoc of String class either from http://java.sun.com/j2se/1.5.0/docs/api/ or within NetBeans in a context sensitive manner.

What and how to submit:

1. Modified LastThreeWords.java (if you are doing the work using command line tool) or screen-capture of the NetBeans that contains the output (if you are using NetBeans). Name the screen capture file as HWExercise5.2.gif or HWExercise5.2.jpg.
2. Email it to javaintro1homework@sun.com with subject line as HWExercise5.2.



  Exercise 5.3: Getting Input From Keyboard via JOptionPane (30 minutes)


Introduction:


In this exercise, you are going to build the same application you built in Exercise 5.1 but this time using JOptionPane class. 

Feel free to use NetBeans to do this work (assuming you are reasonably comfortable using the basic features of NetBeans by now) even though the instruction below is based on command line.

Steps to follow:

1. Write GetInputFromKeyboardJOptionPane.java as shown in Code-5.2 below. (You are welcome to do this work using either command line tools or NetBeans. The instruction here is given using command line tools.  In general, using NetBeans is highly recommended.)
  • cd \myjavaprograms
  • jedit GetInputFromKeyboardJOptionPane.java

import javax.swing.JOptionPane;

public class GetInputFromKeyboardJOptionPane {
   
    public static void main( String[] args ){
        String name = "";
        name=JOptionPane.showInputDialog("Please enter your name");
        String msg = "Hello " + name + "!";
        JOptionPane.showMessageDialog(null, msg);
    }
}
Code-5.3: GetInputFromKeyboardJOptionPane.java

2. Compile and run the code
  • javac GetInputFromKeyboardJOptionPane.java
  • java -classpath . GetInputFromKeyboardJOptionPane
    • Enter your name
    • CTRL/C to close the application
Homework:

1. Modify GetInputFromKeyboardJOptionPane.java as following, compile and run the code
  • Make the program to ask the following question
    • Please enter your age
  • Display the entered age as following
    • If the age is over 100, display
      • Hello <name>, You are old!
    • Otherwise
      • Hello <name>, You are young!
2. Do the homework either at the command line or using NetBeans.

What and how to submit:

1. Modified GetInputFromKeyboard.java or screen-capture of the NetBeans that contains the output. Name the screen capture file as HWExercise5.3.gif or HWExercise5.3.jpg.
2. Email it to javaintro1homework@sun.com with subject line as HWExercise5.3.

                                                                                                               return to the top



 Exercise 6.1:  Building and running Grades sample program  (30 minutes)


Introduction:

In this exercise, you are going to build and run a sample Java program called Grades using NetBeans.  The sample program can be built and run as NetBeans project.  So you are going to open an existing NetBeans project rather than creating a new project. (This is a similar setup as in Exercise 4.4 and Exercise 4.5 above.)

Steps to follow

0. If you have not downloaded and unzipped the NetBeansFiles.zip file as described above, please do that first.
1. Start NetBeans (if you have not done so.)
2. Open an existing Grades sample NetBeans project.
  • Select File from menu bar.
  • Select Open Project  (Crtl+SHift+O).
  • In the Open Project window, browse to C:\NetBeansFiles\Chapter 6\6.1 directory and select GradesProject.
  • Click Open Project Folder button.
  • Expand GradesProject project node.
  • Expand Source Packages.  (The Source Packages node contains all the packages.)
  • Expand <default package>. (If you create Java code without a package statement, it belongs to a default package.)
  • Double click Grades.java to open it in the Editor window.
    • Change every System.out.print(..) statement to System.out.println(..).
Trouble-shooting: If you open a project and it shows ??? as a project name, it is highly likely because you are running either NetBeans 4.1 or Sun Java Studio Enterprise 8 (which is based on NetBeans 4.1).  The NetBeansFiles.zip contains NetBeans project files that are based on 5.0. And that is the reason why you are seeing ???.   I created another file NetBeansFiles41.zip for the users of NetBeans 4.1 so that that is the file you want to download as described above.

3. Run the program.
  • Right-click GradesProject project node and then select Run Project.
Homework

1. Modify Grades.java as following, compile and run the code. 
  • If the average is greater than 90 (average > 90), display "You worked too hard!" (instead of :-))
  • If the average is greater than 60 (average > 60) and less than or equal  to 90 (average <= 90), display "You did OK."
  • If the average is less than or equal to 60 (average <= 60), display "You need to do some work."
What and how to submit:

1. Screen-capture of the NetBeans that contains the output. Name the screen capture file as HWExercise6.1.gif or HWExercise6.1.jpg or in whatever popular graphics file format.
2. Email it to javaintro1homework@sun.com with subject line as HWExercise6.1.



 Exercise 6.2:  Building and running NumWords sample program  (30 minutes)


Introduction:

In this exercise, you are going to build and run a sample Java program called NumWords using NetBeans.  The sample program can be built and run as NetBeans project.  So you are going to open an existing NetBeans project rather than creating a new project. (This is a similar setup as in Exercise 4.4 and Exercise 4.5 above.)

Steps to follow

0. If you have not downloaded and unzipped the NetBeansFiles.zip file as described above, please do that first.
1. Start NetBeans (if you have not done so.)
2. Open an existing NumWords sample NetBeans project.
  • Select File from menu bar.
  • Select Open Project  (Crtl+SHift+O).
  • In the Open Project window, browse to C:\NetBeansFiles\Chapter 6\6.2 directory and select NumWordsProject.
  • Click Open Project Folder button.
  • Expand NumWordsProject project node.
  • Expand Source Packages.  (The Source Packages node contains all the packages.)
  • Expand <default package>. (If you create Java code without a package statement, it belongs to a default package.)
  • Double click NumWords.java to open it in the Editor window.
3. Run the program.
  • Right-click NumWordsProject project node and then select Run Project.
  • You should see Input field being displayed at the bottom of the IDE. 
Homework:

1. Modify NumWords.java as following, comp