Lab Exercises
- Exercise 1: Autoboxing (20 minutes)
- Exercise 2: Enhanced For loop (20 minutes)
- Exercise 3: Static imports (20 minutes)
- Exercise 4: Variable arguments (20 minutes)
- Exercise 5: Type-safe enumerations (20 minutes)
- Homework Exercise (for people who are taking Sang Shin’s “Java Programming online course”)
Exercise 1: Autoboxing
The Autoboxing and Unboxing feature of J2SE 5.0 eliminates the drudgery of manual conversion between primitive types (such as int or long) and wrapper types (such as Integer or Long).
(1.1) Example without autoboxing
1. Create a new NetBeans project
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects.
- Click Next.
- Under Name and Location pane, for the Project Name field, type in NotUsingAutoBoxing as project name.
- For Create Main Class field, type in NotUsingAutoBoxing. (Figure-1.10 below)
- Click Finish.
Figure-1.10: Create a new project
- Observe that NotUsingAutoBoxing project appears and IDE generated NotUsingAutoBoxing.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated NotUsingAutoBoxing.java as shown in Code-1.11 below. Study the code by paying special attention to the bold fonted parts.
public class NotUsingAutoBoxing{
// Suppose the internal variables are in Wrapper types public NotUsingAutoBoxing() { } public static void main( String[] args ) { NotUsingAutoBoxing a = new NotUsingAutoBoxing(); // You have to create instances of Wrapper classes first // In the following code, you are unboxing in order to } |
Code-1.11: NotUsingAutoBoxing.java
3. Build and run the project
- Right click NotUsingAutoBoxing project and select Run Project.
- Observe the result in the Output window of the IDE. (Figure-1.13 below)
int Value of iObj is: 22 float Value of iObj is: 22.0 long Value of iObj is: 22 double Value of iObj is: 22.0 |
Figure-1.13: Result
(1.2) Example with autoboxing
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in UsingAutoboxing as project name.
- For Create Main Class field, type in UsingAutoboxing.
- Click Finish.
- Observe that UsingAutoboxing project appears and IDE generated UsingAutoboxing.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated UsingAutoboxing.java as shown in Code-1.21 below. Study the code by paying special attention to the bold fonted parts.
public class UsingAutoBoxing{
// Suppose the internal variables are in Wrapper types public UsingAutoBoxing() { } public static void main( String[] args ) { // a.fObj = new Float( 22.0 ); // a.lObj = new Long ( 22L ); // a.dObj = new Double( 22 ); // System.out.println( ” int Value of iObj is: ” + a.iObj.intValue() ); // System.out.println( ” float Value of iObj is: ” + a.fObj.floatValue() ); // System.out.println( ” long Value of iObj is: ” + a.lObj.longValue() ); // System.out.println( ” double Value of iObj is: ” + a.dObj.doubleValue() ); } |
Code-1.21: UsingAutoBoxging.java
3. Build and run the project
- Right click UsingAutoBoxing project and select Run Project.
- Observe the result in the Output window of the IDE. (Figure-1.23 below)
int Value of iObj is: 22 float Value of iObj is: 22.0 long Value of iObj is: 22 double Value of iObj is: 22.0 |
Figure-1.23: Result
Summary
Exercise 2: Enhanced For loop
(2.1) Example wihtout using enhanced For loop
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects.
- Click Next.
- Under Name and Location pane, for the Project Name field, type in NotUsingEnhancedForLoop as project name.
- For Create Main Class field, type in NotUsingEnhancedForLoop.
- Click Finish.
- Observe that NotUsingEnhancedForLoop project appears and IDE generated NotUsingEnhancedForLoop.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated NotUsingEnhancedForLoop.java as shown in Code-2.11 below. Study the code by paying special attention to the bold fonted parts.
import java.util.*;
public class NotUsingEnhancedForLoop { public static void main( String[] args ) { for ( Iterator i = v.iterator(); i.hasNext(); ) { String [] s = { for ( int i = 0; i < s.length; ++i ) { |
Code-2.11: NotUsingEnhancedForLoop.java
3. Build and run the project
- Right click NotUsingEnhancedForLoop project and select Run Project.
- Observe the result in the Output window of the IDE. (Figure-2.13 below)
Vector element is: Hello World Vector element is: 10 Vector element is: 11.0 Vector element is: 12 String array element is: Java 2 String array element is: Platform String array element is: Standard String array element is: Edition String array element is: 1.5 String array element is: is String array element is: the String array element is: latest String array element is: release String array element is: of String array element is: the String array element is: Java String array element is: Platform |
Figure-2.13: Result
(2.2) Example with using enhanced For loop
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects.
- Click Next.
- Under Name and Location pane, for the Project Name field, type in UsingEnhancedForLoop as project name.
- For Create Main Class field, type in UsingEnhancedForLoop.
- Click Finish.
- Observe that UsingEnhancedForLoop project appears and IDE generated UsingEnhancedForLoop.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated UsingEnhancedForLoop.java as shown in Code-2.21 below. Study the code by paying special attention to the bold fonted parts.
import java.util.*;
public class UsingEnhancedForLoop { public static void main( String[] args ) { Vector<Object> v = new Vector<Object>(); for ( Object o : v ) { String [] s = { for ( String i : s ) { } |
Code-2.21: UsingAutoBoxging.java
3. Build and run the project
- Right click UsingEnhancedForLoop project and select Run Project.
- Observe the result in the Output window of the IDE. (Figure-2.23 below)
Vector element is: Hello World Vector element is: 10 Vector element is: 11.0 Vector element is: 12 String array element is: Java 2 String array element is: Platform String array element is: Standard String array element is: Edition String array element is: 1.5 String array element is: is String array element is: the String array element is: latest String array element is: release String array element is: of String array element is: the String array element is: Java String array element is: Platform |
Figure-2.23: Result
Summary
In this lab exercise, you learned how to use the Enhanced For Loops of J2SE 5.0.
Exercise 3: Static imports
(3.1) Example without using static imports
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects.
- Click Next.
- Under Name and Location pane, for the Project Name field, type in NotUsingStaticImport as project name.
- For Create Main Class field, type in testpackage.NotUsingStaticImport.
- Click Finish.
- Observe that NotUsingStaticImport project appears and IDE generated NotUsingStaticImport.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated NotUsingStaticImport.java as shown in Code-3.11 below. Study the code by paying special attention to the bold fonted parts.
package testpackage;
public class NotUsingStaticImport{ public static void main( String[] args ) { System.out.println( “Here are the attributes of a employee who will be hired: ” ); } } |
Code-3.11: NotUsingStaticImport.java
3. Write EmpAttributes.java under testpackage package.
package testpackage;
public class EmpAttributes { public static final int MINSALARY = 50000; } |
Code-3.12: EmpAttributes.java
4. Build and run the project
- Right click NotUsingStaticImport project and select Run Project.
- Observe the result in the Output window of the IDE. (Figure-3.13 below)
Here are the attributes of a employee who will be hired: Minimum Salary is: 50000 Maximum Salary is: 70000 Max Vacation Days: 15 Max Raise Percentage: 10 |
Figure-3.13: Result
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in UsingStaticImport as project name.
- For Create Main Class field, type in testpackage.UsingStaticImport.
- Click Finish.
- Observe that UsingStaticImport project appears and IDE generated UsingStaticImport.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated UsingStaticImport.java as shown in Code-3.21 below. Study the code by paying special attention to the bold fonted parts.
The static import construct allows unqualified access to static members without inheriting from the type containing the static members. For example, you can say just MINSALARY instead of EmpAttribs.MINSALARY.
package testpackage;
import static testpackage.EmpAttributes.*; public class UsingStaticImport { public static void main( String[] args ) { System.out.println( “Here are the attributes of a employee who will be hired: ” ); } } |
Code-3.21: UsingStaticImport.java
3. Write EmpAttributes.java under testpackage package. This is the same code as you have written in the previous step.
package testpackage;
public class EmpAttributes { public static final int MINSALARY = 50000; } |
Code-3.12: EmpAttributes.java
4. Build and run the project
- Right click UsingStaticImport project and select Run Project.
- Observe the result in the Output window of the IDE. (Figure-3.23 below)
Here are the attributes of a employee who will be hired: Minimum Salary is: 50000 Maximum Salary is: 70000 Max Vacation Days: 15 Max Raise Percentage: 10 |
Figure-3.23: Result
Summary
Exercise 4: Variable arguments
Object[] arguments = { new Integer(7), new Date(), “a disturbance in the Force” }; String result = MessageFormat.format( |
It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs. So, for example, the MessageFormat.format method now has this declaration:
public static String format(String pattern, Object… arguments); |
The three periods after the final parameter’s type indicate that the final argument may be passed as an array or as a sequence of arguments. Varargs can be used only in the final argument position. Given the new varargs declaration for MessageFormat.format, the above invocation may be replaced by the following shorter and sweeter invocation:
String result = MessageFormat.format( “At {1,time} on {1,date}, there was {2} on planet ” + “{0,number,integer}.”, 7, new Date(), “a disturbance in the Force”); // varargs |
(4.1) Example wihtout using variable arguments
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in NotUsingVarArgs as project name.
- For Create Main Class field, type in NotUsingVarArgs.
- Click Finish.
- Observe that NotUsingVarArgs project appears and IDE generated NotUsingVarArgs.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated NotUsingVarArgs.java as shown in Code-4.11 below. Study the code by paying special attention to the bold fonted parts.
import java.util.Date; import java.text.MessageFormat; import java.util.*; public class NotUsingVarArgs { public String formatThis() { Object[] args = { return MessageFormat.format( “On {2}, a {0} destroyed {1} houses and caused {3} of damage”, public static void main( String[] args ) { NotUsingVarArgs v = new NotUsingVarArgs(); } |
Code-4.11: NotUsingVarArgs.java
3. Build and run the project
- Right click NotUsingVarArgs project and select Run Project.
- Observe the result in the Output window of the IDE. (Figure-4.13 below)
On 1/1/99 12:00 AM, a Hurricane destroyed 99 houses and caused 100,000,000 of damage |
Figure-4.13: Result
(4.2) Example with using variable arguments
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects.
- Click Next.
- Under Name and Location pane, for the Project Name field, type in UsingVarArgs as project name.
- For Create Main Class field, type in UsingVarArgs.
- Click Finish.
- Observe that UsingVarArgs project appears and IDE generated UsingVarArgs.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated UsingVarArgs.java as shown in Code-4.21 below. Study the code by paying special attention to the bold fonted parts.
import java.util.Date; import java.text.MessageFormat; import java.util.*; public class UsingVarArgs { public String formatThis() { return( MessageFormat.format( “On {2}, a {0} destroyed {1} houses and caused {3} of damage”, public static void main( String[] args ) { UsingVarArgs v = new UsingVarArgs(); } |
Code-4.21: UsingAutoBoxging.java
3. Build and run the project
- Right click UsingVarArgs project and select Run Project.
- Observe the result in the Output window of the IDE. (Figure-4.23 below)
On 1/1/99 12:00 AM, a Hurricane destroyed 99 houses and caused 100,000,000 of damage |
Figure-4.23: Result
Summary
Exercise 5: Type-safe enumerations
// int Enum Pattern – has severe problems! public static final int SEASON_WINTER = 0; public static final int SEASON_SPRING = 1; public static final int SEASON_SUMMER = 2; public static final int SEASON_FALL = 3; |
This pattern has several problems as following:
- Not typesafe – Since a season is just an int type, you can pass in any other int value where a season is required, or add two seasons together (which makes no sense).
- No namespace – You must prefix constants of an “int enum” with a string (in this case SEASON_) to avoid collisions with other int enum types.
- Brittleness – Because int enums are compile-time constants, they are compiled into an application that use them. If a new constant is added between two existing constants or the order is changed, the application must be recompiled. If it is not, it will still run, but its behavior will be undefined.
- Printed values are uninformative – Because they are just ints, if you print one out, all you get is a number, which tells you nothing about what it represents, or even what type it is.
It is possible to get around these problems by using the Typesafe Enum pattern (see Effective Java Item 21), but this pattern has its own problems: It is quite verbose, hence error prone, and its enum constants cannot be used in switch statements.
Type-safe Enumeration (enum) allows you to create enumerated types with arbitrary methods and fields. It provides all the benefits of the Typesafe Enum pattern (“Effective Java”, Item 21) without the verbosity and the error-proneness.
(5.1) Example “without” using Type-safe enumerations
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects.
- Click Next.
- Under Name and Location pane, for the Project Name field, type in NotUsingTypeSafeEnum as project name.
- For Create Main Class field, type in NotUsingTypeSafeEnum.
- Click Finish.
- Observe that NotUsingTypeSafeEnum project appears and IDE generated NotUsingTypeSafeEnum.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated NotUsingTypeSafeEnum.java as shown in Code-5.11 below. Study the code by paying special attention to the bold fonted parts.
class FootballScore {
public static final int EXTRAPOINT = 1; private int score; public FootballScore( int score ) { public FootballScore() { public int getScore() { } public class NotUsingTypeSafeEnum { public static void main( String[] args ) { FootballScore[] yourScores = { int mytotal = calcTotal( myScores ); System.out.println( ” My football team scored ” + mytotal ); if ( mytotal > yourtotal ) { } public static int calcTotal( FootballScore[] f ) { |
Code-5.11: NotUsingTypeSafeEnum.java
3. Build and run the project
- Right click NotUsingTypeSafeEnum project and select Run Project.
- Observe the result in the Output window of the IDE. (Figure-5.13 below)
My football team scored 26 Your football team scored 12 My Team Won! |
Figure-5.13: Result
(5.2) Example “with” using type-safe enumerations
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects.
- Click Next.
- Under Name and Location pane, for the Project Name field, type in UsingTypeSafeEnum as project name.
- For Create Main Class field, type in UsingTypeSafeEnum.
- Click Finish.
- Observe that UsingTypeSafeEnum project appears and IDE generated UsingTypeSafeEnum.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated UsingTypeSafeEnum.java as shown in Code-5.21 below. Study the code by paying special attention to the bold fonted parts.
public class UsingTypeSafeEnum {
// Note that FootballScore is now enum type FootballScore( int value ) { private final int score; public int score() { public static void main( String[] args ) { FootballScore[] myScores = { FootballScore[] yourScores = { int mytotal = calcTotal( myScores ); System.out.println( ” My football team scored ” + mytotal ); if ( mytotal > yourtotal ) { public static int calcTotal( FootballScore[] f ) { } |
Code-5.21: UsingAutoBoxging.java
3. Build and run the project
- Right click UsingTypeSafeEnum project and select Run Project.
- Observe the result in the Output window of the IDE. (Figure-5.23 below)
My football team scored 26 Your football team scored 12 My Team Won! |
Figure-5.23: Result
Summary
Homework exercise (for people who are taking Sang Shin’s “Java Programming online course”)
- Modify UsingTypeSafeEnum.java so that FootballScore enum type has extrapoint field (in addition to score field). Take a suggested code change as shown in H-01 below
public class UsingTypeSafeEnum {
// Note that FootballScore is now enum type FootballScore( int value, int extrapoint ) { // More code |
H-01: Modified UsingTypeSafeEnum.java
- Modify the logic of finding who wins between myScores and youScores by considering the values of both score and extrapoint fields (instead of just score field.)
- Zip file of the the MyUsingTypeSafeEnum NetBeans project. (Someone else should be able to open and run it as a NetBeans project.) You can use your favorite zip utility or you can use “jar” utility that comes with JDK as following.
- cd <parent directory that contains MyUsingTypeSafeEnum directory> (assuming you named your project as MyUsingTypeSafeEnum)
- jar cvf MyUsingTypeSafeEnum.zip MyUsingTypeSafeEnum (MyUsingTypeSafeEnum should contain nbproject directory)
- Captured output screen – name it as JavaIntro-javase5language.gif or JavaIntro-javase5language.jpg (or JavaIntro-javase5language.<whatver graphics format>)
- Any screen capture that shows that your program is working is good enough. No cosmetic polishment is required.
- If you decide to use different IDE other than NetBeans, the zip file should contain all the files that are needed for rebuilding the project.