Lab Exercises
- Exercise 1: Create an object instance of a class using “new” keyword (30 minutes)
- Exercise 2: Static variables and static methods (30 minutes)
- Exercise 3: Overloading (20 minutes)
- Exercise 4: Constructors (20 minutes)
- Exercise 5: “this” reference (20 minutes)
- Exercise 6: Access modifiers (20 minutes)
- Homework Exercise (for people who are taking Sang Shin’s “Java Programming online course”)
Exercise 1: Create your own class
(1.1) Build and run an application that uses newly created StudentRecord class
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 General under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyStudentRecordExampleProject.
- For the Create Main Class field, enter StudentRecordExample. (Figure-1.10 below)
- Click Finish.
Figure-1.10: Create a new project
- Observe that the MyStudentRecordExampleProject project node is created under Projects pane of the NetBeans IDE and IDE generated StudentRecordExample.java is displayed in the editor window of the IDE.
- Right click MyStudentRecordExampleProject and select New->Java Class.
- Observe that the Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter StudentRecord. (Figure-1.11 below)
- Click Finish.
Figure-1.11: Create StudentRecord.java
- Observe that the IDE generated StudentRecord.java is displayed in the editor window.
- Modify the IDE generated StudentRecord.java as shown in Code-1.12 below. Study the code by paying special attention to the bold-fonted comments.
public class StudentRecord {
/** Creates a new instance of StudentRecord */ // Declare instance variables. // Declare static variables. /** /** /** /** /** // Instance methods public void setMathGrade(double mathGrade) { public double getEnglishGrade() { public void setEnglishGrade(double englishGrade) { public double getScienceGrade() { public void setScienceGrade(double scienceGrade) { |
Code-1.12: StudentRecord.java
3. Modify the IDE generated StudentRecordExample.java as shown in Code-1.13.
- Study the code while paying special attention to the bold-fonted comments.
- Observe that StudentRecordExample class uses StudentRecord class.
public class StudentRecordExample {
public static void main(String[] args) { // Create an object instance of StudentRecord class. // Increament the studentCount by invoking a static method. // Create another object instance of StudentRecord class. // Increament the studentCount by invoking a static method. // Create the 3rd object instance of StudentRecord class. // Increament the studentCount by invoking a static method. // Set the names of the students. // Print anna’s name. // Print number of students. } |
Code-1.13: StudentRecordExample.java
4. Build and run the program
- Right click MyStudentRecordExampleProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-1.12 below)
Name = Anna Student Count = 3 |
Figure-1.12: Result of running the application
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>/javacreateclass/samples/MyStudentRecordExampleProject. You can just open and run it.
5. (For your own exercise) Do make changes as following and build and run the application.
- Modify StudentRecordExample.java as following:
- Create another StudentRecord object using new keyword, call it myOwnRecord
- Call setName() method of the myOwnRecord object passing “myOwn” as the value to set
- Display the name of the myOwnRecord object
- Set Math grade of myOwnRecord object
- Set English grade of myOwnRecord object
- Set Science grade of myOwnRecord object
- Display the average grade of myOwnRecord object
Summary
In this exercise, you have learned how to create and use your own class called StudentRecord class using new keyword.
Exercise 2: Build and run Java applications that use static (class) variables and static methods
- Build and run an application that uses static variables (and instance variables)
- Build and run an application that uses static methods (and non-static methods)
(2.1) Build and run an application that uses static variables and instance variables
1. Create a NetBeans project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select General under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyStaticVariablesExampleProject.
- For the Create Main Class field, enter StaticVariablesExample. (Figure-2.11 below)
- Click Finish.
Figure-2.11:Create MyStaticVariablesProject project
- Observe that the MyStaticVariablesExampleProject project node is created under Projects pane of the NetBeans IDE and IDE generated StaticVariablesExample.java is displayed in the editor window of the IDE.
2. Write Variables.java.
- Right click MyStaticVariablesExampleProject and select New->Java Class.
- Observe that the Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter Variables. (Figure-2.12 below)
- Click Finish.
Figure-2.12: Create Variables.java
- Observe that the IDE generated Variables.java is displayed in the editor window.
- Modify the IDE generated Variables.java as shown in Code-2.13 below. The modification is to create a couple of static variables and a couple of instance variables.
public class Variables {
// Static variables // Instance variables } |
Code-2.13: Variables.java
3. Modify StaticVariablesExamples.java to access static and instance variables of Variables class as shown in Code-2.14 below.
public class StaticVariablesExample {
public static void main(String[] args) { // Access static variables of Variables class. // Access instance variables of Variables class. // The static variable can be accessed from an object instance. // The static variable can be accessed from multiple object instances. } |
Code-2.14: StaticVariablesExample.java
4. Build and run the program
- Right click MyStaticVariablesExampleProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-2.15 below)
Variables.staticintA = 10 Variables.staticStringB = I am static string Variables.staticStringB = Life is good! objectInstance1.instanceintA = 1 objectInstance2.instanceintA = 3 objectInstance1.staticintA = 10 objectInstance1.staticintA = 220 Variables.staticintA = 220 objectInstance1.staticintA = 550 objectInstance2.staticintA = 550 Variables.staticintA = 550 |
Figure-2.15: Result
5. Observe compile error when you try to access instance variable as if it is a static variable.
- Add the code fragment of Code-2.16 below to the StaticVariablesExample.java.
- Observe the compile error. (Figure-2.17 below)
- Remove the code fragment you just added to remove the compile errors.
Variables.instanceintA = 3; |
Code-2.16: Compile error
Figure-2.17: Compile error
Solution: The solutions to this exercise are provided as ready-to-open-and-run NetBeans projects as part of hands-on lab zip file. You can find them as <LAB_UNZIPPED_DIRECTORY>/javacreateclass/samples/MyStaticVariablesExampleProject and <LAB_UNZIPPED_DIRECTORY>/javacreateclass/samples/MyStaticMethodsExampleProject. You can just open and run them.
6. (For your own exercise) Modify StaticVariablesExample.java to display the addition of staticintA static variable and instanceintA instance variable.
(2.2) Build and run an application that uses static methods and non-static methods
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 General under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyStaticMethodsExampleProject.
- For the Create Main Class field, enter StaticMethodsExample.
- Click Finish.
- Observe that the MyStaticMethodsExampleProject project node is created under Projects pane of the NetBeans IDE and IDE generated StaticMethodsExample.java is displayed in the editor window of the IDE.
2. Write Methods.java.
- Right click MyStaticMethodsExampleProject and select New->Java Class.
- Observe that the Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter Methods.
- Click Finish.
- Observe that the IDE generated Methods.java is displayed in the editor window.
- Modify the IDE generated Methods.java as shown in Code-2.21 below. The modification is to create a couple of static and non-static methods.
public class Methods {
// Static variable // Static method // Anonymous static method. The things inside the anonymous // Non-static method |
Code-2.21: Methods.java
3. Modify StaticMethodsExamples.java to invoke static and non-static methods as shown in Code-2.22 below.
public class StaticMethodsExample {
public static void main(String[] args) { // Access a static variable of Demo class. Note that you don’t have to // Invoke a static method of Methods class. Note that you don’t have to // The static variable can be accessed from an object instance. // The static method can be invoked from an object instance. // The same static variable can be accessed from multiple instances. // Compile error } |
Code-2.22: StaticMethodsExamples.java
4. Build and run the program
- Right click MyStaticMethodsExampleProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-2.23 below)
Anonymous static method entered, a = 0 Anonymous static method exiting, a = 1 Methods.a = 1 staticMethod(5) entered d.a = 1 staticMethod(0) entered e.a = 1 Methods.a = 4 d.a = 4 e.a = 4 |
Figure-2.23: Result
5. Observe compile error when you try to invoke non-static method as if it is a static method.
- Add the code fragment of Code-2.24 below to the StaticMethodsExample.java.
Methods.myNonStaticMethod(3); |
Code-2.24: Compile error expected
- Observe the compile error. (Figure-2.25 below)
- Remove the code fragment you just added to remove the compile errors.
Figure-2.25: Compile error
Summary
In this exercise, you have built and run Java applications that use static variables and static methods.
Exercise 3: Overloading
(3.1) Use two overloaded methods to the StudentRecord class
public class StudentRecord {
// Declare instance variables. // Declare static variables. /** /** /** /** /** public double getMathGrade() { public void setMathGrade(double mathGrade) { public double getEnglishGrade() { public void setEnglishGrade(double englishGrade) { public double getScienceGrade() { public void setScienceGrade(double scienceGrade) { // Overloaded myprint(..) methods public void myprint(String name ){ public void myprint(String name, double averageGrade){ } |
Code-3.11: StaticAndInstanceMethods.java
3. Modify StudentRecoredExample.java as shown in Code-3.12 below. The code fragments that need to be added are highlighted in bold and blue-colored font.
public class StaticVariblesMethods {
public static void main(String[] args) { // Create an object instance of StudentRecord class. // Increament the studentCount by invoking a static method. // Create another object instance of StudentRecord class. // Increament the studentCount by invoking a static method. // Create the 3rd object instance of StudentRecord class. // Increament the studentCount by invoking a static method. // Set the names of the students. // Print anna’s name. // Print number of students. // Set Anna’s grades // Invoke overloaded methods } } |
Code-3.12: Call overloaded methods
4. Build and run the program
- Right click MyStudentRecordExampleProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-3.13 below)
Name = Anna Student Count = 3 First overloaded method: Nothing is passed on Second overloaded method: Name:Anna Third overloaded method: Name:Anna Average Grade:65.16666666666667 |
Figure-3.13: Result
5. (For your own exercise) Do make changes as following and build and run the applicaiton.
- Modify StudentRecord.java as following
- Add another overloaded myprint() method which takes the following three parameters
- name, grade average, student count
- Add another overloaded myprint() method which takes the following three parameters
- Modify StudentRecordExmaple.java as following
- Invoke the newly added myprint() method
Summary
In this exercise, you have exercises how to use overloaded methods.
Exercise 4: Constructors
(4.1) Exercise multiple construcors
1. Create a NetBeans project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select General under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyConstructorExampleProject.
- For the Create Main Class field, enter ConstructorExample.
- Click Finish.
- Observe that the MyConstructorExampleProject project node is created under Projects pane of the NetBeans IDE and IDE generated ConstructorExample.java is displayed in the editor window of the IDE.
- Right click MyConstructorExampleProject and select New->Java Class.
- Observe that the Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter StudentRecord.
- Click Finish.
- Observe that the IDE generated StudentRecord.java is displayed in the editor window.
- Modify the IDE generated StudentRecord.java as shown in Code-4.11 below. Note that change is to add multiple construcors to the StudentRecord class.
public class StudentRecord {
// Declare instance variables. // Declare static variables. // Default constructor // Constructor that gets single parameter // Constructor that gets two parameters // Constructor that gets three parameters // Constructor that gets four parameters /** /** /** /** /** // Instance methods public void setMathGrade(double mathGrade) { public double getEnglishGrade() { public void setEnglishGrade(double englishGrade) { public double getScienceGrade() { public void setScienceGrade(double scienceGrade) { |
Code-4.11: StudentRecord.java that has multiple constructors
3. Modify the IDE generated ConstructorExample.java as shown in Code-4.12.
- Study the code while paying special attention to the bold-fonted comments.
- Observe that ConstructorExample class uses StudentRecord class.
public class ConstructorExample {
public static void main(String[] args) { // Create an object instance of StudentRecord class. // Increament the studentCount by invoking a static method. // Create another object instance of StudentRecord class. // Increament the studentCount by invoking a static method. // Create the 3rd object instance of StudentRecord class. // Increament the studentCount by invoking a static method. // Print Cris’ name and average // Print number of students. } |
Code-4.12: ConstructorExample.java
4. Build and run the program
- Right click MyConstructorExampleProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-4.13 below)
Name = Cris Average = 48.916666666666664 Student Count = 3 |
Figure-4.13: Result
5. (For your own exercise) Modify StudentRecord.java and ConstructorExample.java as following. Build and run the project.
- Create another Constructor in the StudentRecord.java in which average is also passed as a parameter.
- Modify the ConstructorExample.java so that StudentRecord annaRecord object is created with the newly added Constructor.
(4.2) Chaining of contructors via this() method
1. Modify StuentRecord.java as shown in Code-4.20 below.
public class StudentRecord {
// Declare instance variables. // Declare static variables. // Default constructor // Constructor that gets single parameter // Constructor that gets two parameters // Constructor that gets three parameters // Constructor that gets four parameters /** /** /** /** /** // Instance methods public void setMathGrade(double mathGrade) { public double getEnglishGrade() { public void setEnglishGrade(double englishGrade) { public double getScienceGrade() { public void setScienceGrade(double scienceGrade) { |
Code-4.20: Modified StudentRecord.java
2. Build and run the program
- Right click MyConstructorExampleProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-4.21 below)
Name = Cris Average = 48.916666666666664 Student Count = 3 |
Figure-4.21: Result
3. (For your own exercise) Modify StudentRecord.java and ConstructorExample.java as following:
- Create another Constructor in the StudentRecord.java in which average is also passed as a parameter.
- Modify the ConstructorExample.java so that StudentRecord annaRecord object is created with the newly added Constructor.
Summary
In this exercise, you learned you can have overloaded methods in a class. You also learned how to invoke a particular overloaded method by passing different set of parameters.
Exercise 5: “this” reference
(5.1) “this” reference in method call
1. Create a NetBeans project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select General under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyThisReferenceExampleProject.
- For the Create Main Class field, enter ThisReferenceExample.
- Click Finish.
- Observe that the MyThisReferenceExampleProject project node is created under Projects pane of the NetBeans IDE and IDE generated ThisReferenceExample.java is displayed in the editor window of the IDE.
- Right click MyThisReferenceExampleProject and select New->Java Class.
- Observe that the Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter DummyClass.
- Click Finish.
- Observe that the IDE generated DummyClass.java is displayed in the editor window.
- Modify the IDE generated DummyClass.java as shown in Code-5.10 below.
public class DummyClass {
void mymethod1(){ // Note that mymethod2() and this.mymethod2() are the same thing. System.out.println(“s1 = ” + s1 + ” s2 = ” + s2); String mymethod2(String name){ } |
Code-5.10: DummyClass.java
3. Modify ThisReferenceExample.java as shown Code-5.11 below.
public class ThisReferenceExample {
public static void main(String[] args) { |
Code-5.11: ThisReferenceExample.java
4. Build and run the program
- Right click MyThisReferenceExampleProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-5.12 below)
s1 = Hello Sang Shin s2 = Hello Sang Shin |
Figure-5.12: Result
5. Modify DummyClass.java as shown in Code-5.13 below.
public class DummyClass {
void mymethod1(){ // Note that mymethod2() and this.mymethod2() are the same thing. System.out.println(“s1 = ” + s1 + ” s2 = ” + s2); String mymethod2(String name){ // Compile error – you cannot invoke instance method } |
Code-5.13: Compile error when a static method invokes instance method
6. Observe the compile error. (Figure-5.14 below)
Figure-5.14: Compile error
(5.2) “this” reference as a parameter
public class DummyClass {
void mymethod1(){ // Note that mymethod2() and this.mymethod2() are the same thing. System.out.println(“s1 = ” + s1 + ” s2 = ” + s2); // Pass the current object instance as a parameter String mymethod2(String name){ String mymethod3(Object o1){ } |
Code-5.15: Modified DummyClass.java
2. Build and run the program
- Right click MyThisReferenceExampleProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-5.17 below)
s1 = Hello Sang Shin s2 = Hello Sang Shin s3 = DummyClass |
Figure-5.17: Result
3. Modify DummyClass.java as shown in Code-5.18 below. The code fragments that need to be added are highlighted in bold and blue-colored font.
public class DummyClass {
String hello =”Hello”; void mymethod1(){ // Note that mymethod2() and this.mymethod2() are the same thing. System.out.println(“s1 = ” + s1 + ” s2 = ” + s2); // Pass the current object instance as a parameter s3 = this.mymethod3(this, this.bye); String mymethod2(String name){ String mymethod3(Object o1, String s){ } |
Code-5.18: Modifed DummyClass.java
4. Build and run the program
- Right click MyThisReferenceExampleProject and select Run.
- Observe the result in the Output window of the NetBeans IDE. (Figure-5.19 below)
s1 = Hello Sang Shin s2 = Hello Sang Shin s3 = Hello DummyClass s3 = Bye DummyClass |
Figure-5.19: Result
Summary
In this exercise, you learned how to use “this” reference.
Exercise 6: Access modifiers – private, protected, and public
(6.1) Exercise access modifiers within a same package
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select General under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyAccessModifierExampleProject. (Figure-6.10 below)
- For the Create Main Class field, leave it to the IDE generated value myaccessmodifierexampleProject.Main. This is going to generate Main class under myaccessmodifieexampleproject package.
- Click Finish.
Figure-6.10: Create a new project
2. Write DummyClass.java under myaccessmodifieexampleproject package.
- Right click MyAccessModifierExampleProject and select New->Java Class.
- Observe that the Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter DummyClass. (Figure-6.11 below)
- For the Package field, type in or choose myaccessmodifierexampleproject from the drop-down menu.
- Click Finish.
Figure-6.11: Create DummyClass
- Observe that the IDE generated DummyClass.java is displayed in the editor window.
- Modify the IDE generated DummyClass.java as shown in Code-6.12 below. Study the code by paying special attention to the bold-fonted comments.
package myaccessmodifierexampleproject;
public class DummyClass { // Private field. Can be accessed only within the // Protected field. Can be accessed only within // Public field. Can be accessed from anybody. // Default is protected // Private method. Can be accessed only within the // Protected method. Can be accessed only within // Public method. Can be accessed from anybody. // Default is protected. |
Code-6.12: DummyClass.java
3. Modify Main.java as shown in Code-6.13 below.
package myaccessmodifierexampleproject;
public class Main { /** Creates a new instance of Main */ public static void main(String[] args) { // Compiler error expected // No compile error expected // Compiler error expected // No compile error expected } |
Code-6.13: Modified Main.java
- Observe the compile errors. (Figure-6.14 below)
Figure-6.14: Observe the compile errors.
(6.2) Exercise access modifiers from a different package
- Right click Source Packages under MyAccessModifierExampleProject project node and select New->Java Package. (Figure-6.20 below)
Figure-6.20: Create a new Java package
- Observe that the New Java Package dialog box appears.
- For the Package Name field, enter mynewpackage.
- Click Finish.
Figure-6.21: Give a package name
- Observe that the mynewpackage package node appears.
2. Create a class under a new package. You are going to access fields and methods of DummyClass from this new class.
- Right click mynewpackage package node, and select New->Java Class. (Figure-6.22 below)
Figure-6.22: Create a new Java class under mynewpackage package
- Observe that the New Java Class dialog box appears.
- For Class Name field, type in DummyClass2.
- Click Finish.
Figure-6.23: Create DummyClass2
- Observe that IDE generated DummyClass2.java appears in the source editor window of NetBeans IDE.
- Modify DummyClass2.java as shown in Code-6.24 below.
package mynewpackage;
//Import DummyClass public class DummyClass2 { public DummyClass2() { DummyClass t = new DummyClass(); // Compiler error expected // No compile error expected } |
Code-6.24: DummyClass2.java
3. Observe the compile errors. (Figure-6.25 below)
Figure-6.25: Compile errors
Summary
In this exercise, you learned how to use access modifiers to constrain the access privilege between classes.
Homework exercise (for people who are taking Sang Shin’s “Java Programming online course”)
- Create a Student class as following:
- The Student class has StudentRecord class as an instance variable. Name it as studentRecord.
- You can use the StudentRecord class from the MyStudentRecordExampleProject above or you can create a new one – the only requirement is that it has to have at least one instance variable of its own.
- The Student class has studentId instance variable whose type is Integer type.
- Move the studentCount static variable from the StudentRecord class to Student class.
- The Student class has StudentRecord class as an instance variable. Name it as studentRecord.
- Rewrite main.java as following
- Create 3 instances of Student class and initialize them accordingly – use whatever initialization values that are appropriate.
- Display the information of each student including the student id, name.
- Display the studentCount.
- Zip file of the the MyOwnProject 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 MyOwnProject directory> (assuming you named your project as MyOwnProject)
- jar cvf MyOwnProject.zip MyOwnProject (MyOwnProject should contain nbproject directory)
- Captured output screen – name it as JavaIntro-javacreateclass.gif orJavaIntro-javacreateclass.jpg (or JavaIntro-javacreateclass.<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.