Skip navigation

Introductory Programming In Java

Lab 1 Lab 2 Lab 3 Lab 4 Lab 5 Lab 6 Lab 7

Lab 3

Writing the code structurally

Objectives

Using methods to accomplish a complex task — Reusing methods in different tasks — Understanding pass-by-value property — Mastering a complicated logic

Exercise One

Write a program which will print out the integers from 1 to 20 along with their squares. Calculate the squares with the help of a separate method. (Remember, that for the same class method to be called from the main method, it must be declared static.) Try both incorrect (non-returning value) and correct (returning int) versions of the squaring method (as mentioned in the lectures, SquareInt.java). This exercise has an extension, check the bottom of the page.

Exercise Two

Our system of determining dates is known as the Gregorian Calendar. In the Gregorian Calendar, you can determine if a year is a leap year according to the following rules:

There were no leap years before 1582. The year is not a leap year unless: It is divisible by 4, then it is a leap year unless: It is divisible by 100 in which case it is not, unless: It is divisible by 400.

Write a method:

static boolean isLeapYear(int year)

which returns true if the year is a leap year, and false otherwise. Find someone else who has completed this exercise and test your method against theirs!

Further programming ideas

Let's return to the Exercise One. Test the pass-by-value property for the primitive types: try to use void squaring method first which act on the value of the class fields, and then make the method to take an integer parameter and return an integer value (actually, it's all done in SquareInt.java program). Test the pass-by-reference property for reference types: replace int with your own class, MyInteger, which haz an int val field for storing an integer value, a constructor, a setValue(int i) method which can be used to change the value of val to the value passed as the parameter. Modify the original program for printing the squares which uses MyInteger objects and the (properly modified) squaring method, so it all works correctly. BTW, the standard Integer class does not have the method for (re-)setting the int value, and to call the constructor would not be right since we are meant to work with the same object. Hence the need to write our own class.

Lab 1 Lab 2 Lab 3 Lab 4 Lab 5 Lab 6 Lab 7

Updated:  Tue 14 May 2013 01:03:20 EST Responsible Officer:   JavaScript must be enabled to display this email address. Page Contact:   Course Webmaster