Java
programming involves manipulating things called objects. The objects are either
primitive type objects (usually not called objects) or class objects. Some
primitive type are:
int
values are 1, 0 -37 etc and operations are + , - , *, / and %
examples 37 % 3 is 1, 37 / 3 is 12, 14 % 2 is 0 and 8 / 3 is 2
double
values are 1.0 0.0 -37.37 etc and operations are +, -, *, and /
char
values are 'a'. '6'. '$', '\n'. '\\' etc
boolean
values are true and false and operations are !, && and ||
The
assignment operator = means copy the right side to the left side. So
int x =
37;
means
copy 37 to x.
Class objects are defined by
classes. A class is a description of what data and operations a class
object can contain. The data in an object are called fields. The operations are
called methods. Objects are created by methods called constructors. So the
syntax for a class is:
class
ClassName {
fields;
constructors;
methods;
}
Classes
are data type classes which model information and main classes which manage
data type classes.
Fields
have the syntax: type variableName;
Examples
are int count; double balance; String word, BankAccount myAccount; etc.
The field names (count, balance, word etc) are called variables.
Methods
have the syntax:
return-type
methodName(parameters) {
...
}
where parameters
are inputs to the method,. Each parameter must have a name and must be
declared as to it's type. Return-types are
primitive types, class types or void. The return type is void if no value is
returned. Methods are called (executed) using the . notation
Example:
definition is
double deposit(double amount) {
balance =
balance + amount;
}
call is
myAccount.deposit(anAmount)
Constructors have the method
syntax but must have the same name as the class and do not have return types.
Constructors are called (executed) using the new operator only.
Example:
definition is
public BankAccount(double initialDeposit) {
balance =
initialDeposit;
}
call is
new BankAccount(1000);
Primitive
type variables contain values while class type variables contain addresses. When primitive type variables are declared they contain 0 (or
false). When class type variables are declared they contain the illegal
address 0 called the null pointer. Class variables must be assigned the address
of a class object before they can be used. This is typically done using a
constructor. For example:
ClassName
classVariable = new ClassName(...);
where
ClassName(...) is a constructor for the class. The ... refers to either no
parameters or parameters.
Examples:
String word = new String (“abcdef”);
BankAccount myAccount = new BankAccount(1000);
So,
a class is a description of what data and methods a class object can contain
and a class variable is the address of a class object.
Comparing
(relational) operators are == (equal) and != (not equal).
These operators compare the values of being compared. So using == to compare
primitive types compares their vales while using == to compare class type
variables compare addresses. The equals method is used
to compare complete objects.
Examples:
x == 37
x != y
word.equals(“abcdef”);
! word.equals(“abcdef”);
myAccount.equals(yourAccount);
Consider
the BankAccount class description
import javax.swing.JOptionPane;
public class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
balance =
initialBalance;
} // end constructor
public void deposit(double amount) {
balance
+= amount;
} // end deposit
public void withdraw(double amount) {
if(
balance - amount < 0.0 ) {
String
message = "Account Overdrawn. Transaction canceled!"
JOptionPane.showMessageDialog(null, message);
return;
} // end
if
balance -= amount;
} // end withdraw
public double getBalance() {
return
balance;
} // end getBalance
}
// end BankAccount
In
a main class we could have the following statements to make use of or test the
BankAccount class.
//
Construct a new BankAccount object and assign it's
address to myAccount
BankAccount
myAccount = new BankAccount(1000.0);
//
Construct a new BankAccount object and assign it's address to yourAccount
BankAccount yourAccount = new BankAccount(50);
//
deposit 2000 into myAccount. Methods are called using the .
notation myAccount.deposit(2000);
//
try to withdraw 100 from yourAccount. The JoptionPane window will
//
pop up with the error message
yourAccount.withdraw(100);
String
output = ”My balance is “ + myAccount.getBalance();
JOptionPane.showMessageDialog(null,output);
In
order to input information from users we use either the JOptionPane method showInputDialog(String prompt) or the Jlabel, JTextField GUI
combination. In either case the input is retrieved as a String object. Many
times the String object must be converted into a number. Java provides
“wrapper” classes for all of the primitive types. They are Integer, Double,
Character and Boolean. A static method is a method that can be called using the
class name. Some useful static methods from the wrapper classes are:
int parseInt(String s) from the Integer class
double parseDouble(String s) from the Double class
boolean isDigit(char ch) from the Character class
To
call any of these use the class name. For example
Integer.parseInt(“37”) returns the int value 37
Double.parseDouble(“37.37”) returns the double value 37.37 and
Character.isDigit('x') returns false
Selection
is done using the if and if/else statements. The if
statement syntax is
if( boolean-expression ) {
...
} // end if
and
if( boolean-expression ) {
...
} else {
...
} // end if
Examples:
if( x == 37 ) {
System.out.println(“x = “ + 37);
} // end if
if( balance - amount < 0.0 ) {
String
message = "Account Overdrawn. Transaction canceled!"
JOptionPane.showMessageDialog(null, message);
return;
} // end if
if ( word.equals(“abcdef” ) {
System.out.println(word + “ equals abcdef”);
} else {
System.out.println(word + “does not equal abcdef”);
} // end if
Repition
is done using the while statement or the for loop. The
syntax for the while is:
while( boolean-expression ) }
...
} // end while
The
semantics are: if the boolean-expression is true the ... statements are
executed and the boolean-expression is checked again and if true the ...
statements are executed and so on.
Syntax
for the for loop should be used as follows:
for( int i = 0; i < aValue; i++ ) {
...
} // end for
The
semantics are: the ... statements are executed for i = 0, 1,2
... aValue-1.
Examples:
int n = 33;
while( n > 1 ) {
System.out.println(n);
n = n /
2;
} // end while
This
segment will print:
33
16
8
4
2
for( int in = 0; in < 5; in++ ) {
System.out.println(in);
} // end for
This
will print
0
1
2
3
4
boolean isAllDigits(String input) {
int index
= 0;
while( index
< input.length() ) {
if( ! Character.isDigit(input.charAt(index) ) {
return
false;
} // end
if
index++;
} // end
while
return
true;
} // end isAllDigits
The
same example using a for loop is
boolean isAllDigits(String input) {
for( int
index = 0; index < input.length(); index++ ) {
if( ! Character.isDigit(input.charAt(index) ) {
return
false;
} // end
if
} // end
for
return
true;
} // end isAllDigits
Notice
a method with a return type must always return a value.
Some
String examples:
if
String s = “abcdef”;
then
s.substring(4) is “ef”
s.substring(2) is “cdef”
s.substring(1,5) is “bcde”
A
class can be extended to form another class using the keyword extends.
This is called inheritance. A class is extended if:
A
class is available that is similar to a class that is needed. So instead of
cutting and pasting the class is extended to fit the needs. The advantage over
cutting and pasting is that the available class is assumed to be correct so
only the extensions need to be tested.
Some
classes have some identical parts and some that are different. A class or interface
(an interface has only method names and descriptions) can be created
with the identical parts and then can be extended to form the other classes.
Extended
classes are called subclasses and the original class from which they are
extended is called the superclass. Non-private fields
and methods of the superclass are automatically available in the subclasses. So
a subclass consists of fields and methods of the super class, methods of the
superclass that have been redefined, new fields and methods available
only in the subclass and constructors (the first line of a subclass constructor
must be an implicit or explicit call to a super class constructor, called only
by the keyword super).
Superclass
Rules:
A
superclass variable can be assigned (the address of) an object of any of its
subclasses.
A
superclass variable can only access methods defined in the superclass even if
is as assigned an object of a subclass.
If a
superclass variable calls a method that is redefined then the redefined method
from the subclass is called.
A
superclass variable can be cast to any of its subclasses
Interface
Rules:
An
interface variable can be assigned an object of any implementing class
An
interface variable can only access methods defined in the interface even if is
as assigned an object of an implementing class.
An
interface variable can be cast to any non-final class.
A
polymorphic variable is one that can be assigned objects of different
classes (poly) and if the same method is defined in the different
classes chooses the method from the class it was assigned (morph). From
Superclass Rules 1(poly) and 3(morph) a superclass variable is a polymorphic
variable. This concept is called polymorphism.
Java
has a class named Object. Object is a “generic” class. Object has methods
boolean equals(Object x) and String toString()
among
some others. Object is the superclass of all classes in Java. So every class in
Java extends the class Object. The extends
keyword is implicit.
The
Superclass Rules applied to class Object are:
An
Object variable can be assigned an object of any class.
An
Object variable can access only methods defines in class Object (for example
equals and toString).
If an
Object variable calls equals or toString and they have been redefined the the
redefined equals or toString is called.
An
Object variable can be cast to any class.
All
declared parameters (inputs) to methods are local variables to the method and
are assigned the value of the corresponding parameter when the method is
called. So if void someMethod(String s, int x) is the
definition of a method and someMethod(“abcd”,37) is the call then s is assigned
“abcd” and x is assigned 37. Anytime someMethod is called the first parameter
must be a String or a subclass of String since it will be assigned to s. This
also means that no variable’s value can be changed by a call to a method. For
primitive types this means the actual value cannot be changed and for class
type variables this means that the address of the class object cannot be
changed.
Some
ArrayList examples:
The ArrayList class has methods
boolean add(Object x), int size(), and Object get(int
index) (among many others)
Since the parameter type of the add method is Object and class object can be
added to an ArrayList. For example;
ArrayList list = new ArrayList();
list.add(“abcde”);
list.add(new Integer(37);
list.add(new BankAccount(1000));
list.add(new Wallet(100));
for( int I = 0; I < list.size(); i++ ) [
System.out.println(list.get(i).toString());
} // end for
are valid statements. Note that in the for loop case
list.get(0).toString() calls the toString method from the class
String
list.get(1).toString() calls the toString method from the class
Integer
list.get(2).toString() calls the toString method from the class
Object (toString was not redefined in the class BankAccount)
list.get(3).toString() calls the toString method from the class
Wallet
(again this is polymorphism)
and list.size() is 4.
Since the ArrayList method get returns an Object
variable, it must be cast back to the class type that it was assigned if a
method from that class is called.
For example:
list,get(0).length() is NOT correct; use
((String)list.get(0)).length()
list.get(2).deposit(500)
is NOT correct; use ((BankAccount)list.get(2)).deposit(500);