Lab Exercises
- Exercise 1: Create an object instance of a built-in class using “new” keyword (20 minutes)
- Exercise 2: Static method and instance (non-static) method (20 minutes)
- Exercise 3: Pass by value and pass by reference parameter passing (20 minutes)
- Exercise 4: Scope of variables (20 minutes)
- Exercise 5: Type casting of primitive types and Wrapper class (20 minutes)
- Exercise 6: Comparing objects (20 minutes)
- Exercise 7: getClass() method and InstanceOf Operator (20 minutes)
- Homework Exercise (for people who are taking Sang Shin’s “Java Programming online course”)
Exercise 1: Create an object instance of a class using “new” keyword
(1.1) Create String object instances using “new” keyword
0. Start the NetBeans IDE if you have not done so.
1. Create a NetBeans project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select Java under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyClassAndObjectProject.
- For the Create Main Class field, enter ClassAndObject. (Figure-1.10 below)
- Click Finish.
Figure-1.10: Create a new project
- Observe that the MyClassAndObjectProject project node is created under Projects pane of the NetBeans IDE and IDE generated ClassAndObject.java is displayed in the editor window of the IDE.
2. Modify the IDE generated ClassAndObject.java as shown in Code-1.11. Study the code while paying special attention to the bold-fonted comments.
public class ClassAndObject {
public static void main(String[] args) { // Create an instance of a class by using a Java language keyword “new”. // String class a special class for which you can create an instance } } |
Code-1.11: ClassAndObject.java
3. Build and run the program
- Right click MyClassAndObjectProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-1.12 below)
value of strIntance1 = I am object instance of a String class value of strIntance2 = I am object instance of a String class |
Figure-1.12: Result of running the application
4. (For your own exercise – this is not a homework) Modify ClassAndObject.java as following.
- Create another object instance of String class using new keyword. Initialize it with the following value.
- “I am another object instance of String class”
- Display it using Sytem.out.println(..) method.
5. Build and run the program
- Right click MyClassAndObjectProject and select Run.
(1.2) Create Integer object instances using “new” keyword
public class ClassAndObject {
public static void main(String[] args) { // Create an instance of a class by using a Java language keyword “new”. // String class a special class for which you can create an instance // Create an object instance of Integer class // Create another object instance of Integer class } |
Code-2.21: Create an object instance of an Integer class
2. Build and run the program
- Right click MyClassAndObjectProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-2.12 below)
value of strIntance1 = I am object instance of a String class value of strIntance2 = I am object instance of a String class value of intInstance1 = 20 value of intInstance2 = 30 |
Figure-2.22: Result
3. (For your own exercise – this is not a homework) Modify ClassAndObject.java as following.
- Create another object instance of Long class using new keyword.
- Display it using Sytem.out.println(..) method.
4. Build and run the program
- Right click MyClassAndObjectProject and select Run.
Summary
In this exercise, you have learned how to create an object instance of built-in classes such as String and Integer by using new keyword.
Exercise 2: Static method and instance (non-static) methods
<Name of the class>.<Name of the static method> |
An example is
Integer.parseInt(“25”); // parseInt() is a static method of the Integer class |
A non-static (instance) method of class is called only through an object instance in the following form:
<Name of object instance of a class>.<name of the non-static method> |
An example is
String str1 = new String(“Hello”); // Create an object instance of String class char x = str1.charAt(0); // Call an instance method charAt() of String class through the object instance |
(2.1) Use static and non-static (instance) methods
1. Create a NetBeans project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select Java under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyStaticAndInstanceMethodsProject.
- For the Create Main Class field, enter StaticAndInstanceMethods. (Figure-1.10 below)
- Click Finish.
- Observe that the MyStaticAndInstanceMethodsProject project node is created under Projects pane of the NetBeans IDE and IDE generated StaticAndInstanceMethods.java is displayed in the editor window of the IDE.
2. Modify the IDE generated StaticAndInstanceMethods.java as shown in Code-2.11. Study the code by special attention to the bold-fonted comments.
public class StaticAndInstanceMethods {
public static void main(String[] args) { // Create two instances of String class // Invoke an instance method charAt() through an object instance of String class System.out.println(“The 3rd char of strInstance1 = ” + x); // Invoke an instance method equalsIgnoreCase(..) method // Invoke a static-method, valueOf (int i), of the String class // You already have used parseInt() static method of the Integer class in } } |
Code-2.11: StaticAndInstanceMethods.java
3. Build and run the program
- Right click MyStaticAndInstanceMethodsProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-2.12 below)
The 3rd char of strInstance1 = a The 2nd char of strInstance2 = i The 1st char of strInstance2 = L Do strInstance1 and strInstance2 have same string ignoring case? No value of strInstance4 = 23 value of ii = 34 |
Figure-2.12: Result of running the application
4. Modify StaticAndInstanceMethods.java as shown in Code-2.13. The code fragments that need to be added are highlighted in bold and blue-colored font. The new code added is expected to generate a compile error.
public class StaticAndInstanceMethods {
public static void main(String[] args) { // Create two instances of String class // Invoke an instance method charAt() through an object instance of String class System.out.println(“The 3rd char of strInstance1 = ” + x); // Invoke an instance method equalsIgnoreCase(..) method // Invoke a static-method, valueOf (int i), of the String class // You already have used parseInt() static method of the Integer class in // The following code will generate a compile error since you are trying to } } |
Code-2.13: Code that generates compile error.
5. Observe that the NetBeans shows the syntax error as shown in Figure-2.14 below. Take note “non-static method charAt(int) cannot be referenced from a static context” hint message.
Figure-2.14: Compile error is detected.
6. Take a look at the Javadoc of the charAt() method of the String class to verify that charAt() method is indeed a non-static (instance) method.
- Move your cursor over the charAt() method and right click it and select Show Javadoc. (Figure-2.15 below)
Figure-2.15: Display JavaDoc of the String
- Observe that the Javadoc of the charAt() method of the String class gets displayed in the default browser. (Figure-2.16 below)
- Verify that it is not a static method. (If it were, it should have a static modifier.)
Figure-2.16: Javadoc of the charAt() method.
7. (For your own exercise) Identify which bold-fonted methods of the Code-2.17 below are static methods and which ones are non-static methods.
// endsWith() method String str = “Hello”; System.out.println( str.endsWith( “slo” ) ); // forDIgit() method // floor() method // isDigit() method |
Code-2.17: Identify which methods are static methods and which methods are non-static methods
Solution: The solution to this exercise is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javabuiltinclasses/samples/MyStaticAndInstanceMethodsProject. You can just open it and run it.
Summary
In this exercise, you have built and run a Java application using NetBeans IDE.
Exercise 3: Pass by value & Pass by reference parameter passing
(3.1) Parameter passing via Pass by value
1. Create a NetBeans project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select Java under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyTestPassByValueProject.
- For the Create Main Class field, enter TestPassByValue.
- Click Finish.
- Observe that the MyTestPassByValueProject project node is created under Projects pane of the NetBeans IDE and IDE generated TestPassByValue.java is displayed in the editor window of the IDE.
- Modify the TestPassByValue.java as shown in Code-3.11 below.
- Study the code by special attention to the bold-fonted code.
public class TestPassByValue {
public static void main(String[] args) { // Print the value of i // Call method test, which is defined below // print the value of i. please note that i not changed // Another static method in the TestPassByValue class System.out.println(“start of the test method and j = ” + j); // change value of parameter i System.out.println(“end of the test method and j = ” + j); |
Code-3.11: Modified TestPassByValue.java
3. Build and run the program
- Right click MyTestPassByValueProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-3.12 below)
start of the main method and i = 10 start of the test method and j = 10 end of the test method and j = 33 end of the main method and i = 10 |
Figure-3.12: Result of running TestPassByValue program
Solution: The solution to this exercise is provided as ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it <LAB_UNZIPPED_DIRECTORY>/javabuiltinclasses/samples/MyTestPassByValueProject . You can just open and run it.
4. (For your own exercise) Modify TestPassByValue.java as following. Build and run the project.
- Pass the second primitive type parameter to the test(..) method – you can choose any primitive type parameter (such as long or boolean).
- Set the value of the second parameter before calling the test(..) method. And change the value of the passed parameter within the test(..) method as you did with the first parameter in Code-3.11 above.
- Modify the System.out.println(..) methods in the Code-3.11 above to display the values of both the first parameter and second parameter.
(3.2) Parameter passing via Pass by reference
1. Create a NetBeans project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select Java under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyTestPassByReferenceProject.
- For the Create Main Class field, enter TestPassByReference. (Figure-3.15 below)
- Click Finish.
- Observe that the MyTestPassByReferenceProject project node is created under Projects pane of the NetBeans IDE and IDE generated TestPassByReference.java is displayed in the editor window of the IDE.
public class TestPassByReference {
public static void main(String[] args) { System.out.println(“main: start”); // Create an array of integers and initialize // Print array values. The array should display System.out.println(“main: before calling the test method”); // Call test and pass references to array. System.out.println(“main: after calling the test method”); // Print array values again. It now should contain changed values. System.out.println(“main: end”); } // Another static method in the TestPassByReference class System.out.println(“test: start”); // change values of array System.out.println(“test: end”); |
Code-3.16: Modified TestPassByReference.java
3. Build and run the program
- Right click MyTestPassByReferenceProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-3.17 below)
main: start 10 11 12 main: before calling the test method test: start test: end main: after calling the test method 50 51 52 main: end |
Figure-3.17: Result of running MyTestPassByReferenceProject
Solution: The solution to this exercise is provided as ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it <LAB_UNZIPPED_DIRECTORY>/javabuiltinclasses/samples/MyTestPassByRefereneceProject. You can just open it and run it.
Exercise 4: Scope of Variables
- Build and run a Java program that excercises a scope of a variable
- Write a Java program that uses all three types of variables
(4.1) Build and run a Java program that exercises a scope of a variable
1. Create a NetBeans project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select Java under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyScopeOfVariableProject.
- For the Create Main Class field, enter ScopeOfVariable.
- Click Finish.
- Observe that the MyScopeOfVariableProject project node is created under Projects pane of the NetBeans IDE and IDE generated ScopeOfVariable.java is displayed in the editor window of the IDE.
public class ScopeOfVariable {
public static void main(String[] args) { int var1 = 10; if (var1 < 100){ // Access to var1 is allowed so no compile error. // Access to var2 is not allowed so compile error will be generated } |
Code-4.11: Modified ScopeOfVariable.java
3. Observe that there is a compile error. (Figure-4.12 below) This is expected because you are accessing the var2 variable scope is only within the closest { } and cannot be used outside of that scope.
Figure-4.12: Observe scope problem
4. Modify the ScopeOfVariable.java as shown in Code-5.13 below. The code fragments that need to be removed (commented out here) are highlighted in bold and red-colored font while the code fragments that need to be added are highlighted in bold and red-colored font.
public class ScopeOfVariable {
public static void main(String[] args) { int var1 = 10; if (var1 < 100){ // Access to var1 is allowed so no compile error. // Access to var2 is now allowed } |
Code-4.13: Modified ScopeOfVariable.java with correct scoping
5. Build and run the program
- Right click MyScopeOfVariableProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-5.14 below)
value of var1 = 10 value of var2 = 20 |
Figure-4.14: Result of running MyScopeOfVariableProject
Solution: The solution to this exercise is provided as ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javabuiltinclasses/samples/MyScopeOfVaraibleProject. You can just open it and run it.
(4.2) Write a Java program that declares three types of variables
In this step, you are going to declare the three types of variables, static variable, instance variable, and local variable. (I acknowlege that this is not probably the best example to show how these variables are used. We will try different exercise when we learn how to create your own class and the concept of a package.)
1. Create a NetBeans project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select Java under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyThreeVariablesTypesProject.
- For the Create Main Class field, enter ThreeVariablesTypes.
- Click Finish.
- Observe that the MyThreeVariablesTypesProject project node is created under Projects pane of the NetBeans IDE and IDE generated ThreeVariablesTypes.java is displayed in the editor window of the IDE.
2. Modify the IDE generated ThreeVariablesTypes.java as shown in Code-4.21 below. Study the code by special attention to the bold-fonted comments.
public class ThreeVariablesTypes {
// Example of static variable // Example of instance variable /** Creates a new instance of ThreeVariablesTypes */ /** } |
Code-4.20: ThreeVariablesTypes.java
3. Observe that instance variable cannot be referenced from a static context – the main() method is a static method. (Figure-4.21 below)
Figure-4.21: Three types of variables
4. Comment out the offending line and build and run the project.
Solution: The solution to this exercise is provided as ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javabuiltinclasses/samples/MyThreeVaraibleTypesProject. You can just open it and run it.
Exercise 5: Type casting of primitive types and Wrapper
(5.1) Casting primitive types
1. Create a NetBeans project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select Java under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyCastingPrimitivesProject.
- For the Create Main Class field, enter CastingPrimitives.
- Click Finish.
- Observe that the MyCastingPrimitivesProject project node is created under Projects pane of the NetBeans IDE and IDE generated CastingPrimitives.java is displayed in the editor window of the IDE.
public class CastingPrimitives {
public static void main(String[] args) { // Implicit casting example 1 // Implicit casting example 2 // Explicit casting example 1 // Explicit casting example 2 } |
Code-5.11: Modified CastingPrimitives.java
3. Build and run the program
- Right click MyCastingPrimitivesProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-5.12 below)
int 10 is implicitly casted to double 10.0 numInt1/numInt2 0 is implicitly casted to double 0.0 double 10.12 is explicitly casted to int 10 x/y 5.1 is explicitly casted to int 5 |
Figure-5.12: Result of running MyCastingPrimitivesProject
Solution: The solution to this exercise is provided as ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javabuiltinclasses/samples/MyCastingPrimitivesProject. You can just open it and run it.
4. (For your own exercise): Remove the explicit casting when you convert the type from double to int and observe the compile error.
(5.2) Converting primitives to Wrapper class objects and vice-versa
1. Open a NetBeans project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select Java under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyConvertingPrimitivesToWrappersProject.
- For the Create Main Class field, enter ConvertingPrimitivesToWrappers.
- Click Finish.
- Observe that the MyConvertingPrimitivesToWrappersProject project node is created under Projects pane of the NetBeans IDE and IDE generated ConvertingPrimitivesToWrappers.java is displayed in the editor window of the IDE.
public class ConvertingPrimitivesToWrappers {
public static void main(String[] args) { // Create Integer object instance // Convert Integer type into int primitive type using intValue() method // Using static method of the Integer wrapper class // Convert int primitive type into Integer type } |
Code-5.21: Modified ConvertingPrimitivesToWrappers.java
3. Build and run the program
- Right click MyConvertingPrimitivesToWrappersProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-6.22 below)
int newCount = 7801 int penn = 65000 Integer myInteger = 65000 |
Figure-5.22: Result of running MyConvertingPrimitivesToWrappersProject
Solution: The solution to this exercise is provided as ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javabuiltinclasses/samples/MyConvertingPrimitivesToWrappersProject. You can just open it and run it.
4. (For your own exercise) Modify ConvertingPrimitivesToWrappers.java as following. Build and run the project.
- Create a Long type variable and convert it into long primitive and display it
Exercise 6: Comparing objects
In this exercise, you will exercise the concept of comparing objects (object instances) using String class as an example.
(6.1) Build and run a Java program that compares objects
1. Create a NetBeans project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select Java under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyEqualsTestStringProject.
- For the Create Main Class field, enter EqualsTestString.
- Click Finish.
- Observe that the MyEqualsTestStringProject project node is created under Projects pane of the NetBeans IDE and IDE generated EqualsTestString.java is displayed in the editor window of the IDE.
public class EqualsTestString {
/** Creates a new instance of EqualsTestString */ /** // Declare two String type variables, str1 and str2 // Initialize the variables. Note that the variables contain // Display the values of the str1 and str2 variables // The “==” notation, when it is used with variables of reference types not // Check if str1 and str2 are the same object meaning if the two variables // Reinitialize str2 variable. It is now pointing to a new String type object instance. // Display the values of the str1 and str2 variables // Check if str1 and str2 are the same object meaning if the two variables // Check if str1 and str2 have the same vaule } |
Code-6.11: Modified EqualsTestString.java
3. Build and run the program
- Right click MyEqualsTestStringProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-6.12 below)
String1: Life is worth living… with Passion! String2: Life is worth living… with Passion! Same object? true String1: Life is worth living… with Passion! String2: Life is worth living… with Passion! Same object? false Same value? true |
Figure-6.12: Result of running MyEqualsTestStringProject
Solution: The solution to this exercise is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javabuiltinclasses/samples/MyEqualsTestStringProject. You can just open it and run it.
4. (For your own exercise) Write EqualsTestInteger.java as following.
- Compare object instances of Integer class using the similar testing code as in EqualsTestString.java above
- Build and run the project.
Exercise 7: getClass() method & instanceOf operator
(7.1) Build and run a Java program that compares objects
1. Create a NetBeans project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select Java under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyGetClassMethodProject.
- For the Create Main Class field, enter GetClassMethod.
- Click Finish.
- Observe that the MyGetClassMethodProject project node is created under Projects pane of the NetBeans IDE and IDE generated GetClassMethod.java is displayed in the editor window of the IDE.
public class GetClassMethod {
public static void main(String[] args) { // Create String object instance // Find out the class information of String object instance // The the String name of the Class object instance. // Create Integer object instance // Find out the class information of Integer object instance // The the String name of the Class object instance. } } |
Code-7.11: Modified GetClassMethod.java
3. Build and run the program
- Right click MyGetClassMethodProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-7.12 below)
Class of str1 object instance is class java.lang.String Class of str1 object instance is class java.lang.String Class of int1 object instance is class java.lang.Integer Class of int1 object instance is class java.lang.Integer |
Figure-7.12: Result of running MyGetClassMethodProject
4. (For your own exercise) Modify GetClassMethod.java as following. Build and run the project.
- Create an object instance of java.util.Date class and display the class information of it.
(7.2) Use “instanceof” operator
1. Create a NetBeans project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select Java under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyinstanceofOperatorProject.
- For the Create Main Class field, enter instanceofOperator.
- Click Finish.
- Observe that the MyinstanceofOperatorProject project node is created under Projects pane of the NetBeans IDE and IDE generated instanceofOperator.java is displayed in the editor window of the IDE.
public class instanceofOperator {
public static void main(String[] args) { // Create String object instance // Check if str1 is String type using instanceof operator. // Check if int1 is Integer type using instanceof operator. } |
Code-7.21: instanceofOperator.java
3. Take a look the Javadoc of the Integer class.
- Move your cursor on the Integer (in the editor window of the NetBeans) and select Show Javadoc. (Figure-7.22 below)
Figure-7.22: Show Javadoc of the Integer class
- Observe that Integer class has parent class called java.lang.Number, which in turn has a parent class called java.lang.Object. (Figure-7.23 below) This is why the testing of int1 instanceof Number returns true.
Figure-7.23: Javadoc of Integer class
3. Build and run the program
- Right click MyinstanceofOperatorProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-7.24 below)
str1 is String type: true str1 is Object type: true int1 is Integer type: true int1 is Object type: true int1 is Number type: true |
Figure-7.24: Result of running MyinstanceofOperatorProject
4. (For your own exercise) Add code to instanceOperator.java as following. Build and run the project.
- Create an object instance of Long class and display the boolean result of whether it is a type of Number, Object, and Long class itself.
Homework exercise (for people who are taking Sang Shin’s “Java Programming online course”)
- Receive the first names of your family members (between 3 to 6 members of your family) as command line arguments and create an array of String.
- Write a static method called generateNewName() as following:
- It receives the array of String as a parameter.
- It creates a new first name by taking the 2nd character of each String from the array
- Display the names that were enetered and newly generated name
- Zip file of the the MyOwnBuiltinClassesProject 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 MyOwnBuiltinClassesProject directory> (assuming you named your project as MyOwnBuiltinClassesProject)
- jar cvf MyOwnBuiltinClassesProject.zip MyOwnBuiltinClassesProject (MyOwnBuiltinClassesProject should contain nbproject directory)
- Captured output screen – name it as JavaIntro-javabuiltinclasses.gif orJavaIntro-javabuiltinclasses.jpg (or JavaIntro-javabuiltinclasses.<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.