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.
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ą!
On your laptop or at home, on Windows operating system, this means using the start menu, selecting the 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
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”).
The result of your println statement can be seen in the command window. Here, java is the “Java Virtual Machine”.
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.
When the Java Virtual Machine is instructed to execute your program,
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 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.
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?
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.
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”.
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.
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.
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.
Implement a class, called Combination, to store three integer values (ints).
then c1.equals(c2) is true but c1.equals(c3) is false;
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.
Create an implementation for the class DoorLock described below.
Hint: my implementation is approximately 40 lines long, not counting the blank lines.
Implement the class SecurityAgent described below.
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.
Valid values must be in the range 1 to 5;
Hint: my implementation is approximately 15 lines long, not counting the blank lines.
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:
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.
Which of the following statement best characterizes the above Java program:
Submit your answer on Blackboard Learn:
Last Modified: January 15, 2015