Description
Part I
Editing, compiling and running Java programs
Objectives
Learning the requirements for this course regarding assignments;
Becoming familiar with the programming environment.
1 Review of the main code conventions of Java
Take a few minutes to review the code conventions for the Java programming language. Refer to the
conventions when solving your assignments. Up to 20% of the assignments’ grades concerns the conventions
and the clarity of your code.
http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html (PDF)
http://www.eecs.uottawa.ca/~lucia/courses/ITI1121-15/assignments/directives.html
2 Compiling and executing a program from the command shell
You should clearly understand concepts such compiler, editor and Java Virtual Machine. Programming
environment, such as DrJava and Eclipse, integrate these components, therefore making the boundaries
between the components fuzzy.
Use your favorite editor or development environment (we recommend DrJava or Eclipse) and create a
simple “Hello World” program. A “Hello World” program simply consists of a main method that displays the
String “Hello World”. Name this class HelloWord. Consequently, the file will be named HelloWorld.java.
Open a command shell (a.k.a. command line interface). In the teaching laboratories, the procedure to
obtain a shell for running Java commands is simple. Go to the Start’ Menu, select the sub-menu ’All
Programs’, then submenu Programming’, and you will find an entry Java Cmd, launch this, and voilà!
Start -> All Programs -> Programming -> Java Cmd
Screen captures: PDF, XHTML
On your laptop or at home, on Windows operating system, this means using the start menu, selecting the
ITI 1121. Introduction to Computer Science II 2015-05-11, 13:15
http://www.site.uottawa.ca/~lucia/courses/ITI1121-15/labs/t01/index.html Page 2 of 8
option “Run”, and typing cmd (on Windows 7, you can use PowerShell). You will most likely need to set the
environment variable PATH for this.
Okay, back to the main subject. Change to the directory where the file HelloWorld.java has been created
(use the command cd followed by the path of that directory, the command dir lists the content of the current
directory, make sure that you can see your file).
Compile the program HelloWorld.java
> javac HelloWorld.java
the symbol “>” is not part of the command, this is simply the prompt, in all my examples. If there were
errors, fix them, and compile your program again. If the compilation is successful then you should see a new
file in that directory. Its name will be HelloWorld.class. The .class files contain “byte-code” programs akin
to the machine code for microprocessors.
In order to execute your program, type the following in your command window (making sure that the
current directory contains the file “HelloWorld.class”).
> java HelloWorld
Hello World!
The result of your println statement can be seen in the command window. Here, java is the “Java Virtual
Machine”.
3 Command line arguments
Reading data using the input/output system requires creating several objects, but also requires understanding
the Exceptions, which is the framework for handling error situations in Java. This will be introduced in the
lectures, but only once the Stacks have been presented.
In the mean time, there is an easy way to pass information to your programs. You have been instructed to
write your main methods using a signature, and return value, that looks something like this.
public static void main( String[] args );
When the Java Virtual Machine is instructed to execute your program,
> java HelloWorld
It looks for a public static method called main that has exactly that signature: public static void main(
String[] args ) Fine. But what exactly is this reference called args? First, this is a parameter so it is up to
you to select the name of the parameter, you can call it xxx if you want to. I prefer using the name args,
which is the customary way of naming this parameter in the Unix operating system. Now, what is it? It is
simply a reference to an array of String objects. Have you ever attempted to print its content? Write a new
program called Command containing a main method. It will be easier to see what is going on if your
program prints some information when it starts its execution and when it ends (the exact content of these
print statements is not important so be creative!). In between these two statements, using a loop to traverse
the array and print the content of each cell. Your program will be more informative if you print the elements
ITI 1121. Introduction to Computer Science II 2015-05-11, 13:15
http://www.site.uottawa.ca/~lucia/courses/ITI1121-15/labs/t01/index.html Page 3 of 8
of the array one per line. You might as well print the position of the element within the array. Here is the
result of my experiments.
> javac Command.java
> java Command bonjour true 1121 “java intro” bravo
Start of the program.
Argument 0 is bonjour
Argument 1 is true
Argument 2 is 1121
Argument 3 is java intro
Argument 4 is bravo
End of the program.
> java Command
Start of the program.
End of the program.
> java Command 1
Start of the program.
Argument 0 is 1
End of the program.
> java Command dude
Start of the program.
Argument 0 is dude
End of the program.
As you can see, the operating system has handed in to your program an array (of Strings) containing all the
arguments following the name of the class (here Command) on the command line. Quotes can be used for
grouping strings together, e.g. “java intro” above. The other important concept to understand is that all the
elements of the array are all String, although one element is spelled true, this is the String that contains the
letters t, r, u, e. Similarly, although 1121 is a number, in the above context, this is the String made of 1, 1, 2,
1. Hum, but what if you really wanted pass a number to your program? What would you do?
4 Data type conversion
Your teaching assistant will first lead a short discussion on implicit and explicit type casting, see you in bit …
Okay, welcome back. So, you now know that Java can perform certain type conversions automatically
(implicitly). It does it when it knows that no information will be lost, e.g. the content of an int variable can be
safely copied to a long since a long can be assigned any of the values of an int and many more. The mirror
operation, assigning the value of a variable of type long to a variable of type int, cannot be executed
automatically since some of the values of a long cannot be represented using the amount of space reserved
for an int.
Becoming effective at programming. Throughout the semester, several tips will be presented to help you
developing your programming skills. One of the most important skills is debugging. Initially, students tend to
spend quite a bit of time debugging their programs, sometimes looking at the wrong segments of their
program. We will have more to say about debugging strategies in the next laboratories, but for now we will
focus on the error messages. Understand and learn the error messages that are reported by the compiler. A
good way to do this is to create small test programs that cause the error. For instance, create a class called
Test that has a main method. In the main method, declare a variable of type int, then assign the value
Long.MAX_VALUE. This is the largest value for a Long, this must cause an error. Try this for yourself. See
what error message comes out.
ITI 1121. Introduction to Computer Science II 2015-05-11, 13:15
http://www.site.uottawa.ca/~lucia/courses/ITI1121-15/labs/t01/index.html Page 4 of 8
Sometimes, the logic of your program requires you to perform a type conversion. It must be done with
special precautions. Always guard a type casting with the proper test to ensure that the value is in the
proper range. When doing a type cast, you are relieving the compiler of one of its important duties, which is
to make sure that all the types of the sub-expressions are compatible. It is as if you were saying “I know what
I am doing, please allow me to store this value in that variable”.
long l;
…
if ( l >= Integer.MIN_VALUE && l <= Integer.MAX_VALUE ) {
int i = (int) l;
...
}
Type casting cannot be used for transforming a String into a number! Each primitive data type has a
corresponding “wrapper” class. This is a class that has a similar name, for instance, the wrapper class for an
int is called Integer (the classes, Double, Boolean, Character, etc. also exist). As the name “wrapper”
suggests, such class packages a value inside an object. Like this.
public class Integer {
private int value;
public Integer( int v ) {
value = v;
}
...
}
Later on, the idea of packaging a primitive value inside an object will be necessary (in the lectures related to
abstract data types). However, for now it is another aspect of the wrapper classes that is our focus. Each
“wrapper” class also provides a collection of methods that are related to its corresponding primitive type.
Why don’t you see for yourself.
Go to java.sun.com/javase/6/docs/api/overview-summary.html;
This is the documentation of the standard library for Java 6.0;
Go to the package lang (which is always implicitly imported into your program);
java.sun.com/javase/6/docs/api/java/lang/package-summary.html;
Scroll down a little bit, and visit the page for the class Integer;
http://java.sun.com/javase/6/docs/api/java/lang/Integer.html;
Now locate the method parseInt( String s );
Perhaps using the class Command as a starting point, write a new class, called Sum, that converts to integers
all the elements found on the command line, sums these numbers and prints the result.
> javac Sum.java
> java Sum 1 2 3 4 5
The sum is 15
Part II
Object oriented programming
ITI 1121. Introduction to Computer Science II 2015-05-11, 13:15
http://www.site.uottawa.ca/~lucia/courses/ITI1121-15/labs/t01/index.html Page 5 of 8
Implementing simple classes;
Creating associations between classes;
Explore further the notion of encapsulation.
5 Combination
Implement a class, called Combination, to store three integer values (ints).
1. declare the necessary instance variables to store the three integer values;
2. create a constructor, public Combination(int first, int second, int third), to initialize the
values of this object.
3. implement the instance method public boolean equals(Combination other), such that equals
return true if other contains the same values, in the same order, as this Combination; the order is
defined by the order of the parameters of the constructor, given the following,
Combination c1;
c1 = new Combination( 1, 2, 3 );
Combination c2;
c2 = new Combination( 1, 2, 3 );
Combination c3;
c3 = new Combination( 3, 2, 1 );
then c1.equals(c2) is true but c1.equals(c3) is false;
4. finally, implement the method public String toString(), to return a String representation of this
object, where the first, second and third values are concatenated and separated by “:” symbols. E.g.
Combination c1;
c1 = new Combination( 1, 2, 3 );
System.out.println( c1 );
displays “1:2:3”.
The interface of the class Combination consists therefore of its constructor, the method equals and the
method toString.
Ideally, the input data should be validated. In particular, all the values should be in the range 1 to 5.
However, since we do not yet have the tools to handle exceptional situations, we will assume (for now) that
all the input data are valid!
Hint: my implementation is approximately 20 lines long, not counting blank lines. This is not a contest to
write the shortest class declaration. I am providing this information so that you can evaluate the relative
complexity of the tasks.
6 DoorLock
Create an implementation for the class DoorLock described below.
1. declare an integer constant, called MAX_NUMBER_OF_ATTEMPTS, that you will initialize to the value 3;
2. instance variables. The class DoorLock must have the necessary instance variables to i) store an object
of the class Combination, ii) to represent the property of being opened or closed, iii) to represent its
ITI 1121. Introduction to Computer Science II 2015-05-11, 13:15
http://www.site.uottawa.ca/~lucia/courses/ITI1121-15/labs/t01/index.html Page 6 of 8
activation state (the door lock is activated or deactivated), and iv) to count the number of unsuccessful
attempts at opening the door;
3. the class has a single constructor, DoorLock( Combination combination ), which initializes this
instance with a combination. When a door lock is first created, the door lock is closed. Also, when the
object is first created, it is activated and the number of failed attempts at opening it should be zero;
4. implement the instance method public boolean isOpen() that returns true if this door lock is
currently opened and false otherwise;
5. implement the instance method public boolean isActivated() that returns true if this door lock is
currently activated and false otherwise.
6. implement the instance method public void activate( Combination c ) that sets the instance
variable “activated” to true if the parameter c is “equals” to the combination of this object;
7. finally, implement the instance method public boolean open( Combination combination ) such
that i) an attempt is made at opening this door lock only if this door lock is activated, ii) if the
parameter combination is “equals” to the combination of this door lock, set the state of the door to be
open, and the number of failed attempts should be reset to zero, ii) otherwise, i.e. if the wrong
Combination was supplied, the number of failed attempts should be incremented by one, iii) if the
number of failed attempts reaches MAX_NUMBER_OF_ATTEMPTS, this door lock should be deactivated.
Hint: my implementation is approximately 40 lines long, not counting the blank lines.
7 SecurityAgent (if time allows)
Implement the class SecurityAgent described below.
1. instance variables. A security agent is responsible for a particular door lock. Declare the necessary
instance variables such that a SecurityAgent i) remembers (stores) a Combination and ii) has access
to this particular DoorLock, i.e. maintains a reference to a DoorLock object;
2. implement a constructor with no parameter such that when a new SecurityAgent is created i) it creates
a new Combination and stores it, ii) it creates a new DoorLock with this saved Combination. For the
sake of simplicity, you may decide to always use the same combination:
Combination secret;
secret = new Combination( 1, 2, 3);
if secret is the name of the instance variable that is used to remember the Combination. Or, you can
let your SecurityAgents use their imagination, so that each SecurityAgent has a new Combination
that it only knows.
int first = (int) ( Math.random()*5 ) + 1;
int second = (int) ( Math.random()*5 ) + 1;
int third = (int) ( Math.random()*5 ) + 1;
secret = new Combination( first, second, third );
Valid values must be in the range 1 to 5;
3. implement the instance method public DoorLock getDoorLock() that returns a reference to the
saved DoorLock;
4. implement the instance method public void activateDoorLock() that simply reactivates the
particular DoorLock that this SecurityAgent is responsible for, with the saved secret Combination.
ITI 1121. Introduction to Computer Science II 2015-05-11, 13:15
http://www.site.uottawa.ca/~lucia/courses/ITI1121-15/labs/t01/index.html Page 7 of 8
Hint: my implementation is approximately 15 lines long, not counting the blank lines.
Test
A Test class is provided with this laboratory. I suggest that you only use it when all your classes have been
successfully implemented and tested.
The Test class consists of a main method that i) creates a SecurityAgent called bob, it asks bob for an
access to the DoorLock that bob is in charge of, then it applies a “brute force” approach to unlock the door.
After three failures, it has to ask bob to re-activate the lock. When the lock has been unlocked, it prints the
combination of the lock, as well as the number of attempts that were necessary to open the door lock. Here
are examples of successful runs:
% java Test
Success!
Number of attemtps: 266
The combination is: 3:1:3
% java Test
Success!
Number of attemtps: 1
The combination is: 4:1:5
% java Test
Success!
Number of attemtps: 115
The combination is: 2:2:1
% java Test
Success!
Number of attemtps: 383
The combination is: 2:4:5
% java Test
Success!
Number of attemtps: 89
The combination is: 3:5:1
Warning: if the classes are not properly implemented this test can run forever, if you encounter such a
situation use Ctrl-c to kill the process.
Hint: build test classes for each of the three classes that you implement.
www.site.uottawa.ca/~turcotte/teaching/iti-1121/lectures/t01/Test.java
Part III
Quiz
Reference variables (1 mark)
ITI 1121. Introduction to Computer Science II 2015-05-11, 13:15
http://www.site.uottawa.ca/~lucia/courses/ITI1121-15/labs/t01/index.html Page 8 of 8
public class Quiz {
public static void main(String[] args) {
String s = null;
if (s.length() > 0) {
System.out.println(s);
} else {
System.out.println(“empty string”);
}
}
}
Which of the following statement best characterizes the above Java program:
1. The program runs without error, but displays nothing on the console.
2. Displays a message of the form “String@5e8fce95” on the console.
3. Displays “empty string” on the console.
4. Produces a compile-time error:
Quiz.java:4: variable s might not have been initialized
if (s.length() > 0) {
^
1 error
5. Produces a run-time error:
Exception in thread “main” java.lang.NullPointerException
at Quiz.main(Quiz.java:4)
Submit your answer on Blackboard Learn:
https://uottawa.blackboard.com/
Last Modified: January 15, 2015