Programming in Java: What Is in This Chapter ?
Programming in Java: What Is in This Chapter ?
Programming in Java: What Is in This Chapter ?
Programming in Java
There is nothing magical about OOP. Programmers have been coding for years in traditional
top/down structured programming languages. So what is so great about OO-Programming ?
Well, OOP uses 3 main powerful concepts:
Inheritance
Encapsulation
Polymorphism
We will discuss these concepts later in the course once we are familiar with JAVA.
JAVA has become a basis for new technologies such as: Enterprise Java Beans (EJB’s),
Servlets and Java Server Pages (JSPs), etc. In addition, many packages have been added
which extend the language to provide special features:
• Java Media Framework (for video streaming, webcams, MP3 files, etc)
• Java 3D (for 3D graphics)
• Java Advanced Imaging (for image manipulation)
• Java Speech (for dictation systems and speech synthesis)
• Java FX (for graphics, web apps, charts/forms, etc..)
• J2ME (for mobile devices such as cell phones)
• Java Embedded (for embedding java into hardware to create smart devices)
JAVA is continually changing/growing. Each new release fixes bugs and adds features. New
technologies are continually being incorporated into JAVA. Many new packages are available.
Just take a look at the www.oracle.com/technetwork/java/index.html website for the latest
updates.
-3-
COMP1406 - Chapter 1 - Programming in JAVA Winter 2018
• architecture independence
o ideal for internet applications
o code written once, runs anywhere
o reduces cost $$$
• dynamic
o code loaded only when needed
• memory managed
o automatic memory allocation / de-allocation
o garbage collector releases memory for unused objects
o simpler code & less debugging
• robust
o strongly typed
o automatic bounds checking
o no “pointers” (you will understand this in when you do C language programming)
Using the JAVA class libraries whenever possible is a good idea since:
We can actually create our own packages as well, but this will not be discussed in this course.
-4-
COMP1406 - Chapter 1 - Programming in JAVA Winter 2018
There are many IDE's that you can use to write JAVA code. Here are a few:
You may choose whatever you wish. HOWEVER ... YOU MUST hand in exported IntelliJ
projects for ALL of your assignments. So you should install and use IntelliJ for this course.
-5-
COMP1406 - Chapter 1 - Programming in JAVA Winter 2018
1. Writing: define your classes by writing what is called .java files (a.k.a. source code).
2. Compiling: send these .java files to the JAVA compiler, which will produce .class files
3. Running: send one of these .class files to the JAVA interpreter to run your program.
If there were errors during compiling (i.e., called "compile-time" errors), you must then fix
these problems in your program and then try compiling it again.
Just before running a program, JAVA uses a class loader to put the byte codes in the
computer's memory for all the classes that will be used by the program. If the program
produces errors when run (i.e., called "run-time" errors), then you must make changes to the
program and re-compile again.
-6-
COMP1406 - Chapter 1 - Programming in JAVA Winter 2018
All of your programs will consist of one or more files called classes. In JAVA, each time you
want to make any program, you need to define a class.
Here are a few points of interest in regards to ALL of the programs that you will write in this
course:
• The program must be saved in a file with the same name as the class name (spelled the
same exactly with upper/lower case letters and with a .java file extension). In this
case, the file must be called HelloWorldProgram.java.
• The first line beings with words public class and then is followed by the name of the
program (which must match the file name, except not including the .java extension).
The word public indicates that this will be a "publically visible" class definition that we
can run from anywhere. We will discuss this more later.
• The entire class is defined within the first opening brace { at the end of the first line and
the last closing brace } on the last line.
• The 2nd line (i.e., public static void main(String[] args) {) defines the starting place
for your program and will ALWAYS look exactly as shown. All JAVA programs start
running by calling this main() procedure which takes a String array as an incoming
parameter. This String array represents what are called "command-line-arguments"
which allows you to start the program with various parameters. However, we will not
use these parameters in the course and so we will not discuss it further.
• The 2nd last line will be a closing brace }.
So … ignoring the necessary "template" lines, the actual program consists of only one line:
System.out.println("Hello World"); which actually prints out the characters Hello World to
the screen. You may recall that this was a little simpler in Python since you simply did this
print ("Hello World")
So ... to summarize, every java program that you will write will have the following basic format:
-7-
COMP1406 - Chapter 1 - Programming in JAVA Winter 2018
public class {
public static void main(String[] args) {
;
;
;
}
}
Just remember that YOU get to pick the program name (e.g., MyProgram) which should
ALWAYS start with a capital letter. Also, your code MUST be stored in a file with the same
name (e.g., MyProgram.java). Then, you can add as many lines of code as you would like in
between the inner { } braces. You should ALWAYS line up ALL of your brackets using the
Tab key on the keyboard.
When you run your program, any output from the program will appear in a System console,
which is usually a pane in the IDE's window.
Later in the course, we will create our own windows. For now, however, we will simply use the
System console to display results. This will allow us to focus on understanding what is going
on "behind the scenes" of a windowed application. It is important that we first understand the
principles of Object-Oriented Programming.
Commenting Code:
Python JAVA
# single line comment // single line comment
-8-
COMP1406 - Chapter 1 - Programming in JAVA Winter 2018
Math Functions:
Python Java
min(a, b) Math.min(a, b)
max(a, b) Math.max(a, b)
round(a) Math.round(a)
pow(a, b) Math.pow(a, b)
sqrt(a) Math.sqrt(a)
abs(a) Math.abs(a)
sin(a) Math.sin(a)
cos(a) Math.cos(a)
tan(a) Math.tan(a)
degrees(r) Math.toDegrees(r)
radians(d) Math.toRadians(d)
random.random() Math.random()
Variables:
Python Java
Constants:
Python Java
math.pi Math.PI
Type Conversion:
Python Java
-9-
COMP1406 - Chapter 1 - Programming in JAVA Winter 2018
Arrays:
Python Java
FOR loops:
Python Java
WHILE loops:
Python Java
IF statements:
Python Java
if (grade >= 80) and (grade <=100): if ((grade >= 80) && (grade <=100))
print("Super!") System.out.println("Super!");
- 10 -
COMP1406 - Chapter 1 - Programming in JAVA Winter 2018
As the course continues, you will notice other differences between Python and JAVA.
However, the underlying programming concepts remain the same. As we do coding examples
throughout the course, you will get to know the some of the other intricate details of basic
JAVA syntax. Therefore, we will not discuss this any further at this point.
new Scanner(System.in).nextLine();
This line of code will wait for the user (i.e., you) to enter some text characters using the
keyboard. It actually waits until you press the Enter key. Then, it returns to you the
characters that you typed (not including the Enter key). You can then do something with the
characters, such as print them out.
Here is a simple program that asks users for their name and then says hello to them:
- 11 -
COMP1406 - Chapter 1 - Programming in JAVA Winter 2018
Notice the output from this program if the letters Mark are entered by the user (Note that the
blue text (i.e., 2nd line) was entered by the user and was not printed out by the program):
As you can see, the Scanner portion of the code gets the input from the user and then
combines the entered characters by preceding it with the "Hello, " string before printing to the
console on the second line.
Interestingly, we can also read in integer numbers from the keyboard as well by using the
nextInt() function instead of nextLine(). For example, consider this calculator program
that finds the average of three numbers entered by the user:
Here is the output when the CalculatorProgram runs with the numbers 34, 89 and 17 entered:
There is much more we can learn about the Scanner class. It allows for quite a bit of
flexibility in reading input. In place of nextInt(), we could have used any one of the following
functions to obtain the specific kind of data value that we would like to get from the user:
We will discuss the various data values in Chapter 2 of these notes. But for now,
Int/Short/Long/Byte return whole numbers, Float/Double return decimal numbers and Boolean
returns a true/false value.
- 12 -
COMP1406 - Chapter 1 - Programming in JAVA Winter 2018
Notice that there is no nextChar() function available. If you wanted to read a single character
from the keyboard (but don't forget that we still need to also press the Enter key), you could
use the following: nextLine().charAt(0). We will look more into this later when we discuss
String functions. It is important to use the correct function to get user input. For example, if
we were to enter 10, 20 into our program above, followed by some "junk" characters ... an
error will occur telling us that there was a problem with the input as follows:
java.util.InputMismatchException
...
at java.util.Scanner.nextInt(Unknown Source)
at CalculatorProgram.main(CalculatorProgram.java:11)
...
This is JAVA's way of telling us that something bad just happened. It is called an Exception.
We will discuss more about this later. For now, assume that valid integers are entered.
___________________________________________________________________________
Example:
Let us write a program that displays the following menu.
Luigi's Pizza
-------------------------------------------
S(SML) M(MED) L(LRG)
1. Cheese 5.00 7.50 10.00
2. Pepperoni 5.75 8.63 11.50
3. Combination 6.50 9.75 13.00
4. Vegetarian 7.25 10.88 14.50
5. Meat Lovers 8.00 12.00 16.00
The program should then prompt the user for the type of pizza he/she wants to order (i.e., 1 to
5) and then the size of pizza 'S', 'M' or 'L'. Then the program should display the cost of the
pizza with 13% tax added.
To begin, we need to define a class to represent the program and display the menu:
We can then get the user input and store it into variables. We just need to add these lines
(making sure to put import java.util.Scanner; at the top of the program):
- 13 -
COMP1406 - Chapter 1 - Programming in JAVA Winter 2018
Annoying detail: Note that next() is used instead of nextLine(). That is because the previous call to nextInt() does not read
the leftover newline character. A call to nextLine() therefore, would read it and return an empty String which does not have a
character in it. Using next() will read just one token/value … not a whole sentence though. So it works in this case.
Otherwise, we would have to call keyboard.nextLine() after keyboard.nextInt() to read that leftover newline character.
Now that we have the kind and size, we can compute the total cost. Notice that the cost of a
small pizza increases by $0.75 as the kind of pizza increases. Also, you may notice that the
cost of a medium is 1.5 x the cost of a small and the cost of a large is 2 x a small. So we can
compute the cost of any pizza based on its kind and size by using a single mathematical
formula. Can you figure out the formula ?
And of course, we can then compute and display the cost before and after taxes. Here is the
completed program:
import java.util.Scanner;
- 14 -
COMP1406 - Chapter 1 - Programming in JAVA Winter 2018
The above program displays the price of the pizza quite poorly. For example, here is the
output of we wanted a Large Cheese pizza:
The cost of the pizza is: $5.0
The price with tax is: $5.6499999999999995
It would be nice to display money values with proper formatting (i.e., always with 2 decimal
places). The next section will cover this.
import java.util.Scanner;
- 15 -
COMP1406 - Chapter 1 - Programming in JAVA Winter 2018
Here is the output from running this program with a price of $35.99 and payment of $50:
Notice all of the decimal places. This is not pretty. Even worse …if you were to run the
program and enter a price of 8.85 and payment of 10, the output would be as follows:
The E-4 indicates that the decimal place should be moved 4 units to the left…so the resulting
change is actually -$0.0005003888607006957. While the above answers are correct, it would
be nice to display the numbers properly as numbers with 2 decimal places.
JAVA’s String class has a nice function called format() which will allow us to format a String in
almost any way that we want to. Consider (from our code above) replacing the change output
line to:
System.out.println("Change:$" + String.format("%,1.2f", change));
The String.format() always returns a String object with a format that we get to specify. In our
example, this String will represent the formatted change which is then printed out. Notice
that the function allows us to pass-in two parameters (i.e., two pieces of information separated
by a comma , character).
The first parameter is itself a String object that specifies how we want to format the resulting
String. The second parameter is the value that we want to format (usually a variable name).
Pay careful attention to the brackets. Clearly, change is the variable we want to format.
Notice the format string "%,1.2f". These characters have special meaning to JAVA. The %
character indicates that there will be a parameter after the format String (i.e., the change
variable). The 1.2f indicates to JAVA that we want it to display the change as a floating point
number which takes at least 1 character when displayed (including the decimal) and exactly 2
digits after the decimal. The , character indicates that we would like it to automatically display
commas in the money amount when necessary (e.g., $1,500,320.28).
- 16 -
COMP1406 - Chapter 1 - Programming in JAVA Winter 2018
import java.util.Scanner;
It is a bit weird to see a value of -0.00, but that is a result of the calculation. Can you think of a
way to adjust the change calculation of payment - total so that it eliminates the - sign ? Try it.
The String.format() can also be used to align text as well. For example, suppose that we
wanted our program to display a receipt instead of just the change. How could we display a
receipt in this format:
Product Price 35.99
Tax 4.68
-------------------------
Subtotal 40.67
Amount Tendered 50.00
=========================
Change Due 9.33
If you notice, the largest line of text is the “Amount Tendered” line which requires 15
characters. After that, the remaining spaces and money value take up 10 characters. We
can therefore see that each line of the receipt takes up 25 characters. We can then use the
following format string to print out a line of text:
- 17 -
COMP1406 - Chapter 1 - Programming in JAVA Winter 2018
Here, the %15s indicates that we want to display a string which we want to take up exactly 15
characters. The %10.2f then indicates that we want to display a float value with 2 decimal
places that takes up exactly 10 characters in total (including the decimal character). Notice
that we then pass in two parameters: which must be a String and a float value in that order
(these would likely be some variables from our program). We can then adjust our program to
use this new String format as follows …
import java.util.Scanner;
The result is the correct formatting that we wanted. Realize though that in the above code, we
could have also left out the formatting for the 15 character strings by manually entering the
necessary spaces:
- 18 -
COMP1406 - Chapter 1 - Programming in JAVA Winter 2018
There are many more format options that you can experiment with. Just make sure that you
supply the required number of parameters. That is, you need as many parameters as you
have % signs in your format string.
For example, the following code will produce a MissingFormatArgumentException since one of the
arguments (i.e., values) is missing (i.e., 4 % signs in the format string, but only 3 supplied
values:
Also, you should be careful not to miss-match types, otherwise an error may occur (i.e.,
IllegalFormatConversionException).
The next page shows a table of a few other format types that you may wish to use in the
future. You are not responsible for knowing or memorizing anything in that table ... it is just for
your own personal use.
Hopefully, you now feel confident enough to writing simple one-file JAVA programs to interact
with the user, perform some computations and solve some relatively simple problems. It
would be a VERY good idea to see if you can convert some of your simpler Python programs
into JAVA.
- 19 -
COMP1406 - Chapter 1 - Programming in JAVA Winter 2018
There are also various format flags that can be added after the % sign:
There are many options for specifying various formats including the formatting of Dates and Times, but
they will not be discussed any further here. Please look at the java documentation.
- 20 -