Java Notes
Java Notes
However, one of the main selling points of Java is that it can actually be used on any
computer. All that the computer needs is an interpreter for Java bytecode. Such an
interpreter simulates the Java virtual machine in the same way that Virtual PC simulates
a PC computer.
Of course, a different Java bytecode interpreter is needed for each type of computer,
but once a computer has a Java bytecode interpreter; it can run any Java bytecode
program. And the same Java bytecode program can be run on any computer that has
such an interpreter.
This is one of the essential features of Java: the same compiled program can be run on
many different types of computers.
Object-Oriented Programming
What's going on under the hood is none of your business. (And, if you casually try
to make it your business, plan to face an amused mechanic who will have to
straighten out your mess!)
But OOP is a lot more than just a way to hide the details of a program. To learn
about OOP, you need to understand three main concepts that are the backbone
of OOP. These concepts, which are covered in the following sections, are:
encapsulation, inheritance, and polymorphism.
If you want to print a document, in Procedural programming, we are concerned with the steps
involved for printing. In OOP, we are only concerned with how to communicate with a printer that
performs the printing job for us. All we want to know is the printer’s interface.
Encapsulation
One major difference between conventional structured programming and object-
oriented programming is a handy thing called encapsulation. Encapsulation
enables you to hide, inside the object, both the data fields and the methods that
act on that data. (In fact, data fields and methods are the two main elements of
an object in the Java programming language.)
After you do this, you can control access to the data, forcing programs to retrieve
or modify data only through the object's interface. In strict object-oriented
design, an object's data is always private to the object. Other parts of a program
should never have direct access to that data.
It seems that you could use another level of scope -one that would make your
data global to the functions that need it- but still prevent other functions from
gaining access. Encapsulation does just that. In an object, the encapsulated data
members are global to the object's methods, yet they are local to the object. They
are not global variables.
An object is just an instance of a data type. For example, when you declare a
variable of type int, you're creating an instance of the int data type. A class is like
a data type in that it is the blueprint upon which an object is based. When you
need a new object in a program, you create a class, which is a kind of template for
the object. Then, in your program, you create an instance of the class. This
instance is called an object.
Classes are really nothing more than user-defined data types. As with any data
type, you can have as many instances of the class as you want. For example, you
can have more than one window in a Windows application, each with its own
contents.
For example, think again about the integer data type (int). It's absurd to think that
a program can have only one integer. You can declare many integers, just about
all you want. The same is true of classes. We will look at relevant examples later.
After you define a new class, you can create many instances of the class. Each
instance (called an object) normally has full access to the class's methods and gets
its own copy of the data members.
Inheritance
Suppose that you have a class for a regular car, but now you want to create a car
that has a high-speed passing gear. In a traditional program, you might have to
modify the existing code extensively and might introduce bugs into code that
worked fine before your changes.
To avoid these hassles, you use the object-oriented approach: Create a new class
by inheritance. This new class inherits all the data and methods from the tested
base class. (You can control the level of inheritance with the public, private, and
protected keywords. You'll see how all this works with Java "Classes.") Now, you
only need to worry about testing the new code you added to the derived class.
NOTE: The designers of OOP languages didn't pick the word "inheritance" out of
a hat. Think of how human children inherit many of their characteristics from
their parents. But the children also have characteristics that are uniquely their
own. In object-oriented programming, you can think of a base class as a parent
and a derived class as a child.
Polymorphism
For example, you may have a shape object that draws a circle on the screen. By
using polymorphism, you can create a shape object that draws a rectangle
instead. You do this by creating a new version of the method that draws the
shape on the screen. Both the old circle-drawing and the new rectangle-drawing
method have the same name (such as DrawShape()) but accomplish the drawing
in a different way.
Although you won't actually start using Java classes until later in this book, this is
a good time to look at OOP concepts in a general way. As an example, you'll
extend the car metaphor you read earlier this chapter.
In terms of constructing a class for a car object, you can think of direction,
position, and speed as the class's data fields and the steering wheel, gas pedal,
and brakes as representing the class's methods.
The first step in creating an object is to define its class. For now, you'll use
pseudo-code to create a Car class.
class Car{
data direction;
data position;
data speed;
OOP Using method
JAVA NEILS B. JOEL
Steer();
method PressGasPedal();
Page |6
In this base car class, a car is defined by its direction (which way its pointed),
position (where it's located), and speed. These three data fields can be
manipulated by the three methods Steer(), PressGasPedal(), and
PressBrake(). The Steer() method changes the car's direction, whereas
the PressGasPedal() and PressBrake() change the car's speed.
The car's position is affected by all three methods, as well as by the direction and
speed settings.
The data fields and methods are all encapsulated inside the class. Moreover, the
data fields are private to the class, meaning that they cannot be directly accessed
from outside of the class.
Only the class's three methods can access the data fields. In short, Listing 4.1 not
only shows what a class might look like, it also shows how encapsulation works.
Now, suppose you want to create a new car that has a special passing gear. To do
this, you can use OOP inheritance to derive a new class from the Car base class.
method Pass();
You may be surprised to see how small this new class is. It's small because it
implicitly inherits all the data fields and methods from the Car base class. That is,
not only does the PassingCar class have a method called Pass(), but it also
has the direction, position, and speed data fields, as well as the Steer(),
PressGasPedal(), and PressBrake() methods.
The PassingCar class can use all these data fields and methods exactly as if they
were explicitly defined. This is an example of inheritance.
The last OOP concept that you'll apply to the car classes is polymorphism.
Suppose that you now decide that you want a new kind of car that has all the
characteristics of a PassingCar, except that its passing gear is twice as fast as
PassingCar's.
method Pass();
The FastCar class looks exactly like the original PassingCar class. However,
rather than just inheriting the Pass() method, it defines its own version. This
new version makes the car move twice as fast as PassingCar's Pass()
method does (the code that actually implements each method is not shown). In
this way, the FastCar class implements the same functionality as the
PassingCar() class, but it implements that functionality a little differently.
In this line, the word tax is a variable. So, one reason you need variables in a
program is to hold the results of a calculation. In this case, you can think of the
word tax as a kind of digital bucket into which the program dumps the result of its
sales tax calculation.
When you need the value stored in tax, you can just reach in and take it out-
figuratively speaking, of course. As an example, to determine the total cost of a
$12.00 purchase, plus the sales tax, you might write a line like this:
total = 12 + tax;
In this line, the word total is yet another variable. After the computer performs
the requested calculation, the variable total will contain the sum of 12 and
whatever value is stored in tax.
For example, if the value 0.72 is stored in tax, after the calculation, total would be
equal to 12.72.
Do you see another place where a variable is necessary? How about the hard-
coded value 12? Such a hard-coded value makes a program pretty useless
because every person that comes into your store to buy something isn't going to
spend exactly $12.00. Because the amount of each customer's purchase will
change, the value used in your sales tax calculation must change, too.
That means you need another variable. How about creating a variable named
purchase? With such a variable, you can rewrite the calculations like this:
tax = purchase * SALESTAX;
Now you can see how valuable variables can be. Every value in the preceding lines
is represented by a variable. (Although you're using SALESTAX as a symbolic
constant, because of Java's current lack of true constants, it's really a variable,
too.)
Please refer to part one of this lecture notes to digest data types.
Declaration of a Variable
• The first way to declare a variable: This specifies its data type, and reserves
memory for it. It assigns zero to primitive types and null to objects.
• The second way to declare a variable: This specifies its data type, reserves
memory for it, and puts an initial value into that memory. The initial value must
be of the correct data type.
dataType variableName;
• The first way to declare two variables: all of the same data type, reserves
memory for each.
• The second way to declare two variables: both of the same data type, reserves
memory, and puts an initial value in each variable.
Names of Variables
• Use only the characters 'a' through 'z', 'A' through 'Z', '0' through '9', character
'_', and character '$'.
• A name cannot contain the space character.
• Do not start with a digit.
• A name can be of any reasonable length.
• Upper and lower case count as different characters. I.e., Java is case sensitive. So
SUM and Sum are different names.
• A name cannot be a reserved word (keyword).
• A name must not already be in use in this block of the program.
In programming, cycles are called loops. When a program has a loop in it, some
statements are done over and over until a predetermined condition is met.
import java.io.*;
while (condition) {
while(condition) {
When the condition is true, the loop body is executed. When the condition is
false, the loop body is skipped, and the statement after the loop is executed.
Once execution has passed to the statement after the loop, the while statement
is finished. If the condition is false the very first time it is evaluated, the loop
body will not be executed at all.
There are three things to consider when your program has a loop:
Be very careful with boundary Conditions. Scrutinize the two examples below
placed side by side. Their outputs are shown right after.
The above loop will be executed 3 times. The This loop will be executed 2 times. The
output is: output is:
count is: 1 count is: 1
count is: 2 count is: 2
OOP Using JAVA NEILS B. JOEL
count is: 3
P a g e | 16
Consider yet another example. Here for some reasons best known to us, we want
a program that can count downwards by 3. We can implement the program like
below:
count is: 6
count is: 4
count is: 2
count is: 0
A more robust implementation of the while loop is given in the next page. Please
study the codes very well and then try to run it off head!
import java.io.*;
String inputData;
inputData = userin.readLine();
inputData = userin.readLine();
while ( num != 0 ) {
inputData = userin.readLine();
}
OOP Using JAVA NEILS B. JOEL
System.out.println( "Sum of the integers: " + sum );
P a g e | 18
The loops we talked about so far are called counting loops. Loops are controlled
by a counter.
The disadvantage of the previous program is that users have to count the number
of integers to be added.
The idea of a sentinel controlled loop is that there is a special value (the
"sentinel") that is used to say when the loop is done.
PROBLEM:Write a program that will sum up each integer the user enters. In the
program, use a special value “the sentinel” to tell the program that the loop is
done
NOTE: The implementation to this problem was done in class if you guys can
remember. Revise.
For Statement
Java (and several other languages) has a for statement which combines the three
aspects of a loop into one statement. In general, it looks like this:
for ( initialize ; test ; change )
loopBody ;
The initialize, test, and change are statements or expressions that (usually)
perform the named action. The loopBody can be a single statement or a block
statement. Example:
// initialize test change
for ( count = 0; count < 10; count++ )
{
System.out.print (count + " ");
}
The piece of code above can be implemented with the while loop as done below
count = 0; // initialize
count++; // change
}
switch Statement
• A choice is made between options based on the value in code.
• To execute this fragment, look down the list of cases to match the value in code.
• The statement between the matching case and the next break is executed. All
other cases are skipped. If there is no match, the default case is chosen.
Only one case will be selected per execution of the switch statement.
• Each label must be an integer literal (like 0, 23), but not an expression or
variable.
2. The labels after each case are inspected one by one, starting with the
first.
3. The body of the first label that matches has its statementList executed.
• If no case label matches the value of integerExpression, then the default case is
picked, and its statements execute.
• If a break statement is not present, all cases below the selected case will also be
executed.
double discount;
break;
default:
discount = 0.3;
do Statement
The do statement is similar to the while statement with an important difference:
the do statement performs a test after each execution of the loop body. Here is a
counting loop that prints integers from 0 to 9 in the next page:
3. The body of the loop must change the condition that is tested.
The do loop must do all three, but the ending condition test is done after the loop
body has been executed.
Objects
• Many programs are written to model problems of the real world.
• A class contains fields and methods that define the behaviour of the object.
• A programmer may define a class using Java, or may use predefined classes that
come in class libraries such as the JDK.
• The methods do not run in any order. For an application, the first method to
run is the method named main. There should be only one method named main
in an application.
• In a small application, main might do by itself all the computation that needs
to be done. In a larger application, main will create objects and use their
methods. objects. It describes an object’s behaviour and state.
• When a programmer wants to create an object the new operator is used with
the name of the class.
class stringTester {
} NEILS B. JOEL
OOP Using JAVA
}
P a g e | 25
creates an object by following the description in class String. The class String is
defined in the package java.lang that comes with the Java system.
The computer system finds a chunk of memory for the object, lays out this
memory according to the plan (the definition of String), and puts data and
methods into it.
The data in this String object will be the characters "I am a Nigerian" and the
methods will be all of the methods that the String class has. One of these
methods is length().
The variable str1 is used to refer to a string object. In other words, str1 gives the
object a name, like a variable.
A variable that can refer to an object does not always have an object to refer to.
• In our program the variable str1 refers to an object only after the new operator
creates one.
• Before the new operator did its work, str1 was a "place holder" that did not
actually refer to any object.
• After the new operator creates the object, str1 is used to refer to the object.
• Once the object has been created (with the new operator), the variable str1
refers to that object.
• That object has several methods, one of them is the length() method.
• A String object's length() method counts the characters in the string, and
returns that amount.
To invoke the length() method of the object named str1 the following is used:
len = str1.length();
Remember that all method names will have "()" at their end. The above method
evaluates to an integer, 15, which is assigned to the int variable len.
• Constructors often are used with values (called parameters) that are to be
stored in the data part of the object that is created. In the above program, the
characters I am a Nigerian are stored in the data section of the new object.
Object Reference
1. An object is created using the constructor. The Java system keeps track of
how to find the object.
2. The way to find the object is stored in the variable str.
The variable str does not actually contain the object, but contains information
about where the object is located.
Objects are created while a program is running. Each object has a unique object
reference, which is used to find it.
When an object reference is assigned to a variable, that variable says how to find
that object.
Examples
Study the examples below, the explanations are contained inside the codes as
comments.
String str;
strA = new String( "Dog" ); // create the first object and save its reference.
System.out.println( strA ); // follow reference to first object and println its data.
OOP Using JAVA NEILS B. JOEL
strB = new String( "Cat" ); // create the second object and Save its reference.
P a g e | 29
Separation into sections is done for convenience; it is not a rule of the language.
// method definition
void speak() {
class HelloTester {
The definition of class HelloObject only defines a method for the class. When the
main() method starts, it constructs a HelloObject and then invokes its speak()
method.
Objects of this class have no instance variables. The class does have a constructor.
Save the file as HelloTester.java because the file name must match the name of
the class that contains the main() method.
Method Definition
// Java statements
return returnValue;
The returnType is the type of value that the method hands back to the caller of
the method.
Your methods can return values just as do methods from library classes. The
return statement is used by a method to hand back a value to the caller.
void
If you want a method that does something, but does not hand a value back to the
caller, use a return type of void and do not use a return statement.
The method will automatically return to the caller after it executes. Here is the
method from the example program:
// method definition
void speak() {
Now let us look at the examples above with a more detailed explanation.
class HelloTester {
// is created.
// method is called.
OOP Using
} JAVA NEILS B. JOEL
P a g e | 32
Constructors
You will need to include a constructor in the class definition when you need to
pass some data to the object being instantiated.
Default Constructor
So far, the speak method of the HelloObject class always prints the same string to
the monitor.
If different objects of the HelloObject class are to print different things, then each
instance will have its own unique data, which will have to be initialized. This calls
for a constructor.
className( parameterList ) {
No return type is listed before the className. There is no return statement in the
body of the constructor. The constructor must have the same name as the class.
The parameterList is a list of values and their types that will be handed to the
constructorwhen it is asked to construct a new object.
Parameter lists look like this (the same as parameter lists for methods):
TypeName1 parameterName1,
Coding a Constructor
String greeting;
HelloObject( String st ) {
greeting = st;
void speak() {
System.out.println( greeting );
}
P a g e | 34
The constructor will initialize the variable greeting with data that is supplied when
the constructor is used.
When a member of a class is declared private, it can be used only by the methods
of that class. Not all objects can “see” all private variables.
Here is a checking account class definition with each of its variables declared to be
private. Only the methods of a CheckingAccount object can "see" the values in
accountNumber, accountHolder, and balance
//data-declarations
//constructors
accountNumber = accNumber ;
accountHolder = holder ;
balance = start ;
// methods
int currentBalance() {
return balance ;
}
}
P a g e | 35
Accesser Methods
A class with private data controls access to that data by using an accesser ethods.
An accesser method is a method which uses the private data of its class and is
visible to other classes. Some accessr methods alter data; others return a value
but don't alter data.
// . . . .
class CheckingAccountTester {
System.out.println( bobsAccount.currentBalance() );
bobsAccount.processDeposit( 200 );
System.out.println( bobsAccount.currentBalance() );
Private Methods
A private method is one that can be used only by the other methods of an object.
Parts of a program outside of the object cannot directly invoke (use) a private
method of the object.
Example:
// data-declarations
incrementUse();
int charge;
incrementUse();
// …
The private visibility modifier keeps outsiders from looking in. However, the
access methods are intended for outsiders, and have to be visible to outsiders in
order to be useful.
Example:
class CheckingAccount {
. . .*/ }
Package Visibility
If you do not specify public or private for a variable or a method, then it will have
package visibility.
// . . . .
// . . . .
The parameter amount is used by a caller to send a value to the method. This is
usually called passing a value to the method.
100 );
bobsAccount.processDeposit( 200 );
// . . . .
Then the method will exit and control will return to main(). The state of the
object referred to by bobsAccount will be changed.
actual parameter --- the actual value that is passed into the method by a caller.
For example, the 200 used when processDeposit is called is an actual parameter.
Scope
The scope of a formal parameter (a local variable) is the section of code that can
"see" (can use) the parameter. The scope of a formal parameter is the body of its
method.
Statements of a method can see the object's instance variables and the object's
other methods. They cannot see the parameters (and local variables) of other
methods.
// . . . .
// . . . .
int charge;
charge = 15;
else
charge = 0;
}
OOP Using JAVA NEILS B. JOEL
P a g e | 42
Indices always start at zero, and count up by one's until the last slot of the array.
If there are N slots in an array, the indices will be 0 through N-1.
Every slot of an array holds a value of the same type. A slot of an array that
contains a numeric type (such as int) can be used anywhere a numeric variable
can be used.
Array Declaration
This tells the compiler that arrayName will be used as the name of an array
containing type, and constructs an array object containing length number of slots.
An array is an object, and like any other object in Java is constructed out of main
storage as the program is running. type[ length] names the type of data in each
slot and the number of slots. Once an array has been constructed, the number of
slots it has does not change.
stuff[0] = 23;
stuff[1] = 38;
stuff[2] = 7*2;
stuff[0] has 23
stuff[1] has 38
stuff[2] has 14
stuff[3] has 0}
You may alternatively, decide to use a variable as your array index. During the
course of programming, you will find this concept particularly helpful.
val[0] = 0.12;
val[1] = 1.43;
val[2] = 2.98;
int j = 3;
System.out.println( val[ j ] );
j = j-2;
System.out.println( val[ j ] );
Initializer List
You can declare, construct, and initialize the array all in one statement:
This declares an array of int which will be named data, constructs an int array of
10 slots (indexed 0..9), and puts the designated values into the slots. The first
value in the initializer list corresponds to index 0, the second value corresponds
to index 1, and so on.
The slots of an array are often called elements. In a one dimensional array, the
elements are accessed using a single index. In a two dimensional array, the
elements are accessed using two indices.
Length of an Array
An array is an object. An array object has a member length that is the number of
elements it has.
import java.io.* ;
import java.lang.reflect.Array;
int data;
Vector Class
The Vector class builds upon the capabilities of arrays. A Vector object contains
an array of object references plus many methods for managing that array.
You can keep adding elements to it no matter what the original size of the vector
is. The size of the Vector will increase automatically and no information will be
lost. The elements of a Vector are object references, not primitive data.
Using a Vector is slightly slower than using an array. The elements of a Vector are
references to Object. This means that often you will need to use type casting with
the data from a Vector.
It is best to illustrate this with a code. Consider the declarations made below:
Vector myVector; //myVector is a reference to a future vector
object
Please study the example below and understand the methods for vector objects
import java.util.* ;
class VectorEg {
names.addElement( "Amy" );
names.addElement( "Bob" );
names.addElement( "Chris" );
names.addElement( "Deb" );
names.removeElementAt(2);
}
OOP Using JAVA NEILS B. JOEL
P a g e | 49
ASSIGNMENT PAGE:
QUESTION: