Java
Quick Review
Conestoga College
©
P.Komisar version 1.2
Following is a
condensed review of Java fundamentals
which will serve
as a refresher as we approach the
visual world of Java programming.
First, visit the
documentation. We see the basic
structuring
that Java uses for it's libraries.
http://java.sun.com/j2se/1.6/docs/api/index.html
Visit any class,
for instance the String class. We
can see in the documentation the component parts
of of the packages. The base unit is the class. A
related structure is the interface of which there are
plenty as well. The class itself is composed of fields
constructors, methods and other inner classes.
Breakdown
of Java's Component Parts
packages
|
|__
sub-packages
|
|__
interfaces
|
|__
classes
|__ inner classes
|
|__ fields
|
|__ constructors
|
|__ methods
To review the
basic form Java classes take, we
look back at
HelloWorld. We notice it's components
are are enclosed in scopes created by pairs of
curly braces.
HelloWorld
class
HelloWorld
{
public static void main(String [ ] args)
{
System.out.println("Hello World");
}
}
- a class
- a main( ) method
- a println statement
Should we need
to pass a value in from the command
line, the String array represented by the 'args' variable
can be used.
Command Line Arguments
class HelloCommand
{
public static void
main(String [ ] args)
{
if (args.length<1){
System.out.println("Enter an
argumment");
return;
}
System.out.println("Command Line Argument: " + args[0]);
}
}
- passing arguments from the command line
Flow
Control
This is all the flow control
review you get!
if ( boolean ) { } else { }
for (int i =0; i
< 10 ; i ++) { }
//
look up the switch
We can add
fields to the class.
The following table shows the basic primitive types
that Java makes available to manage numerical and
character data.
Table showing the Basic Categories of Java
Primitives
Type |
Use |
boolean |
represents
truth values, true and false |
int,
long, byte, short |
Integral
Numbers { 1 , 2 , 3 } |
double,
float |
Real
( floating point ) Numbers { 1.1, 2.2,
3.3 } |
char |
represents
character data { 'A ' } |
Primitives
Following is
some code that shows the primitives
being used.
class
HelloPrimitives
{
static byte oneByte = 121;
static char letter = 'A';
static short twoBytes = -32000;
static int fourBytes = 2000000000;
static long eightBytes = 2000000000000L;
static float fourByteFloatingPoint = 2.13E3F;
static double eightByteFloatingPoint = 9.9E60;
public static void main(String [ ] args)
{
System.out.println("Primitive Examples");
System.out.println("byte Type: " + oneByte);
System.out.println("char Type: " + (int)letter );
// etc.
}
}
// Note the
one cast (int)letter
OUTPUT
java HelloPrimitives
Primitive Examples
byte Type: 121
char Type: 65
Notice we (cast ) the char value to an int. This yields
it's numeric value '65' rather than it's char value 'A'.
We could also return these values in methods.
Full
Form of the Method
[ opt_Modifier
]return_type
identifier(opt_ParameterList)[ opt_ThrowsClause
]{
/* statements */ }
identifier - a method
must have a legal identifier
return type - a
method
must have a return type, which is void if the methods returns nothing
round braces - a
method
has to have a pair of round braces.
Options
modifiers -a
method may have modifiers such as public or static associated with them.
parameter list - a method
may optionally specify a parameter list (aka argument list*)
throws clause -a method
may be declared showing it throws some Exception
statment block - If there
is no statement block the method is marked abstract and ends in a
semi-colon.
statements -a method may
be
defined with empty curly braces creating an empty method
Methods
class
HelloMethods
{
static long eightBytes = 2000000000000L;
static float fourByteFloatingPoint = 2.13E3F;
static double eightByteFloatingPoint = 9.9E60;
public static void main(String [ ] args)
{
double sum =
HelloMethods.addBigNumbersMethod(eightBytes, fourByteFloatingPoint);
System.out.println(sum);
}
static double addBigNumbersMethod(long one, float two){
return one
+ two;
}
}
OUTPUT
> java HelloMethods
1.999999991808E12
// promotion
A long and float were used in the method. The compiler
required a double be used as the numbers were promoted
to a double in the addition operation.
Constructors
We recall Java's object oriented nature and visit declaration
instantiation and assignment when we use constructors.
Remember constructors are like methods but have no
return types, implicitly returning the class object itself.
Following is a class with three different constructors.
In the main method each constructor is invoked.
class Shapes{
// constructor 1
Shapes (int x,
int y){
System.out.println ("Draw a point at (" + x + "," + y +")." );
}
// constructor 2
differentiated by number of arguments
Shapes( int x1, int
y1, int x2, int y2 ){
System.out.println
("Draw a line between (" + x1 + "," + y1 + ")
and (" + x2 + "," + y2 +")." );
}
public static void main(String[]args){
Shapes point = new
Shapes(21,34);
Shapes line = new
Shapes(11,22,33,44);
}
}
OUTPUT
java Shapes
Draw a point at (21,34).
Draw a line between (11,22) and (33,44).
Inheritance
//
super( )
Following we use super to invoke a parent constructor
and add some extra 'specialization' to the child extension
of the parent class.
Notice as well the use of the 'extends' keyword to create
an extension of the Shapes class.
// Shapes is
defined in the earlier example
class
TriShape extends Shapes{
TriShape( int
x1, int y1, int x2, int y2, int x3, int y3){
super(x1,x2,x2,y2);
System.out.println
("Draw another line between (" + x2 + "," + y2 + ") and (" + x3 +
"," + y3 +")." );
}
public static void main(String[]args){
new
TriShape(1,3,5,7,11,13);
}
}
Key
Modifiers & Keywords
Following is a
chart of all the Java keywords. JDK1.5.x is
a bit of a
watershed and has added some new keywords
and syntax to
the mix.
Breakdown of Java Keyword Based on
Category
// with Java 1.5 enum. asserts and
strictfp are quite recent
primitives |
modifiers |
control |
exceptions |
object oriented |
boolean |
private |
if |
try |
class |
byte |
protected |
else |
catch |
new |
short |
public |
for |
finally |
extends |
int |
static |
do |
throw |
implements |
long |
abstract |
while |
throws |
interface |
float |
final |
switch |
. |
this |
double |
synchronized |
case |
. |
super |
char |
native |
default |
// in methods |
instanceof |
. |
transient |
break |
return |
import |
. |
volatile |
continue |
void |
package |
Words reserved
for values |
true |
false |
null |
Words reserved but not used
|
goto |
const |
. |
Reserved words
that have been dropped |
widefp |
|
|
Keywords recently
added
|
asserts |
strictfp |
enum
|
// strictfp has moved from
reserved status to the keyword list
Operators
Following are Java's Operators in a table that
shows them in order of precedence.
Java Operators in Order of Precedence
Operator
Type |
Operator Symbols |
Precedence |
Braces, the Dot
operator |
( ) { } . |
highest |
Unary |
++ -- - + ! ~ (type cast) |
pre 16
post 15
~ ! 14
(cast) 13 |
Arithmetic |
* / %
+ - |
* / % 12
+ - 11 |
Shift |
<< >> >>> |
10 |
Comparison |
< <= >
>=
instanceof |
9 |
Equality |
== != |
8 |
Bitwise |
&
^ | |
&
7
^ 6
| 5 |
Short Circuit |
&& || |
&&
4
|| 3 |
Ternary |
? : |
2 |
Assignment
= or op=) |
=, *=, /=, %=, +=, -=, <<=,
>>>=, >>>=, &=, ^=, |= |
1
lowest |
Coffee Pot
rule for determining
Associativity //
higher # corresponds to higher precedence
left
associative operators |
precedence |
right
associative operators |
precedence |
post-increment &
decrement |
15 |
++ pre-increment &
decrement |
16 |
* / %
multiplicative |
12 |
~ inversion (bit
flip) |
14 |
+ - add and
subtract |
11 |
! logical not |
14 |
<<
>> >>> bit wise shift |
10 |
- + arithmetic negative
& positive |
14 |
instanceof
< <=
> >= relational |
9 |
type conversion (cast) |
13 |
==
!=
equality |
8 |
. |
. |
& bitwise
AND |
7 |
. |
. |
^ exclusive OR |
6 |
. |
. |
| bitwise
(inclusive) OR |
5 |
. |
. |
&& conditional
AND |
4 |
tertiary (conditional)
operator |
2 |
| |
conditional OR |
3 |
assignment = *= /= %= +=
-=
<<= >>= >>>= &=
^= |= |
1 |
Exceptions
Recall Java has
it's own error handling code.
Following is some code that shows 'try, catch and
finally' blocks as well as the 'throw' keyword in
action.
class
MotorFailure extends Exception{
MotorFailure(String cause){
super(cause);
}
}
// should really add the no-args constructor as well
// now in case
someone extends this class
class
MotorTest{
public static void
main(String[]args){
try {
throw new
MotorFailure("blown gasket");
}
catch(MotorFailure mf){
System.out.println( mf.getMessage( ));
}
finally { System.out.println( "Call for service!" ); }
}
}
Arrays
Java has
three array forms, the literal form, the
classic version and the 'array creation expression.'
Instantiated
Form
Example int[]
numbers = new int [10];
Literal
Arrays
Example int[]
decimals = {1.1,2.2,3.3};
Array Creation
Expressions
Example char characters =
new char[]{ 't','o','p');
Recall the
following code with some important array
methods.
public static void main(String[]
args){
// a couple of String arrays are created
by different
techniques
String[] src = new
String[]{ "Left", "Right","Young", "Old", "Downtown", "Uptown"};
String[] dst = new String[]{ "London
","Glasgow", "New", "York"};
// the method arraycopy() is
demonstrated
System.arraycopy( src,
3, dst, 0, 2);
System.out.println(
dst[0] + " " + dst[1] + " " + dst[2] + " " + dst[3] );
// the clone() method is used to
duplicate the
dst array
String[] twin= (
String[] ) dst.clone( );
for(int i=0;
i <twin.length; i++)
System.out.print( twin[i] + " " );
// this is yet another loop
preview
}
}
New
in JDK 1.5
An example of the 'enum' data type, really a very new
feature in
Java. We now
have a data type that can live
outside the class.
//
the cat is
out of the bag now!
Enums // for reference
from JDK 1.5 docs
http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html
public enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6),
MARS (6.421e+23, 3.3972e6),
JUPITER (1.9e+27, 7.1492e7),
SATURN (5.688e+26, 6.0268e7),
URANUS (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7),
PLUTO (1.27e+22, 1.137e6);
private final double mass; // in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double mass() { return mass; }
public double radius() { return radius; }
// universal gravitational constant (m3 kg-1 s-2)
public static final double G = 6.67300E-11;
public double surfaceGravity() {
return G * mass / (radius *
radius);
}
public double surfaceWeight(double otherMass) {
return otherMass *
surfaceGravity();
}
// a
main( ) method is added to reference some
// of the defined data You would probably reference
// the enum from another class but the enum is happy
// to host the main( ) method! .ed
public static void main(String[] args){
System.out.println(Planet.MERCURY.mass());
System.out.println(Planet.EARTH.radius());
System.out.println(Planet.JUPITER.surfaceGravity());
}
}
|
Assignment
Create a Java
class that:
1) Takes an
argument from the command line and prints it to console.
2) Declares two primtive types.
3) Creates a method that takes these primitives as arguments and
multiplies them.
The result is printed to console ( from the method or
as a return
type. )
4) Has two overloaded constructors.
a ) One constructor takes a String and prints it to console.
b) The other takes a String and a double and prints them to console.
5) Create an array and use a for loop to print the values to console.