Java First Session
Java First Session
Session 1
1. Programming concepts and algorithms
a. What is programming: it is the process of writing, testing,
debugging/troubleshooting, and maintaining the source
code/commands/instructions of computer programs. This source
code is written in a programming language e.g. visual basic, C,
C++, Pascal, Java.
2. Java technology
a. What is java:
• Simple powerful language
• Similar to C++ (both object oriented supporting classes
instantiated from objects / similar variable types e.g int, float /
case sensitive)
• Originated at Sun Microsystems, Inc. in 1991. It was
conceived by James Gosling
• Developed to provide a platform-independent
programming language on any system where a Java™ Virtual
Machine is available e.g. Windows 9x/ME/NT/2000/XP etc.,
MacOS, OS/2, Solaris, LINUX, UNIX and PDAs (Pocket PCs).
b. Applications of java :
• Web based applications – ecommerce (Java applets -
small standalone applications e.g. text editor, calculator - can
run in a Web browser for many platforms, including Windows,
Unix, Mac OS and Linux using a Java Virtual Machine).
The client sends an HTTP request to the web server. A web
server that implements Java Servlet and JavaServer Pages
technology converts the request into an HTTPServletRequest
object. This object is delivered to a web component (There are
two types of web components: Java Servlets and JavaServer
Pages (JSP ) pages. Servlets are Java programming
language classes that dynamically process requests and
construct responses), which can interact with JavaBeans
components or a database to generate dynamic content. The
web component can then generate an HTTPServletResponse or
it can pass the request to another web component. Eventually
a web component generates a HTTPServletResponse object.
The web server converts this object to an HTTP response and
returns it to the client).
• Financial applications (stocks / payroll / banks),
• Gaming applications (racing cars etc.),
b. Methods
• An object stores its state in fields (variables in some
programming languages) and exposes its behavior and
interaction with the outer world through methods (functions in
some programming languages).
• Hiding internal state and requiring all interaction to be
performed through an object's methods is known as data
encapsulation (e.g. when assembling a pc, each object- card,
processor etc.- is a self contained unit, and all you are
interested in is how the units interact with each other not how
each one works alone)
c. How to write Java:
• Enter the program source code in a data file using an
editor e.g. JCreator / IBM Websphere etc.
• Transform the source program into machine language or
Java Bytecode using a compiler
• Return to the editor to correct any errors (or bugs) and
start the cycle again
• Bytecode files, which are very compact, are easily
transported through a distributed system like the Internet.
•The compiled Java code (resulting byte code) will be executed
at run time
Attributes (Variables)
Attributes are the PROPERTIES of a class; on the whole they are things that can
be measured or observed.
When a new object is created, an area of the computer's memory is
allocated to store the object.
Attributes are defined by variables : locations in memory in which values can be
stored
Variables have a
name,
type,
value
A variable must be declared before you can use a variable. After declaration,
values can be assigned to it
Types of Variables
instance variables: (Non-Static Fields) used to define attributes or the state
for a particular object INSTANTIATED from a class.
Each instance (object) can have different values for a variable but always
the same type. (Even if all the attributes of two objects are identical, this
does not make the objects identical).
Instance variables may be set when an object is created and stay constant
throughout the life of the object, or they may be able to change at will as the
program runs.
class variables: (Static Fields) this tells the compiler that there is exactly one
copy of this variable in existence. They apply to all that class's instances (and to
the class itself) rather than having different values for each object.
Class variables' values are stored in the class itself.
local variables: are declared and used only inside a method definition or a block.
Once the method (or block) finishes executing, the variable definition and its
value cease to exist.
Declaring variables
Once a variable has been declared, you can assign a value to that variable by using the
assignment operator =:
size = 14;
tooMuchCaffiene = true;
name= “noha”
Variable/Method Names
choose names that are meaningful - represent the characteristic of the variable or
what the method does
Variable names in Java can start with a letter, an underscore (_), or a dollar sign
($).
They cannot start with a number
Do not use reserved java words e.g. “class”, “public” etc.
Symbols, such as %, *, @, and so on, are often reserved for operators in Java so
avoid them
Names in java are case sensitive
If it’s a complex name the first word is lowercase, but all following words have an
initial uppercase letter e.g.
Button theButton;
long reallyBigNumber;
boolean currentWeatherStateOfPlanetXShortVersion;
Comments
Java has three kinds of comments
/* and */ surround multiline comments , e.g.
/* I don't know how I wrote this next part; I was working
really late one night and it just sort of appeared.
*/
Double-slashes (//) can be used for a single line of comment
comments beginning with /** and ending with */ are used to generate API
documentation from the code. (API) is an interface implemented by a software program
to enable interaction with other software, much in the same way that a user interface
facilitates interaction between humans and computers.
String Literals
Methods (operations)
Operations say what a class does.
Methods are operations/functions defined inside classes that operate on instances
(objects) of those classes. Java does not have functions (methods) defined outside
classes (as C++ does)
Message Passing:
All of a class's operations are accessible to other classes (Public
Operations)
Classes can communicate by invoking EACH OTHERS’ operations.
Method Declaration
Method definition syntax:
return value type method-name ( parameter1, parameter2, …, parametern){
declarations and statements
}
A method definition consists of a method header and a method body.
A method header states the method name and the type of the return value.
The header may also specify variables called formal parameters which receive
incoming arguments. These formal parameters are used in them method body to
perform the computations.
The method body consists of a sequence of declarations and statements enclosed
in braces{}
The method main “public static void main (String args[])” has
void as type of return value which means that it does not return a value,
method name is main,
this method returns a parameter of an array of Strings with any name.
static means that the method belongs to the class in which it resides
Methods that do not return a value must have the reserve word void.
Static methods operate on a class as a whole (not on specific instances of the
class).
Keyword public means that it can be accessed from outside the class.
class HelloWorld
{
public static void main (String args[])
{
System.out.println("Hello World!");
}
}
b. The body of the program (here, just the one line) is contained in a method
(function) called main(). In Java applications, as in a C or C++ program, main() is
the first method (function) that is run when the program is executed
2. Parentheses are used for the beginning and end of any class or method
3. Semicolons end each statement in a method
4. If a statement returns a value , it is called an expression e.g. when you add two
numbers together or test to see whether one value is equal to another
5. A statement is called a block if complex lines surrounded by parentheses e.g. loop,
array, if condition
6. Once you finish typing the program, save the file. Most of the time, Java source files
are named the same name as the class they define, with an extension of .java. This
file should therefore be called HelloWorld.java.
7. Now, let's compile the source file using the Java compiler. In Sun's JDK, the Java
compiler is called javac. The compiler should compile the file without any errors. If
you get errors, go back and make sure that you've typed the program exactly as it
appears
8. When the program compiles without errors, you end up with a file called
HelloWorld.class, in the same directory as your source file. This is your Java bytecode
file. You can then run that bytecode file using the Java interpreter. In the JDK, the
Java interpreter is called simply java
9. If your program was typed and compiled correctly, you should get the string "Hello
World!" printed to your screen as a response
10. You can make another class and instantiate this one from inside it i.e. make an
instance of it which executes: If a class is the general (generic) representation of an
object, an instance is its concrete representation = an object
a. e.g. you might create a class for the user interface element called a button. The
Button class defines the features of a button (its label, its size, its appearance) and
how it behaves (does it need a single click or a double click to activate it, does it
change color when it's clicked, what does it do when it's activated?). Once you define
the Button class, you can then easily create instances of that button—that is, button
objects—that all take on the basic features of the button as defined by the class, but
may have different appearances and behavior based on what you want that
particular button to do. By creating a Button class, you don't have to keep rewriting
the code for each individual button you want to use in your program, and you can
reuse the Button class, by creating instances (objects) of it from inside other classes,
to create different kinds of buttons as you need them .
Second Java Application
class Motorcycle {
String make;
String color;
boolean engineState;
void startEngine() {
if (engineState == true)
System.out.println("The engine is already on.");
else {
engineState = true;
System.out.println("The engine is now on.");
}
}
void showAtts() {
System.out.println("This motorcycle is a "
+ color + " " + make);
if (engineState == true)
System.out.println("The engine is on.");
else System.out.println("The engine is off.");
}
}
Answer:
Calling showAtts...
This motorcycle is a yellow Yamaha RZ350
The engine is off.
————
Starting engine...
The engine is now on.
————
Calling showAtts...
This motorcycle is a yellow Yamaha RZ350
The engine is on.
————
Starting engine...
The engine is already on.
class TestString {
public static void main(String args[]) {
String str = "Now is the winter of our discontent";
System.out.println("The string is: " + str);
System.out.println("Length of this string: " +
str.length());
System.out.println("The character at position 5: " +
str.charAt(5));
System.out.println("The substring from 11 to 17: " +
str.substring(11, 17));
System.out.println("The index of the character d: " +
str.indexOf('d'));
System.out.print("The index of the beginning of the ");
System.out.println("substring \"winter\":" +
str.indexOf("winter"));
System.out.println("The string in upper case: "
+ str.toUpperCase());
}
}
Answer:
N.B. All spaces are , and the counting starts at position “0”
Fourth Java Example: The TestPoint Class.
import java.awt.Point;
class TestPoint {
System.out.println("Setting X to 5.");
thePoint.x = 5;
System.out.println("Setting Y to 15.");
thePoint.y = 15;
Answer:
X is 10
Y is 10
Setting X to 5.
Setting Y to 15.
X is 5
Y is 15
SmartSoft
ITWorx
IBM
Link
Orascom
Java Programming Language
Session 3/4
Scope of variables
Instance Variables (Non-Static Fields): objects store their individual states in
"non-static fields", that is, fields declared without the static keyword. Non-static
fields have values that are unique to each instance of a class (to each object); the
currentSpeed of one bicycle is independent from the currentSpeed of another.
Class Variables (Static Fields): A class variable is any field declared with the
static modifier; this tells the compiler that there is exactly one copy of this variable
in existence; regardless of how many times the class has been instantiated. A field
defining the number of gears for a bicycle could be marked as static since the same
number of gears will apply to all instances, e.g. static int numGears = 6 (static
field). Additionally, the keyword final could be added to indicate that the number of
gears will never change.
Local Variables: a method stores its temporary state in local variables, e.g. int
count = 0;). Local variables are only visible to the methods in which they are
declared; they are not accessible from the rest of the class.
N.B. String objects are immutable, which means that once created, their values
cannot be changed e.g. String s = "this is a string";
They are instantiated from the java.lang.String class
Arrays
An array is a container object that holds a fixed number of values of a single type. The
length of an array is established when the array is created. After creation, its length is
fixed.
Each item in an array is called an element, and each element is accessed by its numerical
index. Numbering begins with 0. The 9th element, for example, would therefore be
accessed at index 8.
Declaring a Variable to Refer to an Array
Like declarations for variables, an array declaration has two components: the array's
type and the array's name.
An array's type is written as type[], where type is the data type of the
contained elements;
the square brackets are special symbols indicating that this variable holds an
array.
The size of the array is not part of its type (which is why the brackets are
empty).
The declaration does not actually create an array — it simply tells the
compiler that this variable will hold an array of the specified type.
Example
The following program, ArrayDemo, creates an array of integers, puts some values in it,
and prints each value to standard output.
class ArrayDemo {
public static void main(String[] args) {
int[] anArray; // declares an array of integers
Answer:
Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
It’s easier to use one of the looping constructs (for, while, and do-while) to iterate
through each element of the array, rather than write each line individually as shown
above, as will be shown later.
You can also declare an array of arrays (also known as a multidimensional array) by
using two or more sets of square brackets, such as String[][] names. Each element,
therefore, must be accessed by a corresponding number of index values.
class MultiDimArrayDemo
{
public static void main(String[] args) {
String[][] names = {{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}};
System.out.println(names[0][0] + names[1][0]);
System.out.println(names[0][2] + names[1][1]);
System.out.println(names.length);
}
}
Answer:
Mr. Smith
Ms. Jones
To determine the size of any array use the built-in length property:
System.out.println(anArray.length);
N.B.
- length of single array gives number of elements
- length of multi dimensional array gives number of single arrays
- string.length() array.length
Copying Arrays
The System class has an arraycopy method that you can use to efficiently copy data
from one array into another:
public static void arraycopy (Object src,
int srcPos,
Object dest,
int destPos,
int length)
The two Object arguments specify the array to copy from and the array to copy to. The
three int arguments specify the starting position in the source array, the starting position
in the destination array, and the number of array elements to copy.
The following program, ArrayCopyDemo, declares an array of char elements, spelling the
word "decaffeinated". It uses arraycopy to copy a subsequence of array components into
a second array:
class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
Answer:
Caffein.
(mention VECTORS)
Operators
Operators are special symbols that perform specific operations on one, two, or three
operands, and then return a result.
Assignment Operator
The simple assignment operator "="
assigns the value on its right to the operand on its left e.g.
int speed = 0;
can also be used on objects to assign object references e.g.
Point originOne = new Point(23, 94);
Arithmetic Operators
+ addition operator (also used for String concatenation)
- subtraction operator
* multiplication operator
/ division operator
% remainder operator: divides one operand by another and returns the
remainder as its result
e.g.
class ArithmeticDemo {
public static void main (String[] args){
int result = 1 + 2; // result is now 3
result = result - 1; // result is now 2
result = result * 2; // result is now 4
result = result / 2; // result is now 2
result+=8; // result is now 10
result = result % 7; // result is now 3
System.out.println(result);
}
}
The + operator can also be used for concatenating (joining) two strings together
e.g.
class ConcatDemo {
public static void main(String[] args){
String firstString = "This is";
String secondString = " a concatenated string.";
String thirdString = firstString+secondString;
System.out.println(thirdString);
}
}
You can also combine the arithmetic operators with the assignment operator to
create compound assignments. e.g.
result+=1 is the same as result=result+1
Expression Meaning
x += y x=x+y
x —= y x=x—y
x *= y x=x*y
x /= y x=x/y
N.B.
result = +1 is different from result+=1
The increment/decrement operators can be applied before (prefix) or after (postfix)
the operand. The code result++; and ++result; will both end in result being
incremented by one. The only difference is that the prefix version (++result)
evaluates to the incremented value, whereas the postfix version
(result++) evaluates to the original value.
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
System.out.println(i); // "4"
++i;
System.out.println(i); // "5"
System.out.println(i++); // "5"
System.out.println(++i); // "7"
System.out.println(i); // "7"
}
}
class ComparisonDemo {
public static void main(String[] args){
int value1 = 1;
int value2 = 2;
if(value1 == value2) System.out.println("value1 == value2");
if(value1 != value2) System.out.println("value1 != value2");
if(value1 > value2) System.out.println("value1 > value2");
if(value1 < value2) System.out.println("value1 < value2");
if(value1 <= value2) System.out.println("value1 <= value2");
}
}
Answer:
value1 != value2
value1 < value2
value1 <= value2
The Conditional Operators
The && and || operators perform Conditional-AND and Conditional-OR operations
on two boolean expressions.
class ConditionalDemo1 {
public static void main(String[] args){
int value1 = 1;
int value2 = 2;
if((value1 == 1) && (value2 == 2))
System.out.println("value1 is 1 AND value2 is 2");
if((value1 == 1) || (value2 == 1)) System.out.println("value1
is 1 OR value2 is 1");
}
}
multiplicative * / %
additive + -
equality == !=
logical OR ||
ternary ? :
assignment = += -= *= /= ^=
If a statement returns a value , it is called an expression e.g. when you add two
numbers together or test to see whether one value is equal to another
A statement is called a block if complex lines surrounded by parentheses e.g. loop,
array, if condition
Operators that deal with bits are less commonly used. For example:
"~"
This inverts a bit pattern; making every "0" a "1" and every "1" a "0". For example, a
byte contains 8 bits "00000000" would change its pattern to "11111111".
“|” “&”
The single OR and AND operators work on bits in the following way:
bit 1 bit 2 OR (|) AND (&) XOR (^)
0 0 0 0 0
1 0 1 0 1
0 1 1 0 1
1 1 1 1 0
―|‖ Bitwise OR returns one in all cases except where the corresponding bits of both
operands are zero. The resulting bit pattern is the "set" (1 or true) bits of any of the two
operands. This property can be used to "set" or "turn on" a "flag" (bit set to one) in the
―flags‖ variable regardless of whether that flag was set previously or not.
// To set or turn on a flag bit(s)
flags = flags | MASK;
―&‖Bitwise AND sets a bit to 1 if and only if both of the corresponding bits in its operands
are 1, and to 0 if the bits differ or both are 0. In other words, a one ANDed with any bit
is that bit and a zero ANDed with any bit is zero. This operator can be used to check the
state of a flag in e.g. ―flags‖ variable. When you AND the ―flags‖ variable with the
―MASK‖, all zeroes in the ―MASK‖ will return zero for the corresponding position in ―flags‖
and all ones in the ―MASK‖ will return whatever the corresponding bit is set to in the
―flags‖ variable.
// To check the state of a flag bit(s)
if (flags & MASK) == MASK) { N.B. we can’t say:
// flag is set or turned on if (flags & 1) == 1)
... because 1 here is a character
} not a bit
else {
//flag is not set or is turned off
...
}
―&‖ can also be used, RARELY, as a logical operator but this single
ampersand always evaluates both arguments whereas the double
ampersand ―&&‖ will only evaluate the second argument if the first
argument is true – thus it’s faster.
Flag refers to one or more bits that are used to store a binary value or code
that has an assigned meaning.
One common use of flags is to mark or designate data structures for
future processing.
Within microprocessors and other logic devices, flags are commonly
used to control or indicate the intermediate or final state or outcome of
different operations. Microprocessors typically have, for example, a
status register that is composed of such flags, and the flags are used to
indicate various post-operation conditions, such as when there has
been an arithmetic overflow.
The Type Comparison Operator
The instanceof operator compares an object to a specified type. You can use it to test if
an object is
an instance of a class,
an instance of a subclass, or
an instance of a class that implements a particular interface.
class InstanceofDemo {
public static void main(String[] args) {
Parent obj1 = new Parent();
Parent obj2 = new Child();
class Parent{}
interface MyInterface{}
Answer:
obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true
Control Flow Statements
The statements inside source files are generally executed from top to bottom, in the
order that they appear. Control flow statements break up the flow of execution by
enabling the program to conditionally execute particular blocks of code using:
IF-THEN-ELSE Statement
It executes a certain section of code only if a particular condition occurs.
E.g.
The Bicycle class could allow the brakes to decrease the bicycle's speed only if the
bicycle is already in motion. If this test evaluates to false (meaning that the
bicycle is not in motion), control jumps to the end of the if-then statement
void applyBrakes(){
if (isMoving) { // the "if" clause: bicycle must be moving
currentSpeed--; // the "then" clause: decrease current speed
}
}
N.B. it is better to include the opening and closing braces for the ―then‖ clause
e.g. The following program, IfElseDemo, assigns a grade based on the value of a
test score: an A for a score of 90% or above, a B for a score of 80% or above, and
so on:
class IfElseDemo
{
public static void main(String[] args)
{
int testscore = 76;
char grade;
Answer:
Grade = C
N.B.
The value of testscore can satisfy more than one expression in the compound
statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the
appropriate statements are executed (grade = 'C';) and the remaining
conditions are not evaluated.
If we don’t use ―else if‖ and only ―if‖ , the program will run all feasible conditions
Is the character a digit ?
class IfInteger {
static int x=5;
static String y="not number";
e.g. The following program, SwitchDemo, declares an int named month whose value
represents a month out of the year. The program displays the name of the month, based
on the value of month, using the switch statement.
class SwitchDemo
{
public static void main(String[] args)
{
int month = 8;
switch (month)
{
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");break;
}
}
}
Answer:
August
N.B. Each break statement terminates the enclosing switch statement. Control flow
continues with the first statement following the switch block. The break statements are
necessary because without an explicit break, control will flow sequentially through
subsequent case statements.
int month = 8;
if (month == 1) {
System.out.println("January");
} else if (month == 2) {
System.out.println("February");
}
. . . // and so on
class SwitchDemo2 {
public static void main(String[] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if ( ((year % 4 == 0) && !(year % 100 == 0))
|| (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = " + numDays);
}
}
Answer:
Number of Days = 29
The WHILE and DO-WHILE Statements
The difference between do-while and while is that do-while evaluates its
expression at the bottom of the loop instead of the top. Therefore, the statements
within the do block are always executed at least once:
do {
statement(s)
} while (expression);
e.g.
class DoWhileDemo
{
public static void main(String[] args)
{
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
}
while (count < 11);
}
}
The FOR Statement
The FOR statement is called "for loop" because it repeatedly loops until
a particular condition is satisfied. The general form of the FOR
statement is as follows:
for (initialization; termination; increment) {
statement(s)
}
The initialization expression initializes the loop; it's executed once, as the loop
begins.
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is
perfectly acceptable for this expression to increment or decrement a value.
GO BACK TO “class ArrayCopyDemo” EXERCISE
e.g.
class ForDemo
{
public static void main(String[] args)
{
for(int i=1; i<6; i++)
{
System.out.println("Count is: " + i);
}
}
}
Answer:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
the code declares a local variable within the initialization expression. The scope of
this variable extends from its declaration to the end of the block governed by the
for statement, so it can be used in the termination and increment expressions as
well
The names i, j, and k are often used to control for loops; declaring them within the
initialization expression limits their life span and reduces errors
The FOR statement has another form designed for iteration through arrays referred to
as the enhanced FOR statement, and makes loops more compact.
class EnhancedForDemo
{
public static void main(String[] args)
{
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item=0; item<numbers.length; item++)
System.out.println("Item in array is: " + numbers[item]);
}
}
In this example, the variable item holds the current value from the numbers array. The
output from this program is the same as before:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
This form of the for statement is recommended instead of the general form
whenever possible – this way the number of iterations is dynamic.
e.g. This program searches for the number 12 in an array. The break statement, shown
in boldface, terminates the for loop when that value is found. Control flow then transfers
to the print statement at the end of the program.
class BreakDemo
{
public static void main(String[] args)
{
int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 8, 622, 127 };
int searchfor = 12;
int i;
boolean foundIt = false;
if (foundIt)
{
System.out.println("Found " + searchfor + " at index " + i);
}
else
{
System.out.println(searchfor + " not in the array");
}
}
}
Answer:
Found 12 at index 4
class BreakWithLabelDemo {
public static void main(String[] args) {
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++)
{
for (j = 0; j < arrayOfInts[i].length; j++)
{
if (arrayOfInts[i][j] == searchfor)
{
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor +
" at " + i + ", " + j);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
}
Answer:
Found 12 at 1, 0
N.B. It stores values of ―i‖ and ―j‖ just before the break. They are seen by the fnal ―if‖
statement because they were declared outside the ―search‖ block.
The CONTINUE Statement
The continue statement skips the current iteration of a for, while , or do-while loop.
The unlabeled continue skips to the end of the innermost loop's body and
evaluates the boolean expression that controls the loop.
e.g. The following program, ContinueDemo , steps through a String, counting the
occurences of the letter "p". If the current character is not a p, the continue statement
skips the rest of the loop and proceeds to the next character. If it is a "p", the program
increments the letter count.
class ContinueDemo {
public static void main(String[] args) {
//process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}
On removing the continue statement and recompiling, the count will be wrong,
saying that it found 35 p's instead of 9
Answer:
Found 9 p's in the string
A labeled continue statement skips the current iteration of an outer loop marked
with the given label
e.g. The following program, ContinueWithLabelDemo, uses nested loops to search for a
substring within another string. Two nested loops are required: one to iterate over the
substring and one to iterate over the string being searched. The following program,
ContinueWithLabelDemo, uses the labeled form of continue to skip an iteration in the
outer loop.
public static void main(String[] args)
{
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() - substring.length();
test:
for (int i = 0; i <= max; i++)
{
int n = substring.length();
int k = 0;
while (n-- != 0)
{
if (searchMe.charAt(i)!= substring.charAt(k))
{
continue test;
}
i++;
k++;
}
foundIt = true;
break test;
}
Return Statement
class ReturnClass
{
static boolean t = true;
/*for each "int" object in "numbers".Here the variable ―i‖ is used to point to the current
instance of Employee in the collection. Because of the "for each" wording, the
enhanced-for construct is also referred to as the for-each construct.*/
Vectors
import java.util.*;
public class VectorDemo{
public static void main(String[] args){
vector.addElement(int1); vector.add(int2);
vector.add(str);
vector.add(2, new Integer(30)); // addElement cannot be used to put object in
specific place in vector
}
}
A class hierarchy
Each class has a superclass (above it in the hierarchy), and each class can have one
or more subclass (below it in the hierarchy)
Subclasses inherit all the methods and variables from their superclasses further
up in the hierarchy - subclassing
Each class farther down in the hierarchy adds more information and is more
tailored to a specific purpose
At the top of the Java class hierarchy is the class Object; all classes inherit from
this one superclass.
Using subclassing, you only need to define the differences between your class
and its parent
Vehicle
Engine Person
powered powered
vehicle vehicle
Single inheritance means that each Java class can have only one superclass
In C++, classes can have more than one superclass, and they inherit combined
variables and methods from all those classes. This is called multiple inheritance.
Interface
java.lang: Classes that apply to the language itself, which includes the Object
class, the String class, and the System class. It also contains the special classes
for the primitive types (Integer, Character, Float, and so on).
java.util: Utility classes, such as Date, as well as simple collection classes, such
as Vector and Hashtable.
N.B. a general subsequent level of classes can be imported by “*”, but
not classes inside a subsequent level of packages e.g.
java.util.* OR java.util.Vector - imports the Vector class
java.util.regex.* OR java.util.regex.Matcher - imports Matcher class
java.io: Input and output classes for writing to and reading from streams (such
as standard input and output) and for handling files.
java.net: Classes for networking support, including Socket and URL (a class to
represent references to documents on the World Wide Web).
java.awt: (the Abstract Window Toolkit): Classes to implement a graphical user
interface, including classes for Window, Menu, Button, Font, CheckBox, and so
on. This package also includes classes for processing images (in the
java.awt.Image package).
java.applet: Classes to implement Java applets, including the Applet class itself,
as well as the AudioClip interface
Defining Classes
to define a normal class
class MyClassName {
...
}
3. Converting primitive types to objects and then extracting primitive values back
out of those objects
Casting Objects
Instances of classes can also be cast to instances of other classes, with one restriction:
the class of the object you're casting and the class you're casting it to must be related
by inheritance; that is, you can cast an object only to an instance of its class's sub- or
superclass—not to any random class.
(classname) object
e.g.
GreenApple a= new GreenApple();
Apple a2;
a2 = (Apple) a;
N.B. Casting an object to an instance of one of that object's superclasses loses the
information the original subclass provided
N.B. In addition to casting objects to classes, you can also cast objects to interfaces—
but only if that object's class or one of its superclasses actually implements that
interface. Casting an object to an interface then enables you to call one of that
interface's methods even if that object's class does not directly implement that
interface.
Constants
A constant variable or constant is a variable whose value never changes (Constants
are useful for defining shared values for all the methods of an object)
To declare a constant:
use the final keyword before the variable declaration
include an initial value for that variable:
e.g. final float pi = 3.141592;
Class Variables (Static Fields): A class variable is any field declared with the static
modifier; this tells the compiler that there is exactly one copy of this variable in
existence; regardless of how many times the class has been instantiated. Additionally,
the keyword final could be added to indicate that it will never change.
e.g.
t=x // the x instance variable for this object
myMethod(this) // call the myMethod method, defined in this class
class Student
{
String stName;
int stAge;
String stAddress;
class ScopeTest {
int test = 10;
void printTest () {
int test = 20;
System.out.println("test = " + test);
}
}
Because the local variable hides the instance variable, the println() method will print
that test is 20
You can get around this particular problem by using “this.test” to refer to the
instance variable, and just “test” to refer to the local variable
Calling Methods
The object whose method you're calling is on the left side of the dot; the name of
the method and its arguments is on the right side of the dot:
e.g. calling some methods defined in the String class
str.length() / str.charAt(5)
Method Definition
Method definitions have four basic parts:
The name of the method
The type of object or primitive type the method returns
A list of parameters
The body of the method
Method signature is a combination of
the name of the method,
the type of object or base type this method returns, and
a list of parameters.
returntype is the type of the of the value this method returns. It can be:
one of the primitive types,
a class name, or
void if the method does not return a value at all.
if this method returns an array object, the array brackets can go either after the
return type or after the parameter list
If the method has a return type (not declared to return void), somewhere inside
the body of the method you need to return a value. Use the return keyword to
do this
e.g.
class RangeClass {
The array: [ 1 2 3 4 5 6 7 8 9 10 ]
The main() method in this class tests the makeRange() method by creating a range
where the lower and upper boundaries of the range are 1 and 10, and then uses a for
loop to print the values of the new array.
e.g.
The following class includes a method called OneToZero() which does two things:
It counts the number of ones in the array and returns that value.
If it finds a one, it substitutes a zero in its place in the array.
the main() method for the PassByReference class tests the onetoZero() method
class PassByReference {
public static void main (String arg[]) {
int arr[] = { 1, 3, 4, 5, 1, 1, 7 };
PassByReference test = new PassByReference();
Class Methods
Like class and instance variables, there are class and instance methods
Class methods are available to any instance of the class itself and can be made
available to other classes – these are general utility methods and do not directly
affect an instance of that class
e.g. the Java class libraries include a class called Math containing mathematical
methods:
float root = Math.sqrt(453.0);
System.out.print("The larger of x and y is " + Math.max(x, y));
To define class methods, use the “static” keyword in front of the method
definition, just as you would create a class variable.
e.g. static int max(int arg1, int arg2) { ... }
import javax.swing.JOptionPane;
import java.awt.Point;
class MyRect {
int x1 = 0;
int y1 = 0;
int x2 = 0;
int y2 = 0;
MyRect buildRect(int x1, int y1, int x2, int y2)
{
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
return this;
}
void printRect(){
System.out.print("MyRect: <" + x1 + ", " + y1);
System.out.println(", " + x2 + ", " + y2 + ">");
}
public static void main(String args[]) {
MyRect rect = new MyRect();
System.out.println("Calling buildRect with coordinates 25,25 50,50:");
rect.buildRect(25, 25, 50, 50);
rect.printRect();
System.out.println("—————");
System.out.println("Calling buildRect w/points (10,10), (20,20):");
rect.buildRect(new Point(10,10), new Point(20,20));
rect.printRect();
System.out.println("—————");
System.out.print("Calling buildRect w/1 point (10,10),");
System.out.println(" width (50) and height (50)");
rect.buildRect(new Point(10,10), 50, 50);
rect.printRect();
System.out.println("—————");
}
}
Answer:
Calling buildRect with coordinates 25,25 50,50:
MyRect: <25, 25, 50, 50>
—————
Calling buildRect w/points (10,10), (20,20):
MyRect: <10, 10, 20, 20>
—————
Calling buildRect w/1 point (10,10), width (50) and height (50)
MyRect: <10, 10, 60, 60>
All the buildRect() methods work based on the arguments with which they are called
Java Programming Language
Session 6
Revision: Class Declaration
class MyClass {
Access modifiers determine whether other classes can use a particular field or invoke a
particular method:
Public: A class declared with the modifier public, is visible to all classes everywhere
inside and outside its package. The public field or method is accessible from all
classes.
No modifier (package private): If a class has no modifier (the default, also
known as package-private), is visible only within its own package
Private: specifies that the member (field / method ) can only be accessed in its
own class. A standard design strategy is to make all fields private and provide public getter
methods for them.
N.B. a class can only use public or package private (no modifier). Private cannot be
used for classes and Interfaces. It also cannot be used for fields and methods within an
interface.
Protected: specifies that the member can only be accessed within its own package
(as with package-private) and, in addition, by a subclass of its class in another
package
Access Levels
Class(access Package(classes in the same Subclass (of the class — World (all classes
Modifier to its package as the class have declared outside this package have access to the
members) access to the member) — have access to the member) member)
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
Private
protected Y N Y N
Tips:
FINAL
When the final modifier is applied to a class, it means that the class cannot be
subclassed.
N.B. private methods are effectively final, as are all methods declared in a final
class. Marking these latter methods final is legal, but redundant; the compiler
already treats them as final.
Constructor Methods
Basic Constructors
Constructors look a lot like regular methods, with two basic differences:
Constructors always have the same name as the class.
Constructors don't have a return type.
when you use ―new‖ to create a new instance of a class, Java does three things:
Allocates memory for the object
Calls the class's constructor method
Initializes that object's instance variables, either to their initial values or to a default
(0 for numbers, null for objects, false for booleans, '\0' for characters)
‗New‘ invokes the no-argument constructor to create a new Bicycle object called yourBike.
To create a new Bicycle object called myBike, a constructor is called by the new operator.
If the constructor was not there , it sets the variable to „0‟ ,null and false
e.g. a class called Person, with a constructor that initializes its instance variables based
on the arguments to new. The class also includes a method for the object to introduce
itself, and a main() method to test each of these things
class Person {
String name;
int age;
Person(String n, int a) { // constructor method
name = n;
age = a;
}
void printPerson() {
System.out.print("Hi, my name is " + name);
System.out.println(". I am " + age + " years old.");
}
If the constructor was not there then we would have more coding lines to
add to give the correct results:
class PersonAdjusted {
String name;
int age;
void printPerson() {
System.out.print("Hi, my name is " + name);
System.out.println(". I am " + age + " years old.");
}
Subclass Example
public class MountainBike extends Bicycle {
// the MountainBike subclass has one field
public int seatHeight;
Like methods, constructors can also take varying numbers and types of parameters,
enabling you to create your object with exactly the properties you want it to have, or for
it to be able to calculate properties from different kinds of input, thus “overloading the
constructor”
e.g. a class , MyRect2, that has all the same functionality of the original class MyRect,
except with overloaded constructor methods instead of the buildRect() method
import java.awt.Point;
class MyRect2 {
int x1 = 0;
int y1 = 0;
int x2 = 0;
int y2 = 0;
void printRect() {
System.out.print("MyRect: <" + x1 + ", " + y1);
System.out.println(", " + x2 + ", " + y2 + ">");
}
public static void main(String args[]) {
System.out.println("Calling MyRect2 with coordinates 25,25 50,50:");
MyRect2 rect = new MyRect2(25, 25, 50,50);
rect.printRect();
System.out.println("—————");
System.out.println("Calling MyRect2 w/points (10,10), (20,20):");
rect= new MyRect2(new Point(10,10), new Point(20,20));
rect.printRect();
System.out.println("—————");
System.out.print("Calling MyRect2 w/1 point (10,10),");
System.out.println(" width (50) and height (50)");
rect = new MyRect2(new Point(10,10), 50, 50);
rect.printRect();
System.out.println("—————");
}
}
You can‘t return a value from a method that is declared void, you will get a
compiler error.
Any method not declared void must contain a return statement with a
corresponding return value, like this:
return returnValue;
The data type of the return value must match the method's declared return type;
you can't return an integer value from a method declared to return a boolean.
e.g. return integer:
Overriding Methods
There may be times when you want an object to respond to the same methods but have
different behavior when that method is called. Overriding a method involves defining a
method in a subclass that has the same signature as a method in a superclass. When that
method is called, the method in the subclass is found and executed instead of the one in
the superclass.
Create a method in your subclass that has the same signature (name, return type, and
parameter list) as a method defined by one of your class's superclasses, but change the
body arguments
Answer:
X is 0, Y is 1
I am an instance of the class PrintSubClass
A third class PrintSubClass2 is nearly identical to PrintSubClass, but you override the
printMe() method to include the z variable
x is 0, y is 1, z is 3
I am an instance of the class PrintSubClass2
Usually, there are two reasons why you want to override a method that a superclass has
already implemented:
To replace the definition of that original method completely (hide it) – done above
To augment the original method with additional behavior - This is particularly useful
where you end up duplicating behavior in both the original method and the method
that overrides it; by being able to call the original method in the body of the
overridden method, you can add only what you need – using the word
“super”
Rather than duplicating most of the behavior of the superclass's method in the subclass,
you can rearrange the superclass's method (PrintClass) so that additional behavior can
easily be added:
// from PrintClass
void printMe() {
System.out.println("I am an instance of the class" +
this.getClass().getName());
System.out.println("X is " + x);
System.out.println("Y is " + y);
}
Then, in the subclass, when you override printMe, you can merely call the original method
and then add the extra commands:
// From PrintSubClass2
void printMe() {
super.printMe();
System.out.println("Z is " + z);
}
Answer:
A subclass automatically inherits all methods and variables defined in its superclass.
We only use the command ―super‖ :
To instantiate the constructor of the superclass from the subclass e.g.1 p5
or
To call a method from the superclass instead of the compiler by hierarchy
default calling the one in the subclass e.g.2 p10
**operator checks if both object references refer to the same memory location
eg: if (a==b) means it verifies whether both a and b refer to the same location in
memory.
1) If you want to compare two basic types are equal, please use the = =;
2) If you want to compare two object references are equal, please use the = =;
3) If you want to compare two objects logically, please use the equals;
E.g.
1 String s1 = "STRING ME";
2 String s2 = "STRING ME";
3
4 System.out.println("s1: " + s1);
5 System.out.println("s2: " + s2);
6 System.out.println("s1 == s2 is " + (s1 == s2));
Nested Classes
The Java programming language allows you to define a class within another class. Such
a class is called a nested class
e.g.
class OuterClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}
Logical grouping of classes—If a class is useful to only one other class, then it
is logical to embed it in that class and keep the two together.
Increased ENCAPSULATION—Consider two top-level classes, A and B, where B
needs access to members of A that would otherwise be declared private. By hiding
class B within class A, A's members can be declared private and B can access
them. In addition, B itself can be hidden (private) from the outside world and only
seen by A.
More readable, maintainable code—Nesting small classes within top-level
classes places the code closer to where it is used.
The most common use of inner classes is as event handlers for GUI-based
applications. These classes are usually declared anonymously and as needed for
each component that requires an event handler. The advantage of using an inner
class for event handling is that you can avoid large If/else statements to decide
which component is being handled. Each component gets its own event handler,
so each event handler knows implicitly the component for which it's working.
Example:
In the following example, we will create an array, fill it with integer values (using a
constructor) and then output only values of even indices of the array in ascending order.
The DataStructure outer class, which includes methods to add an integer onto the
array and print out values of even indices of the array.
The InnerEvenIterator inner class, which is similar to a standard Java iterator
interface. Iterators are used to step through a data structure and typically have
methods to test for the last element, retrieve the current element, and move to
the next element.
A main method that instantiates a DataStructure object (ds) and uses it to fill the
arrayOfInts array with integer values (0, 1, 2, 3, etc.), then calls a printEven
method to print out values of even indices of arrayOfInts.
N.B. Iterators and other specific commands are outside scope of this course which is to
understand basic OOP concepts in Java and how to logically create coding.
class DataStructure {
//create an array
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
private DataStructure() {
//fill the array with ascending integer values
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
private void printEven() {
//print out values of even indices of the array
InnerEvenIterator iterator = this.new InnerEvenIterator();
while (iterator.hasNext()) {
System.out.println(iterator.getNext() + " ");
}
}
}
Answer:
0 2 4 6 8 10 12 14
Note that the InnerEvenIterator class refers directly to the arrayOfInts instance variable
of the DataStructure object.
N.B.
public DataStructure1() {
//fill the array with ascending integer values
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
public void printEven() {
//print out values of even indices of the array
InnerEvenIterator1 iterator = new InnerEvenIterator1();
while (iterator.hasNext()) {
System.out.println(iterator.getNext() + " ");
}
}
public static void main(String s[]) {
//fill the array with integer values and print out values of even indices
DataStructure1 ds = new DataStructure1();
ds.printEven();
}
}
Creating a Package
e.g.
package myFirstPackage.mySecondPackage;
public class MyPublicClass extends ItsSuperclass {
...
} guidance
The package is a folder that would contain classes. There can be several packages,
and thus folders, inside each other.
First declare the name of the package in a class by using a package statement,
then define the class
By convention, package names tend to begin with a lowercase letter to distinguish
them from class names
Any other classes also declared inside this same package name, are grouped
together
Packages can be organized into a hierarchy analogous to the inheritance hierarchy,
where each "level" usually represents a smaller, more specific grouping of classes
e.g. the java class library: The top level is called ―java‖ the next level e.g.
packages ―io, net, util, and awt‖ an even lower level, e.g. the package ―image‖
next e.g. the ColorModel class which can be referred to anywhere in Java code
as java.awt.image.ColorModel
The first level of the hierarchy specifies the (globally unique) name of the company
or software
The top-level package name reserves, all the uppercase abbreviations used for
top-level domains on the Internet (EDU, COM, GOV, FR, US, and so on). These
reserved names form the first part of all new package names
When the compiler generates the
―.class‖ file of a ―.java‖ file, it places it
into this same directory so that the java
interpreter can find it. Both the compiler
and the interpreter expect the hierarchy
When classes are defined without a
package statement, the compiler places
such classes in a default, unnamed
package, and their ―.java‖ and ―.class‖
files can be located in the current directory (or in the directory called classes below
it). On some systems, the Java class library's .class files are now located in an
archive file named classes.zip in the lib directory
MyPublicClass ;
myFirstPackage.MyPublicClass ;
If we want to use a class from a certain package many times, we can "import" the
name of that class into the beginning of the class coding
e.g.
import packagename.ClassName;
ClassName anObject;
// and you can use ClassName directly as many times as you like
N.B.
All import statements must appear after any package statement but before
any class definitions
e.g.
package javaapplication1;
import java.util.*;
public class VectorDemo{
If we want to use several classes from the same package, this is how to write it at
the beginning of the coding:
import packagename.*;
e.g.
import javax.swing.*;
The generic class is known as the parent (or superclass or base class) and the
specific classes as children (or subclasses or derived classes).
The concept of inheritance greatly enhances the ability to reuse code as well as
making design a much simpler and cleaner process
Java uses the extends keyword to set the relationship between a child class and a
parent class
You can reuse the superclass constructor and overridden superclass methods by
using the reserved word super. Note that this reference must come first in the
subclass constructor. The reserved word this is used to distinguish between the
object's property and the passed in parameter.
You cannot override final methods, methods in final classes, private
methods or static methods
Interfaces as APIs
Defining an Interface
e.g.
public interface OperateCar extends Interface1, Interface2, Interface3 {
// constant declarations, if any
// method signatures
Implementing an Interface
To declare a class that implements an interface:
Include ―implements‖ in the class declaration
Your class can implement more than one interface, so the implements keyword is
followed by a comma-separated list of the interfaces implemented by the class
the ―implements‖ clause follows the ―extends‖ clause
Implementing an interface means implementing all the methods specified in it
This means you cannot modify an interface later on by e.g. adding methods to it
because these will have to be implemented by its subclasses too.
E.g., here is a method for finding the largest object in a pair of objects, for any objects
that are instantiated from a class that implements Relatable:
N.B. nextInt(int n) Returns a random number, uniformly distributed int value between 0 (inclusive) and
the specified value (exclusive), drawn from this random number generator's sequence.
POLYMORPHISM
As mentioned, Polymorphism refers to “One Object, Many forms”
It is the ability of one object to be treated and used like other objects
It is manifested in several forms:
1. “method overriding” and “method overloading” (multiple methods having
the same name)
o Method Overloading or compile time polymorphism allows having
same method name in a class or a subclass, with different argument types
or numbers.
Overloaded methods may all be defined in the same class, or they
may be defined in different classes as long as those different
classes share a superclass - subclass relationship.
o Method Overriding means creating a new set of method statements for
the same method signature (name, number of parameters and parameter
types) within inherited subclasses, in 2 ways:
Replacement occurs when the code of the inherited method is not
executed at all, i.e. it is completely superceded by the code in the
overriding method.
Refinement augments an inherited method. This is accomplished
by calling, from within the overriding method, a superclass method
using the keyword ―super” or explicitly calling an ancestor method
with its fully qualified name (dot notation); thus the inherited code
is executed in the context of the subclass code
o N.B.
Overriding: java determines the proper methods to call at the
program’s run time
Overloading: java determines the proper methods to call at the
program’s compile time
2. ―late/dynamic method binding”
o Consider the shapes example above. The decision to fill the shape array
with a certain type does not occur until runtime. This is a special feature of
Java called ―late binding.‖ It is late binding that allows polymorphism to
work
3. Interfaces Increase Polymorphism: it stretches the ability of polymorphism
over many families of classes
Java Programming Language
Session 8
Abstract Classes - continued
Case Study 1
Create a package called “abstractApplication” and create five classes inside it to fill an
array with shapes and calculate their areas and parameters:
}}
Case Study 2: Payroll System Using Polymorphism
N.B. note the usage of the question mark colon operator question e.g. :
result = someCondition ? value1 : value2;
N.B.
“Constructors” don't create objects. They initialize them. The “new” operator
creates objects
Therefore All classes including abstract classes can have constructors.
Abstract class constructor will be called only when its concrete subclass is
instantiated. But you cannot create a new object of an abstract class using the
“new” operator
6 classes :
// constructor
public SalariedEmployee( String first, String last,
String socialSecurityNumber, double salary )
{
super( first, last, socialSecurityNumber );
setWeeklySalary( salary );
}
// constructor
public HourlyEmployee( String first, String last,
String socialSecurityNumber, double hourlyWage, double hoursWorked )
{
super( first, last, socialSecurityNumber );
setWage( hourlyWage );
setHours( hoursWorked );
}
// return wage
public double getWage()
{
return wage;
}
// constructor
public CommissionEmployee( String first, String last,
String socialSecurityNumber,
double grossWeeklySales, double percent )
{
super( first, last, socialSecurityNumber );
setGrossSales( grossWeeklySales );
setCommissionRate( percent );
}
// constructor
public BasePlusCommissionEmployee( String first, String last,
String socialSecurityNumber, double grossSalesAmount,
double rate, double baseSalaryAmount )
{
super( first, last, socialSecurityNumber, grossSalesAmount, rate );
setBaseSalary( baseSalaryAmount );
}
} // end main
} // end class
Case Study 3 : create several musical instrument classes which inherit from the
abstract class “instruments”
// Abstract class and methods
abstract class Instrument {
public abstract void play();
public String what() {
return "Instrument";
}
public abstract void adjust();
}
// subclass
package music;
class Wind extends Instrument {
public void play() {
System.out.println("Wind.play()");
}
public String what() { return "Wind"; }
public void adjust() {}
}
// subclass
package music;
class Percussion extends Instrument {
public void play() {
System.out.println("Percussion.play()");
}
public String what() { return "Percussion"; }
public void adjust() {}
}
// subclass
package music;
class Strings extends Instrument {
public void play() {
System.out.println("Strings.play()");
}
public String what() { return "Strings"; }
public void adjust() {}
}
// subclass
package music;
class Brass extends Wind {
public void play() {
System.out.println("Brass.play()");
}
public void adjust() {
System.out.println("Brass.adjust()");
}
}
// subclass
package music;
class Woodwind extends Wind {
public void play() {
System.out.println("Woodwind.play()");
}
public String what() { return "Woodwind"; }
}
Search Functions for Arrays & Dynamic Array
import java.util.*;
public class ArraySearchTest {
public static void main(String args[])
throws Exception {
int array[] = {2, 5, -2, 6, -3, 8, 0, -
7, -9, 4};
// Insert
int newIndex = -index - 1;
array = insertElement(array, 1, newIndex);
printArray("With 1 added", array);
}
private static void printArray(String message, int array[]) {
System.out.println(message + ": [length: " + array.length + "]");
// Print out sorted array elements
for (int i=0, n=array.length; i<n; i++) {
if (i != 0) System.out.print(", ");
System.out.print(array[i]);
}
System.out.println();
}
private static int[] insertElement(int original[], int element, int index) {
int length = original.length;
int destination[] = new int[length+1];
System.arraycopy(original, 0, destination, 0, index);
destination[index] = element;
System.arraycopy(original, index, destination, index+1, length-index);
return destination;
}
}
Selection Sort for Arrays
This uses the idea of finding the biggest item in the list and moving it to the end. Once
the biggest item is in its correct location, you can then apply the same idea to the
remaining items. That is, find the next-biggest item, and move it into the next-to-last
space, and so forth. This algorithm is called selection sort
}
Vectors
Vectors (the java.util.Vector class) are commonly used instead of arrays, because
they expand automatically when new data is added to them.
Vectors can hold only Objects and not primitive types (eg, int). If you want to put
a primitive type in a Vector, put it inside an object (eg, define your own class)
You must import either import java.util.Vector; or import java.util.*
Create a Vector with default initial size
Vector v = new Vector();
Create a Vector with an initial size
Vector v = new Vector(300);
To Add elements to the end of a Vector
v.add(s); // adds s to the end of the Vector v
v.addElement(new Float(1.9999));
To get the elements from a Vector (ListIterator)
You can use a for loop to get all the elements from a Vector, but another very
common way to go over all elements in a Vector is to use a ListIterator. The
advantage of an iterator is that it can be used with other data structures, so that if
you later change to using a linked list for example, you won't have to change your
code. Here is an example of using an iterator to print all elements (Strings) in a
vector. The two most useful methods are hasNext(), which returns true if there
are more elements, and next(), which returns the next element.
ListIterator iter = v.listIterator();
while (iter.hasNext()) {
System.out.println((String)iter.next());
}
BorderLayout
The content pane is the main container in all frames, applets, and dialogs. A
BorderLayout places components in up to five areas: top, bottom, left,
right, and center. All extra space is placed in the center area.
/*
* BorderLayoutDemo.java
*
*/
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
/**
* Create the GUI and show it.
*/
private static void createAndShowGUI() {
BoxLayout
The BoxLayout class puts components in a
single row or column. It respects the
components' requested maximum sizes and
also lets you align components
think of it as a version of FlowLayout, but with greater functionality
/*
* BoxLayoutDemo.java requires no other files.
*/
import java.awt.Component;
import java.awt.Container;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
* Create the GUI and show it.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("BoxLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
The CardLayout class lets you implement an area that contains different
components at different times. A CardLayout is often controlled by a combo
box, with the state of the combo box determining which panel (group of
components) the CardLayout displays.
/*
* CardLayoutDemo.java
*
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
pane.add(comboBoxPane, BorderLayout.NORTH);
pane.add(cards, BorderLayout.CENTER);
}
/**
* Create the GUI and show it.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("CardLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout
FlowLayout is the default layout manager for every JPanel. It simply lays
out components in a single row, starting a new row if its container is not
sufficiently wide. Both panels in CardLayoutDemo, shown previously, use
FlowLayout
/*
*
* FlowLayoutDemo.java
*
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
/**
* Create the GUI and show it.
*/
private static void createAndShowGUI() {
//Create and set up the window.
FlowLayoutDemo frame = new FlowLayoutDemo("FlowLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
frame.addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
GridBagLayout
GridBagLayout is a sophisticated, flexible
layout manager. It aligns components by
placing them within a grid of cells,
allowing components to span more than one cell. The rows in the grid can
have different heights, and grid columns can have different widths.
GridLayout
/*
* GridLayoutDemo.java
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Uses
If a container holds components whose size is not affected by the container's size or by
font, look-and-feel, or language changes. Desktop panes, which contain internal frames,
are in this category. The size and position of internal frames does not depend directly on
the desktop pane's size. The programmer determines the initial size and placement of
internal frames within the desktop pane, and then the user can move or resize the
frames. A layout manager is unnecessary in this situation.
Steps
/*
* AbsoluteLayoutDemo.java
*/
import java.awt.Container;
import java.awt.Insets;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
pane.add(b1);
pane.add(b2);
pane.add(b3);
/**
* Create the GUI and show it.
*/
Event Listeners
1. Beeper
• a button that beeps when you click it
• The Beeper class implements the ActionListener interface, which contains
one method: actionPerformed. Once the Beeper has been registered using
the Button addActionListener method, the Beeper's actionPerformed method
is called every time the button is clicked.
/*Beeper.java
*/
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JComponent;
import java.awt.Toolkit;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public Beeper() {
super(new BorderLayout());
button = new JButton("Click Me");
button.setPreferredSize(new Dimension(200, 80));
add(button, BorderLayout.CENTER);
button.addActionListener(this);
}
• addActionListener
• addItemListener
• addPopupMenuListener
Thus a combo box supports action, item, and popup menu listeners in addition to the
listener methods it inherits from JComponent
Because all Swing components descend from the AWT Component class, you can
register the following listeners on any Swing component:
component listener
focus listener
Listens for whether the component gained or lost the keyboard focus.
key listener
Listens for key presses; key events are fired only by the component that has the
current keyboard focus.
mouse listener
Listens for mouse clicks, mouse presses, mouse releases and mouse movement
into or out of the component's drawing area.
mouse-motion listener
Listens for changes in the mouse cursor's position over the component.
mouse-wheel listener
Examples: When the user clicks a button, chooses a menu item, presses Enter in a text
field. The result is that an actionPerformed message is sent to all action listeners that
are registered on the relevant component.
Steps:
1. Declare an event handler class and specify that the class either implements an
ActionListener interface or extends a class that implements an ActionListener
interface. For example:
Register an instance of the event handler class as a listener on one or more components
using the addActionListener method. When the user clicks the onscreen button, the
button fires an action event. This results in the invocation of the action listener's
actionPerformed method (the only method in the ActionListener interface). The single
argument to the method is an ActionEvent object that gives information about the event
and its source.
2. . For example:
someComponent.addActionListener(instanceOfMyClass);
3. Include code that implements the methods in listener interface. For example:
E.G.
import java.awt.*;
import java.awt.event.*;
super(title);
setLayout(new FlowLayout());
addWindowListener(this);
b = new Button("Click me");
add(b);
add(text);
b.addActionListener(this);
}
Internal Frame
Event
/*
InternalFrameEventDemo
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import
javax.swing.event.*;
public class
InternalFrameEventDemo
extends
JFrame
implements InternalFrameListener,
ActionListener {
JTextArea display;
JDesktopPane desktop;
JInternalFrame displayWindow;
JInternalFrame listenedToWindow;
static final String SHOW = "show";
static final String CLEAR = "clear";
String newline = "\n";
static final int desktopWidth = 500;
static final int desktopHeight = 300;
createDisplayWindow();
desktop.add(displayWindow); //DON'T FORGET THIS!!!
Dimension displaySize = displayWindow.getSize();
displayWindow.setSize(desktopWidth, displaySize.height);
}
displayWindow.setContentPane(contentPane);
displayWindow.pack();
displayWindow.setVisible(true);
}
public void internalFrameClosing(InternalFrameEvent e) {
displayMessage("Internal frame closing", e);
}
public void internalFrameClosed(InternalFrameEvent e) {
displayMessage("Internal frame closed", e);
}
public void internalFrameOpened(InternalFrameEvent e) {
displayMessage("Internal frame opened", e);
}
public void internalFrameIconified(InternalFrameEvent e) {
displayMessage("Internal frame iconified", e);
}
public void internalFrameDeiconified(InternalFrameEvent e) {
displayMessage("Internal frame deiconified", e);
}
public void internalFrameActivated(InternalFrameEvent e) {
displayMessage("Internal frame activated", e);
}
//Set its size and location. We'd use pack() to set the size
//if the window contained anything.
listenedToWindow.setSize(300, 100);
listenedToWindow.setLocation(
desktopWidth/2 - listenedToWindow.getWidth()/2,
desktopHeight - listenedToWindow.getHeight());
}
//Show the internal frame.
listenedToWindow.setVisible(true);
}
Mouse Listener
Mouse events notify when the user uses the mouse (or similar input device) to interact
with a component. Mouse events occur when the cursor enters or exits a component's
onscreen area and when the user presses or releases one of the mouse buttons.
/*
* BlankArea.java is used by:
* MouseEventDemo.java.
* MouseMotionEventDemo.java
*/
import javax.swing.*;
import java.awt.Dimension;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.*;
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLoo
kAndFeel");
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel")
;
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("MouseEventDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
public MouseEventDemo() {
super(new GridLayout(0,1));
blankArea = new BlankArea(Color.green);
add(blankArea);
textArea = new JTextArea();
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(200, 75));
add(scrollPane);
Java Programming
Test Assignment 2 Due: Sat 13/2/10
Create a class called Salaries to contain and do the following:
1. Create 4 single dimensional arrays containing the following information:
3. If the age of the employee is from 20 to 39, add a bonus for him of 1100
LE, then reduce 20% from this total sum for taxes. Print out the name
and final salary of each employee
4. If the age of the employee is not in the above categories, then print out
his name and say that he is not an employee
5. Find out how many people live in Cairo and print it out ( hint: use the
comma in your search / You can also use e.g. array[2].length()).
N.B. marks will be allocated for
• suitable names of variables,
• proper organization of coding and
• adding comments
/*
Salaries class
/*
Salaries class
*/
package salaries;
public class Main {
public static void main(String[] args) {
String[] names={"Ahmed Moussa","Hadeer Hassab","Ziad Amr","Maha Ellenby","Mohammed Abdou"} ;//names
array
int[]ages={65,23,42,35,75};//ages array
double[]salary={5500,2000,4000,3500,0};//salary array
String[]adreslocation={"Heliopolis","Elharam","Mohandseen","Tanta","Nasr city"};//location array
String[]adrescity={"Cairo","Giza","Cairo","Elgharbia","Cairo"};//citiesarray
//declaring variables
int agesi;
int empage;
String searchfor="Cairo";
System.out.println("******The Answers Of Q2, Q3 And Q4 :******");
for(agesi=0;agesi<ages.length;agesi++)
{
//any employee abpve 65 doesn't match any category
if (ages[agesi]>65)
System.out.println("Q4-"+"For "+ names[agesi]+"he is not an employee ");
// for employees above or equal 40 salary increase by 2200 having 10 % as taxes
else if (ages[agesi]>=40)
{salary[agesi]=((salary[agesi]+2200)*0.9);
System.out.println("Q2-"+"For "+ names[agesi]+" the new salary is : "+salary[agesi]);
}
//any employee above 39 doesn't match with having 40 criteria already specified
else if(ages[agesi] > 39)
System.out.println("Q4-"+"For "+ names[agesi]+"he is not an employee ");
// for employees above or equal 20 salary increase by 1100 having 20 % as taxes
else if (ages[agesi]>=20)
{salary[agesi]=((salary[agesi]+1100)*0.8);
System.out.println("Q3-"+"For "+ names[agesi]+" the new salary is : "+salary[agesi]);
}
}
//end of if statment
System.out.println(" ");
System.out.println("******The Answer Of Q5 :******");
for(agesi=0;agesi<adrescity.length;agesi++)
{if (adrescity[agesi]=="Cairo")
System.out.println("This employees lives in cairo :"+names[agesi]);
}
}
}
d) constructor
e) methods to set and get number of orders required by customer and number of side orders in
each order(hint: this info should be taken from customer in an array), method to calculate
total price of number of orders (by searching in both arrays for number of required side
dishes for each order and their prices), and method to represent the food object item
4. A subclass called “Beverages” containing:
a) attribute for number of drink orders required by customer
b) a single dimensional array containing type of beverage in each order taken from customer
c) two single dimensional arrays as follows (acting as a menu) showing price of each type of
beverage
Type of Fizzy (e.g. cola) Juice Water Milkshake
beverage
Serial number B01 B02 B03 B04
price 3.99LE 5.99LE 2.99LE 6.99LE
d) constructor
e) methods to set and get number of orders required by customer and type of beverage in each
order, method to calculate total price of number of orders (by searching in both arrays for
type of beverage for each order and their prices), and method to represent the beverage
object item
d) constructor
e) methods to set and get number of orders required by customer and type of dessert in each
order, method to calculate total price of number of orders (by searching in both arrays for
type of beverage for each order and their prices), and method to represent the beverage
object item
6. A class containing the business logic as follows:
a) Give the user a dialog box asking if he wants to order food, beverage or dessert
b) Whichever he chooses, make another dialog box appear asking him how many orders
c) Then make a dialog box appear for each order which allows him to choose the type of
food/beverage/dessert he wants
d) When these are finished give him another dialog box asking if he wants to order any more
items
e) If he says yes go back to point a) again and repeat the whole procedure. If he says no output
a message box containing the name / serial number / type of each order / its price. At the
very end of the message box show the total price of all the orders together obtained from:
f) Create a method to get the total orders’ prices returned from all the other classes and add
them all up
Good Luck
what does java virtual machine do
characteristics of an array
what is overriding, overloading, polymorphism (methods with same name in same class and superclass)
idea of IF statement
examples of code: arrays / for loops (nested) / while, continue , break / =,==,++, % /
types of variables / simple casting / &&, || / unreachable, non logic code