Java CIS 260 Notes Part 1
Java CIS 260 Notes Part 1
Fairly challenging
How to do well
Attend class regularly with the notes and have read the material
assigned for the week before the week starts
You have already paid $$$ for my office hours - USE THEM
Hardware
Computers are just much, much faster and somewhat more complex
versions of a calculator. All computers manipulate sequences of
binary numbers consisting of 0's and 1's. These sequences can either
represent instructions for the computer or data such as text, images,
sound, and numbers. The computer’s hardware focuses on the ability
to process (add, subtract, multiply, divide, compare and branch),
store (retrieve, save) and move (input and output) this data. Here
is a brief list of several major functional components that allow
this to happen.
Compilers can be either low level or high level. They are based on
a "easy" to learn language we use to write source code programs in.
The compiler then handles any preprocessing needed in later steps,
4
such as removing comments from source code. It then converts the
result into object code. This object code is linked with special
libraries and an executable image is formed. (Steps = edit,
preprocess, compile, link, load. . . and then run when ever you
want).
One advantage to a compiled language is that it is easier to
learn and use than machine/assembly language. It is also more
portable, large sections of C source code made on a Macintosh can be
compiled and run on a PC with a minimal amount of changes. And,
compiled languages can easily take advantage of the operating system
features, saving the programmer lots of work. On the other hand,
compiled code is only 30-75% (C is about 75%) efficient and the
programmer must go through several steps to get a working program.
Examples: Turbo PASCAL, C, C++, FORTRAN
4) It is re-usable
Ethics
Software Piracy
Privacy of Data
Problem Solving
Terminology
Deployment (Delivery) roll out the new(er) code and be sure to keep
backups of older code just in case you need to roll back your changes
Don’t do more than what was asked for UNTIL the basic code works
Don’t forget to get buy in for any changes to the design once
approved. Keep people in the loop
Documented well
OOP
Dynamic Binding is a nuts and bolts concept that goes hand and hand
with inheritance. While, not one of the prime concepts of OOP, it is
required to handle inheritance correctly. Essentially, if code
expects one object, it will also work with any inherited object (More
on this much later)
Events
12
Events are actions that can cause programmer changeable code to run.
Examples of events include a printer reporting out of paper, a user
clicking a mouse, each character entered in a text box, etc. If the
programmer does not over ride these actions, then they do whatever
they would normally do (usually very little). However, it is
possible to use inheritance to add code to events so that they can do
more (or less) then what is normally done
All Events are originally triggered by the OS. This in turn passes
the event objects to the Java Virtual Machine (JVM, more later). The
JVM periodically checks to see what events it has. If someone’s Java
program has some special event code that matches that event, it will
run that code
13
Java
Java supports safe computing. The JVM first checks Java code to be
sure that it can not do anything malicious before running it. This
is especially true of Java applets (small Java programs downloaded
off of web pages). This increases the safety of running Java
programs, but at the cost of increased start up times. The later
issue is one reason why there are very few web sites that have client
side executable Java content any more, despite the safety guarantee
Java has a variety OOP Structures are used to embody the key OOP
concepts we previously mentioned. The basic Java structures are
A Class is the basic plan for your objects that will make up your
Java programs. This is a structural container that holds a
description (blue print) of the field variables (the data) and the
methods (the code) that make up each object you will instantiation
(create). This process works very much like using the blue print for
a Ford Focus from which you can build any number of actual Focuses to
use.
The name of your class must also be the same as file name (not
counting the .java file extension) that stores it including all
capitalization. Note, if you have more than one class in a file the
other classes do not have to be so named
A class may also contain code in the form of methods. As for field
variables, a copy of each is created fro each object created for each
object of the class
16
Each object of a class will have its own copy of each method,
unless that method is declared static (more later)
Each object of a class will have its own copy of each field
variable, unless that field variable is declared static (more later)
Use the Java byte code compiler (javac) to convert your program
to byte code, or chose compile for your IDE
The JVM then loads the program byte codes into memory
The program’s byte codes are verified for security to make sure
your application does not do anything naughty
Use a true Java compiler such as the GNU Java Compiler (GCV –
http://gcc.gnu.org/java/ ) to convert your program directly to
19
native machine code
You can get an older version of Java off of the CD that comes with
the course book. However, a newer free version is located at
http://java.sun.com/j2se/1.4.2/download.html. Note that this is a
big download. Do it over night if you are a modem user (or go to a
friend’s house with broadband and burn a CD from him/her)
I do not recommend the IDE that comes on the CD. It is very slow,
difficult to use and quite buggy. To get a decent free IDE that
works on all Windows versions that I am aware of, try going to the
site http://www.jcreator.com/ and downloading the free version 2.50
LE. It is only a 1.8 meg download. A “Pro” version featuring
inteli-sense is about $30 and well worth it.
If you wish to use Java from the command line you will need to set
the Path Environment Variable. Under XP / 2000 this can be set in
control panel -> system -> advanced -> environment variables ->
system variables -> path. Add the following to the path to make it
look like the end of this line ( That assumes that is the version and
location where Java is installed for you – should be correct if you
downloaded from Sun’s site above and changed nothing during
installation )
// Class test
// Prints a message to the screen
// written by David Antolovich
class test
{
public static void main( String args[] )
{
System.out.println("Hello and welcome to CIS 260.");
} // end main routine
} // end class test
Every program will contain files with one (or more) classes each.
However, only one class of all files in a project can be defined as
public. This is an indicator to the computer that this class
contains the a starting code to use
21
Note that test and main() are a special case. The OS implicitly
and automatically instantiates an object from class test and runs its
main method by default. Every other object we want to create and
every other method we wish to use has to be done explicitly
We don not have to code all the methods we wish to use. If someone
else has made them, such as System.out.println(), then we can just
call them and use them
22
Variables
The Scope of variable affects where it can be seen. For now, assume
that we have two choices
Field variables have class wide scope and are declared and defined
outside of any method (but within the class). Such variables are
declared and defined once each time an object is instantiated from a
class. They are accessible to any method in the class and survive
until the object itself is terminated. All such variables must have
encapsulation
// Class test
// written by David Antolovich
} // end main
} // end othermethod
Types
Java supports several types of Variables and each type has its own
uses and limitations. Variables can take more or less memory to hold
and can also store different things. In general the more flexible or
complex a variable type, the slower it is to use. Types listed below
marked with * are the fastest to work with
25
Whole numbers are represented by numbers with no decimals or
special surrounding characters other than the – character. Example
literal values) 1 4 6 23 -45
Modifiers
final is used to indicate a variable can not have any other value
assigned to it after it is first declared. In essence these are
“constant” variables. One use of this is for such thing as defining
27
PI or some other global and unchanging value you may need in your
code
You may not name a variable after any reserved word or key word in
Java. A reserved word is word Java may use for itself. A keyword is
a word it currently uses.
Eaxmples) ( + main { - println int float .
No two variables in the same class and scope can have the same
name. Thus you could have a field level variable called x and a local
variable in each method of the class also called x. But, never two
field level variables called x or two local variables in a method
both called x
By Java tradition you pick names starting with a lower case letter
and then capitalize every word in the name. You may use modified
Hungarian notation if you wish
Examples) iSocialSecurityNumber, myVariable, x
// Class test
// declares and assigns to variables and prints results
// written by David Antolovich
Import
All imports must come first in our code, even before we start our
class declaration(s)
import must have the full . naming scheme to locate the appropriate
class.
Streams
An output stream works the just the reverse of the input stream.
Here we place things into the bin, and then OS will remove as much
information (usually all) as it wishes and send it to the appropriate
output device
The bins that streams use should never be confused with the actual
IO device itself. For example it is possible to send stuff to be
output and have the machine crash after we have completed adding
31
information to the bin, but before it actually gets written to the
output device
Output
\t indicates a tab
// Class test
// uses print and println and \
// written by David Antolovich
System.out.println("\n\n");
GUI Output can be done with a variety of widgets and is fairly easy
to do in Java. We will look at just the simplest message box to
start with and explore other GUI widgets later on in the course
// Class test
// creates a message to say hello
// written by David Antolovich
Input
Text Input is sadly a much more complex process than for output. We
need to deal with exceptions (events), import and instantiating
buffered reader objects and attaching them to System.in. To shorten
this I include a separate class that can be used to help retrieve
keyboard input from a text window.
import java.io.*;
message = stdin.readLine();
return(message);
} // method readtext
} // class DaveIO
35
// Test code
import javax.swing.JOptionPane; // imports JOptionPane
import java.io.*;
// say hi
JOptionPane.showMessageDialog( null, "Hello and welcome to Java."
);
GUI Input can be similarly to GUI output. We will look at just the
simplest input box to start with and explore other GUI widgets later
on in the course
// Class test
// creates a message box
// reads in some values by the user using an input box
// writes those values back to the screen
// written by David Antolovich
Operators
· Left Associative meaning the left hand side evaluates before the
right hand side
Basic Operators are all left associative and binary. They work only
on primitive literals and/or variables
· Multiplication *
· Subtraction -
intX = 2 % 5
38
intX = 0 % 5
intX = 17 % 5
iX = 4;
iY = ++iX + 3;
iX = 4;
iY = iX++ + 3;
iX = 6;
iY = --iX + 3;
iX = 6;
iY = iX-- + 3;
39
· unary + or – used to temporarily flip the sign of a primitive
variable’s value
fX = 6.0;
fY = -fX + 2.0;
Basic Logical Operators include <, >, <=, >= and are binary, left
associative and only work on primitives
! ( 5 < 3 )
3 == 4
· Not Equal !=, evaluates to true if both sides are NOT equal.
Binary, and usable for both primitive and reference types with the
same conditions as above
3 != 3
· Logical And, && means the expression is true if both sides are
true, this will stop evaluating (short circuit) if the left hand side
is false. & works the same way but does not short circuit
40
3 != 3 && 4 < 5
· Logical Or, ||, means the expression is true if either side is true
and it will stop evaluating if the left hand side is true (short
circuit). | works the same way but does not short circuit
3 > 2 || 4 < 7
Concatenation
// Class vartest
// shows use of + for concatenation
// written by David Antolovich
Precedence
( )
! + - (unary operators)
++ -- (pre increment / decrement )
* / %
+ -
<=, >=, <, >, ==, !=
&&, &, |, ||
=
++ -- post increment / decrement
Examples
iX = 3 + 3 * 3;
iX = ( 3 + 3 ) * 3;
2 == 4
5 != -5
42
ix = 3;
3 < 4 && ix++ < 5
2 != 4 | 7 < 4
Type Conversion
iX = 1;
fY = iX;
dZ = iX;
lX = iX;
iX = 1;
dZ = 3.2222;
iY = (int)dZ;
dZ = (int)3.2 + 2.3;
fX = (float)dZ;
String sAge;
Int iUsersAge;
sAge = “” + iUsersAge;
sAge = Integer.toString( iAge );
sAge = Double.toString( 13.2 );