You are on page 1of 49

Lesson Proper for Week 1

Defining Java
Ø  Java is a high-level programming language developed by Sun Microsystems.
Ø  Java can be used to write applets (small applications running inside other applications hence the diminutive suffix
'let') but is not the only language that can produce applets.
History of Java
Ø  Java was developed at Sun Microsystems, Inc. (Sun) by James Gosling.
Ø  The language needed to be small, fast, reliable, and portable (hardware independent).
Ø  With the goals it had achieved (smallness, speed, reliability, portability), Java was discovered to be ideal for web
pages.
Ø  Java can also be used to write stand-alone applications.
 
Java Technology
Ø  A programming language
Ø  A development environment
Ø  An application environment
Ø  A deployment environment
 
Features of Java
Ø  Object-Oriented
o   Java uses classes to organize code into logical modules
Ø  Portable and Platform-Independent
o   Java is platform-neutral, which means that programs developed with Java can run on any computer system with
no changes
Ø  Dynamically Linked
o   Java codes are linked at runtime
Ø  Multithreaded
o   Java programs can contain multiple threads of execution
Ø  Garbage Collected
o   Java does its own garbage collection, which means that programs are not required to delete objects allocated in
memory
 
   Java Requirements
ü  Pentium D processor or higher
ü  At least 128MB of RAM
ü  Using an applet within a Web Browser with
ü  JDK plug-in
 
  Java Development Environment
Ø  Installing JDK (Java Development Kit) produces several folders in your system. Each of these folders holds
pertinent files that would be necessary in building your program. For instance, the bin folder contains executable files
for compiling your program (javac.exe).
 

   Java Development Environment – Using Path


Ø  Since javac.exe (the one that compiles your program) is located in the bin directory. It is necessary to execute this
command, by doing so you can now compile on any directory your program may be.

 Java Development Environment– Using CLASSPATH


Ø  The class path is used to tell Java where to look for classes. Set the environment variable CLASSPATH if there’s
a need to look for classes in different folders.
 Java Development Environment
Ø  The tool to be used for programming is called JCreator
Ø  You can get a copy of JCreator at
o   https://www.jcreator.com
Ø  Download the free version (JCreator LE).
Ø  Learn more about JCreator by surfing their sites  
   Other Java programming environment:

      Symantec Visual Café

      Microsoft J++

      Borland JBuilder

      IBM Visual Age for Java

      Sun Java Forte

      Java 2 SDK 1.4.2 FCS

 
  Applets and Applications
Ø  Java can be used to create two types of programs:
§  Applet
·         special applications designed to run within the context of a Web browser

§  Application
·         stand-alone program that does not need a browser to run
  Java Program Cycle

Ø  Use any text editor to create source code — .java file


Ø  Source code compiled according to JVM to get byte code — .class file
Ø  Byte code executed using an interpreter

 
 
Lesson Proper for Week 2

Java Program
      A minimum Java program has the following format:
public class <classname>{
public static void main (String[] args) {
<program statement>}}
 
        Java Coding Guidelines
Ø  Java program files must
o   Have same name as public class
o   End with extension .java
Ø  Use comments for documentation and readability
Ø  White spaces are ignored
Ø  Indent for readability
        Java Statements
Ø  A statement is one or more lines of code terminated by a semicolon.
 
Example:
 
                                    System.out.print(“Hello, World!”);
        Java Blocks
Ø  A block is formed by enclosing statements by curly braces.
Ø  Block statements can be nested indefinitely.
Ø  Any amount of white space is allowed.
 
Example:
public static void main (String[]args) {
System.out.println(“Hello”);
System.out.print(“World!”);}
         Java Comments
Ø  A comment is an optional statement used to describe what a program or a line of program is doing.
 
// This is a comment
/* This is a comment */
/** This is a special comment **/
o   Comment lines are ignored by the compiler.
public class Hello {
/**
* My First Java Program
*/
public static void main (String[] args) {
// print “Hello, World!” on screen
System.out.println(“Hello, World!”); }}
           
Java Identifiers
Ø  Identifiers used to label variables, methods, classes, etc.
Ø  Case-sensitive
Ø  May contain letters, digits, underscore and dollar sign ($)
Ø  May not start with a digit
Ø  May not use Java keywords
 
Java Identifiers Rules and Guidelines
 
Rules:
§  Identifiers can use alphabetic characters of either case (a–z and A–Z), numbers (0–9), underscores ( _ ), and
dollar signs ( $ ).
§  Identifiers cannot start with a number.
§  Keywords cannot be used as identifiers (for this reason keywords are sometimes called reserved words).
Guidelines:
§  Name your identifiers close to its functionality.
§  Method and variable names start in lowercase while classes start in uppercase.
§  For multi-word identifiers, either use underscores to separate the words, or capitalize the start of each word.
§  Avoid starting the identifiers using the underscore.

Java Identifier: Example

 
Java Keywords

          Java Literals


Ø  Literals are the representation of values.
o   Integers
o   Floating Point Numbers
o   Booleans (true or false)
o   Strings (enclosed in “ “)
o   Characters Java Literals (enclosed in ‘ ‘)
         Integer Literal
Ø  can be expressed in three different bases:
o   Octal (base 8)
o   Decimal (base 10)
o   Hexadecimal (base 16)

Floating Point Literal


Ø  appears in several forms
Ø  typical form makes use of digits and a decimal point
Ø  note that digits may appear before or after or before and after the decimal point
         Boolean Literal
Ø  only two Boolean literals  exist: true and false, representing the Boolean concepts of true and
false, respectively
 
        String Literal
Ø  sequence of characters within double quotes
Ø  the characters can be escape sequences
 
        Character Literal
Ø  Character literals come in two forms. They both use the single quote (‘ ’) as a delimiter. The
first form places the literal character between single quotes. Examples include 'a', '+', and '$'.
Ø  Some characters, such as the newline character, don't have visible literal representations. For
these, an escape sequence must be used, which consists
 
       Data Types
There are two kinds of data types:
Simple -  Built-in or primitive Java data types
Composite
Created by the programmer using simple types, arrays, classes, and interfaces
 
       Primitive Data types
The Java programming language defines eight primitive data types:
 
Ø  boolean (for logical)
Ø  char (for textual)
Ø  byte
Ø  short
Ø  int
Ø  long (integral)
Ø  double
Ø  float (floating-point)
 
       Boolean Data Type
Ø  one-bit wide and takes on the values true or false
Ø  default value: false
Ø  cannot be cast to a number or any other type
 
      Char Data Type
Ø  represents a 16-bit Unicode character
Ø  must have its literal enclosed in single quotes (‘’)
      Integer Data Type

 
 Floating Point Data Type
has types: float (32 bits single precision) and double (64-bit double precision)
                            
    Java Variables

Ø  A variable is an item of data used to store the state of objects.


Ø  A variable is composed of:
o   Data type – indicates the type of value that the variable can hold
o    Name – must follow rules for identifiers
 
        Declaring and Initializing Variables

A variable is declared as follows:


 
Note:
Values enclosed in <> are required values, while those values in [] are option
 
        Guideline in Declaring and Initializing Variables
1. Always initialize your variables as you declare them.
2. Use descriptive names for your variables.
3. Declare one variable per line of code.
 
        Java Variable Example

public class VarSample {


public static void main(String[]args){
boolean result;
char option;
option = ‘C’;
double grade = 0.0;}}
         Displaying Variable Data
Ø  To display the value of a certain variable, we use the following commands:
System.out.print()
System.out.println()
Example:
public class VarOutput {
public static void main(String[] args) {
int value = 10;
char x;
x = ‘A’;
System.out.println(value);
System.out.println(“The value of x = ” + x);}}
 
Ø  System.out.print()
o   Does not append newline at the end of the data output
Example:
System.out.print(“Hello”);
System.out.print(“World”);
Output:
HelloWorld
 
Ø  System.out.println()
o   Appends a newline at the end of the data output
Example:
System.out.println(“Hello”);
System.out.println(“World”);
Output:
Hello
World
 
          Types of Variables
 

Ø  Primitive Variables
o   variables with primitive data types
o   stores data in the actual memory location where the variable is
Ø  Reference Variables
o   variables that stores the address in the memory location
o   points to another memory location where the actual data is
           Constants

Ø  value never changes


Ø  Use the final type modifier in class definition
public class Variables {
public static void main(String[] args){
final double PI = 3.14;}}
Lesson Proper for Week 3

Java Expressions
Ø  An expression produces a result and returns a value.
Ø  An expression can be any combination of variables, literals, and operators.
Ø  Purposes of expressions:
o    to compute values
o    to assign values to variables
o    to control the flow of execution
Examples:
x = 5;
y = x;
z = x * y;
     Java Operators
Ø  Operators are special symbols that perform specific operations on one, two, or three operands, and then return a
result.
Operators used are:
o    Arithmetic
o    Increment and Decrement
o    Assignment
o    Relational
o    Logical
 
    Arithmetic Operators
 
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo
x = 6; // assign 6 to x
y = 4; // assign 4 to y
x = x + 2; // x is equal to 8
y = y - 3; // y is equal to 1
z = x * y; // z is equal to 8
z = x / y; // z is equal to 8
z = x % y; // z is equal to 0
 
 
     Increment and Decrement Operators
 
++ Pre/Post-Increment
- - Pre/Post-Decrement
if num = 5
z = num++ // z = 5
z = ++num // z = 6
 
    Assignment Operators
 
= Assignment
+= Addition
-= Subtraction
*= Multiplication
/= Division
%= Remainder
a = 8;
b = 12;
c = 3;
d = 15;
b += 1; // same as (b=b+1)
a -= 2; // same as (a=a-2)
c *= 2; // same as (c=c*2)
d /= 5; // same as (d=d/5)
 
     Relational Operators
           
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
!= Not equal to
 
Expression                   Result               Expression                    Result
3+4 == 7                       true                               3+4 < 10           true
3+4 != 7                        false                             3+4 <=              10 true
3+4 != 2+6                    true                               3+4 == 4+4       false
 
 
 
 Logical Operators
|| OR
^ Exclusive-OR
! NOT
 (3+2==5)                     &&                   (6+2==8) true
(4+3==9)                       &&                    (3+3==6) false
(3+6==2)                       ||                       (4+4==8) true
(5+7==12)                     ^                       (4+3==8) true
(5+7==12)                     ^                       (4+3==7) false
(4+3==5)                                                                false
!(4+3==5)                                                               true
 

Operator Precedence
 
 
 Exercises
 

Answer the following:


 
Assume: m=10
 
a.       3 – 2 + 5 + 6 – 1 = _______
b.       4 * (5 + 4) / 2 = _______
c.       5 % 2 + (2 * 8) = _______
d.       !((((m-2)*4)+15 / 5) == (15%3)*7)) result = _______
e.       !(m == 10) && (m+3 == 13) result = _______
 
Assume: b=6 and num=10
f.        num-=2 num = _______
g.  num = b + 3; = ________
- -num ;             num = _______
                           num- -;              num = _______
h. num += 2            num = _______
                         i. num = 11 % 3      num = _______

Lesson Proper for Week 4

Java Statements
Ø  In Java, a statement  is one or more lines of code ending with a semi-colon (;).
Ø  It generally contains expressions (expressions have a value).
 
Simple Statement
o   Basic building blocks of a program
o   One or more lines terminated by a semicolon (;)
Example:
System.out.println (“Hello, World!”);
Compound Statement or Block
o   Used to organize simple statements into complex structures
o   One or more statements enclosed by braces { }
o   Recommended to indent blocks for readability
Example:
public static void main (String[] args) {
System.out.println (“Hello, ”);
System.out.println (“World!”);}
      Java Control Structure
Ø  Control structures allow to change the ordering of how the statements in a program is executed
Types of control structures:
o    Decision control structures
§  allow to select specific sections of code to be executed
 
o   Repetition control structures
§  allow to execute specific sections of the code a number of times
    Decision Control Structures
Ø  Java statements that allows a programmer to select and execute Specific blocks of code while skipping other
sections.
Ø  If Structure
o   The if  statement specifies that a statement (or block of code) will be executed if and only if a certain Boolean
statement is true.
The general format of an if  statement is:
if (expression)
statement or block;
or
if (expression) statement;
Ø  Where expression represents a relational, equality, or logical expression (conditional expression).
Ø  If there is a need to execute several statements (compound statement), then left and right {} braces can group
these statements.
if (expression){
statement1;
statement2;…}
Every time Java encounters an if  statement,
 
1.       It determines whether expression is true or false.
2.       If expression is true, then Java executes statement.
3.       If expression is false, then Java ignores or skips the remainder of the if  statement and proceeds to the next
statement.
 
Ø  Making a decision involves choosing between two alternative courses of action based on some value within a
program.
 
Ø  If Structure: Example 1
o   Suppose that the passing grade on an examination is 75 (out of 100). Then the if statement may be written in Java
as:

Exercises
1.       Test if the value of the variable count is
greater than 10. If the answer is yes, print,
“Count is greater than 10”.
2.       Test if the value of the variable number
is an odd number. If the answer is yes, print
“This number is not an even number.”
3.       Test if the value of the variable age is
greater than 18 and less than or equal to 40. If
the answer is yes, print “You’re not getting
old!”
 
 
if (grade >= 75)

System.out.println(“You
Passed!”);
Ø  If Structure: Example 2
                   int grade = 68;
                   if (grade > 60){
                   System.out.println(“Congratulation s!”);
                   System.out.println(“You Passed!”);
 
 
Ø  If-Else Structure

o    The if-else  statement is used when you want to execute one statement if a condition is true, and another
statement if the condition is false.
The general format of an if-else  statement is:
if (expression)
statement1;
else
statement2;
or
if (expression) statement1;
else statement2;
 
Ø  As in the if statement, compound statements may also be used in if-else  statements (provided they be grouped
together by braces).
if (expression){
statement1;
statement2;
…}

Exercises
1.       Test if the value of the variable count is greater
than 10. If it is, print “Count is
greater than 10”, otherwise, print “Count is less than 10”.
2.       Test if the value of the variable number is an odd
number. If it is, print “This number is not an even
number” otherwise, print “This number is an odd
number.”
3.       Test if the value of the variable age is greater than
18 and less than or equal to 40. If it is, print “You’re not
getting old!” otherwise, print “You’re not getting
younger.”
 
 
else{

statement3;
statement4;
…}
 
Ø  If-Else Structure: Example
            int grade = 68;
            if (grade > 60)
            System.out.println(“Congratulations!”);
            else
           System.out.println(“Sorry you failed!”);
 
Ø  Nesting If and If-Else Structure
o   The statement in the else-clause of an if-else block can be another if-else structure.
The general format of an if-else-else if statement is:
if (expression 1) {
statement1;}
else if ( expression 2) {
statement2;}
else {
statement 3;}
 

Ø  Nesting If and If-Else Structure: Example


int grade = 68;
if(grade > 90) {
System.out.println(“Very Good”);}
else if(grade > 60) {
System.out.println(“Good”);}
else {
System.out.println(“Failed”);}
 
Common Errors
Ø  The condition inside the if-statement does not evaluate to a Boolean value
Ø  The variable number does not hold a Boolean value
Ø  Writing elseif instead of else if
Ø  Using = instead of == for comparison
 
Switch Structure
Ø  The switch  statement enables a program to switch between different outcomes based on a given expression.
The general format of a switch  statement is:
switch (switch_expression){
case 1:
statement1;
case 2:
statement2;
default:}
 
Ø  Every time Java encounters a switch  statement,
 
1.       It evaluates the switch expression, and jumps to the case whose selector matches the value of the expression.
2.       The program executes the statements in order from that point on until a break statement is encountered,
skipping then to the first statement after the end of the switch structure.
3.       If none of the cases are satisfied, the default block is executed. However, note that the default part is optional.
 
Ø  Unlike with the if statement, the multiple statements are executed in the switch statement without needing the curly
braces.
Ø  When a case in a switch statement has been matched, all the statements associated with that case are executed.
Not only that, the statements associated with the succeeding cases are also executed.
Ø  To prevent the program from executing statements in the subsequent cases, use a break statement as the last
statement.

Exercises
Ø  Analyze what happens when the following
code is executed with val equal to 10? 100?
1,000? Write a program to verify your answer.
 
switch (val){
case 10:
System.out.println("ten");
case 100:
System.out.println("hundred");
default:
System.out.println("thousand");}
 
 
Switch Structure: Example
switch (x){
case 1:
y = 1;
break;
case 2:
y = 2;
break;
case 3:
y = 3;
break;
default:
y = 0;}
 
 
Ø  Repetition Control Structures
o   Java statements that allows a programmer to execute specific blocks of code a number of times.
Ø  While Structure
o   The while  loop is a statement or block of statements that is repeated as long as some condition is satisfied.
The general format of a while  statement is:
while (boolean_expression){
statement1;
statement2}
Ø  While Structure: Examples
int counter = 1;
while (counter <= 10) {
System.out.println("counter = " + counter);
counter += 1;}
int counter = 1;
while (counter*counter < 1000) {
System.out.println(counter * counter);
counter++;}
Ø  Do-While Structure
o   The do-while loop is similar to the while-loop. The statements inside a do-while loop are executed several times
as long as the condition is satisfied.
The general format of a do-while statement is:
do{
statement1;
statement2
} while ( boolean_expression);
 
Ø  Do-While Structure: Examples
nt x = 0;
do {
System.out.println(“x = ” + x);
x++;}
 while(x < 10);
do {
System.out.println(“Hello!”);
} while (false);
 
Ø  For Structure
o   The for  statement instructs a program to perform a block of code a specified number of times.
The general format of a for  statement is:
for (initialization; condition;increment){
statement 1;
statement 2;}
 
Ø  For Structure: Examples
int x;
for(x=1; x<=10; x++){
System.out.println(“x= ” + x);}
int i;
for(i=0; i<10; i++){
System.out.println(i);}
 
Branching Statements
Ø  These statements redirect the flow of program execution.
These include:
o   Break Statement
§  The break statement causes an exit from an enclosing loop.
§        In other words, encountering the break  statement causes immediate termination of the loop.

§   Program control picks up at the code following the loop.

o   Break Statement: Example


§   This program segment will normally print all numbers between 1 to 100. But because of the break statement, only
the numbers between 1 to 50 will be printed.
for (ctr = 1; ctr <= 100; ++ctr) {
System.out.print(“\nctr = “ + ctr);
if (crt = = 50)
break;}
o   Continue Statement
§  The continue statement works in a somewhat similar way to the break  statement.
§  But instead of forcing loop termination, continue  forces the next iteration for the loop to take place, skipping any
code in between.
o   Return Statement
§   The return statement is used to exit from the current method.
§  Flow of control returns to the statement that follows the original method call.

Lesson Proper for Week 5

Arrays
Ø  Suppose there are three variables of type intwith different identifiers for each variable.
int number1;
int number2;
int number 3;
number1 = 1;
number2 = 2;
number3 = 3;
 
Ø  This seems like a tedious task in order to just initialize and use the variables especially if they are used for the
same purpose.
 
Ø  An array is a sequence of memory locations for storing data set out in such a way that any one of the individual
locations can be accessed by quoting its index  number.

Ø  The individual items within an array are called elements.


 
Declaring Java Arrays
Ø  To declare an array, write the data type, followed by a set of square brackets [], followed by the identifier name.
ElementType[] arrayName;
Example:
int[] x;
int[] ages;
Or equivalently
int x[];
int ages[];
 
Initializing Array Variables
Ø  To initialize an array, you use the new operator to allocate memory for objects. The new operator is followed by
the data type with the number of elements to allocate specified. The number of elements to be allocated is placed
within the [] operator.
Example:
name = new String[100];
age = new int[10];
 
Ø  Memory model for array storage

Ø  Like other variables, an array variable can be initialized when it is declared.


 
ElementType[] arrayName = new ElementType[sizeOfArray];
or
ElementType arrayName[] = new ElementType[sizeOfArray];
Example:
int[] x = new int[10];
int[] ages = new int[100];
 
Ø   An array can be also created by directly initializing it with data.
Example:
int[] arr = {1, 2, 3, 4, 5};
 
Ø  This statement declares and creates an array of integers with five elements, and initializes this with the values 1,
2, 3, 4, and 5.
Ø  Creates an array of Boolean variables with identifier results.
 
Ø  This array contains 4 elements that are initialized to values {true, false, true, false}.
boolean[] results = {true, false, true, false};
 
Ø  Creates an array of 4 double variables initialized to the values {100, 90, 80, 75}.
double[] grades = {100, 90, 80, 75};
 
Ø  Creates an array of strings with identifier days and initialized. This array contains 7 elements.
String[] days = {“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”};
Exercise:
Ø  Declare and create array variables for the following data:
o   An array of 15 doubles
o    An array of 20 strings
 
Accessing Array Element
Example:
//assigns 10 to the first element
in the array
ages [0] = 10;
//prints the last element in the
array
System.out.print(ages[99]);
 
Ø  To access an array element, or a part of the array, use a number called an index  or a subscript.
 
Ø  Index number or subscript
o   assigned to each member of the array, to allow the program to access an individual member of the array
o   an integer beginning at zero and progresses sequentially by whole numbers to the end of the array
o   Note:  index is from 0 to (sizeOfArray-1) Accessing an
Ø  The example below illustrates how to print all the elements in the array.
public class ArraySample {
public static void main(String[] args) {
int[] ages = new int[100];
for(int i=0; i<100; i++) {
System.out.print(ages[i]);}}}
 
Coding Guidelines
1.       It is better to create the array right away after you declare it.
 
int[] arr = new int[100];
 
2.       The elements of an n-element array have indexes from 0 to n-1. Note that there is no array element arr[n]! This
will result in an arrayindex- out-of-bounds exception.
 
3.       You cannot resize an array. However, you can create a new array of a different size, copy the desired data into
the new array, and assign the new array to the array variable.
 
Array Length
 
Ø  All array indices begin at 0. The number of elements in an array is stored as part of the array object in
the length  attribute.
Ø  Use the length attribute to iterate on an array as follows:
int list[] = new int[10];
for(int i = 0; i < list. length; i++){
System.out.println(list[i]);}
 
Array Manipulation
/** Array manipulation */
public class upavon{
public static void main(String[] args) {
int [] sizes = {31,28,31,30,31,30,31,31,30,31,30,31};
System.out.print("number ... ");
int month = (int) wellreader.read_number();
if (month < 1 || month > 12){
System.out.println("Not a valid month number");
} else {
System.out.print("That month has ");
System.out.print(sizes[month-1]);
System.out.println(" days");}
System.out.print("Length of sizes array: ");
System.out.println(sizes.length);
int day = month;
sizes = new int[7];
for (int k=0;k<7;k++) sizes[k]=24;
if (day < 1 || day > 7){
System.out.println("Not a valid day number");
} else {
System.out.print("That day has ");
System.out.print(sizes[day-1]);
System.out.println(" hours");}
System.out.print("Length of sizes array: ");
System.out.println(sizes.length);
}}
 
Multidimensional Arrays
Ø  Multidimensional arrays are implemented as arrays of arrays.
Ø  Multidimensional arrays are declared by appending the appropriate number of bracket pairs after the array name.
Example:
//integer array 512 x 128 elements
int[][] twoD = new int[512][128];
 //character array 8 x 16
char[][] twoD = new char[8][16];
//String array 4 rows x 2 columns
String[][] dogs = {{“terry”, “brown”},
{“kristin”, “white”},
{“toby”, “gray”},
{“fido”, “black”}};
 
Ø  Accessing an element in a multidimensional array is the same as accessing elements in a one dimensional array.
Example:
 
o   To access the first element in the first row of the array dogs, we write,
System.out.print(dogs[0][0]);
o   This will print the String “terry” on the screen.
 
Example
int[][] matrix = {{0, 1, 2, 3},
{1, 0, 3, 2}, {2, 3, 0, 1}, {3,
2, 1, 0}};
int row, col;
for(row = 0; row < 4; row++) {
for(col = 0; col < 4; col++){
System.out.print(“ ” + matrix[row][col]);
System.out.println();
}}
 

Lesson Proper for Week 7


Programming Paradigm
Procedural Programming
§  style of programming in which the programming task is broken down into a series of operations (called procedures)
applied to data (or data structures)
§  C and Pascalbject-Oriented Programming
§  extension of procedural programming
§  breaks down a programming task into a series of interactions among different entities or objects
§  Java, C++, and Smalltalk
Illustration of OOP
type of programming in which programmers define not only the data structures, but also the
types of operations (methods) that can be applied to the data structure
 
enables programmers to create modules that do not need to be changed when a new type of
object is added
 
most widely used paradigm
 
instead of focusing on what the system has to do, focus on:
§  what objects the system contains
§  how they interact towards solving the programming problem
 
Object-Oriented Programming

Advantages of OOP over conventional approaches:


§  It provides a clear modular structure for programs which makes it good for defining abstract data types where
implementation details are hidden and the unit has a clearly defined interface.
§  It makes it easy to maintain and modify existing code as new objects can be created with small differences from
existing ones.
§  It provides a good framework for code libraries where supplied software components can be
§  easily adapted and modified by the programmer. This is particularly useful for developing graphical user interfaces.
 
Key OOP concepts:
§  Objects
§  Classes
§  Abstraction
§  Inheritance
§  Encapsulation
§  Polymorphism
 
Objects and Classes
 
Objects
§  Represent things from the real world
§  Made up of
o   Attributes – characteristics that define an object
o   Method – self-contained block of program code similar to procedure
§  Example:
o   A cars attributes are make, model, year and purchase price
o   A cars method adre forward and backward
Classes
§  Term that describes a group or collection of objects with common properties
§  Define a type of object
§  Specifies a method and data that type of object has
§  Example
o   Employee
o   Car
Abstraction
§  allows a programmer to hide all but the relevant information (to the problem at hand)
about an object in order to reduce complexity and increase efficiency
§  closely related to encapsulation and information hiding
 Encapsulation
§  refers to the hiding of data (attributes) and methods within an object
§  protects an object’s data from corruption
§  protects the object’s data from arbitrary and unintended use
§  hides the details of an object’s internal implementation from the users of an object
§  separates how an object behaves from how it is implemented
§  easier to modify programs since one object type is modified at a time
 

Inheritance
§  the process by which objects can acquire (inherit) the properties of objects of other class
§  provides reusability, like adding additional features to an existing class without modifying it
 

Polymorphism
§  refers to the ability to process objects differently depending on their data type or class
§  the ability to redefine methods for derived classes
§  request for an operation can be made without knowing which specific method should be invoked
 

 
Abstract Classes
§  class that is not used to create (instantiate) objects
§  designed to act as a base class (to be inherited by other classes)
§  design concept in program development and provides a base upon which other classes are
built
§  can only specify members that should be implemented by all inheriting classes
Interfaces
§  allow you to create definitions for component interaction
§  provide another way of implementing polymorphism
§  specify methods that a component must implement without actually specifying how
The method is implemented

Lesson Proper for Week 8

What is GUI?
§  stands for Graphical User Interface
§  program interface that takes advantage of the computer’s graphics capabilities to make the
program easier to use
§  designed in 1970 by Xerox Corporation’s Palo Alto Research Center

Basic Components:
§  Pointer
§  Pointing device
§  Icons
§  Desktop
§  Windows
§  Menu
 
Basic GUI Objects
§  In Java, GUI-based programs are implemented by using the classes from the standard
javax.swing (Swing classes) and java.awt (AWT classes) packages.
§  All GUI classes are based on the fundamental classes in the Application Windowing Toolkit
or AWT.
§  A GUI program is composed of three types of software:
o   Graphical components that make up the Graphical User Interface
o   Listener methods that receive the events and respond to them
o   Application methods that perform the desired operations on the information
 
Abstract Window Toolkit
§  Java’s platform-independent windowing, graphics, and user-interface widget toolkit
§  part of the Java Foundation Classes (JFC) – the standard API (Application Program Interface) for providing
graphical user interfaces for Java programs
§  contains the fundamental classes used for constructing GUIs
 
Swing
§  graphical user interface toolkit in Java, which is one part of the Java Foundation Classes (JFC)
§  includes graphical user interface (GUI) widgets such as text boxes, buttons, splitpanes,
and tables
§  runs the same on all platforms
§  supports pluggable look and feel – not by using the native platform's facilities, but by
roughly emulating them
§  classes are often described as lightweight because they do not require allocation of native resources in the
operating system’s window toolkit
 
Swing Components
§  UI elements such as dialog boxes and buttons; you can usually recognize their names because they begin with J
§  Each Swing component is a descendant of a JComponent, which in turn inherits from
the java.awt.Container class
§  You insert the import statement
import javax.swing.*;
at the beginning of your Java program files so you can take advantage of the Swing UI
components and their methods
 
Using the JFrame Class
§  contains the most basic functionalities that support features found in any frame window,
such as minimizing the window, moving the window, and resizing the window
§  To design such a frame window, we define a subclass of the JFrame class and add methods
and data members that implement the needed functionalities.
Example 2:
import javax.swing.*;
public class MyFrame extends JFrame {
public void paint(Graphics g) {
g.drawString("A MyFrame
Object", 10, 50);}}
 
public class TestFrame1 {
public static void main(String[] args){
MyFrame frame = new MyFrame();
frame.setSize(150, 100);
frame.setVisible(true);}}
 
§  When a JFrame serves as a Swing application’s main user interface, you usually want the program to exit when
the user clicks Close. To change this behavior, you can call a JFrame’s
setDefaultCloseOperation() method and use one of the following four values as an
argument:
o   JFrame.EXIT_ON_CLOSE exits the program when the JFrame is closed.
o   WindowConstants.DISPOSE_ON_CLOSE closes the frame, disposes of the JFrame object, and keeps running
the application.
o   WindowConstants.DO_NOTHING_ON_CLOSE keeps the JFrame and continues running. In other words, it
functionally disables the Close button.
o   WindowConstants.HIDE_ON_CLOSE closes the JFrame and continues running; this is the default operations that
you frequently want to override.
 
Using the JPanel Class
§  the simplest Swing container
§  plain, borderless surface that can hold lightweight UI components, such as JButton, JCheckBoxes,

 
§  To add a component to a JPanel, the container’s add() method is called, using the
component as the argument.
§  In using a JPanel to hold components, the setContentPane() method is also used to
allow the JPanel to be set as a content pane so it can hold components.
 

 
 
 
 
 Lesson Proper for Week 9

Events and Event Handling


§  In Java, events represent all activity that goes on between the user and the application.
§  Like all Java classes, events are Objects that the user initiates.
§  The parent class for all event objects is named EventObject, which descends from the Object class.
§  EventObject is the parent of AWTEvent, which in turn is the parent of specific event classes such
as ActionEvent and ComponentEvent .
Programming
Event Listeners
§  Each event class shown in the table has a listener interface associated with it so that for
Every event class, such as <name>Event, there is similarly named <name>Listener
Interface.
§  Every <name>Listener interface method has the return type void, and each takes one
Argument – an object that is an interface of the corresponding <name>Event class.
§  Any object can be notified of an event as long as it implements the appropriate interface and is registered as an
event listener of the appropriate event source.
§  The class of the object that responds to an event must contain a method that accepts the event object created by
the user’s action.
§  In other words, when you register a component (such as JFrame) to be a listener for events generated by another
component (such as a JCheckBox), you need to write a method that reacts to any generated event.
Handling Mouse Events
§  The MouseMotionListener interface provides methods named mouseDragged()
and mouseMoved() that detect the mouse being rolled or dragged across a component surface.
§  The MouseListener interface provides methods named mousePressed() , mouseClicked() ,
and mouseReleased() that are similar to the keyboard event methods keyPressed() , keyTyped(),
and keyReleased() .
§  The MouseInputListener interface implements all the methods in both
the MouseListener and MouseMotionListener interfaces.
JComponent Class
§  All Swing components except top-level containers whose names begin with ―J ‖ descend from
the JComponent class (e.g., JPanel, JScrollPane, and JButton).
§  Inheritance Hierarchy of the JComponent clas
§  The JComponent class provides the following functionality to its descendants:
o   Tool tips
o   Painting and borders
o   Application-wide pluggable look and feel
o   Custom properties
o   Support for layout
o   Support for accessibility
o   Support for drag and drop
o   Double buffering
o   Key bindings
JLabel Class
§  A JLabel object can display either text or an image, or both. It cannot react to input events but is instead
commonly used to provide a label identifier for a nearby object that does.
§  The JLabel class uses three constants to align the component horizontally.
o   JLabel.LEFT
o   JLabel.RIGHT
o   JLabel.CENTER
§  One form of the constructor for JLabel is:
o   JLabel(String text, int horizontalAlignment);
§  This creates a JLabel instance with the specified text and horizontal alignment.
JTextComponent Class
§  The JTextComponent class provides a base class for Swing components that handle editable text.
§  It provides the functionalities for entering and editing text information—nearly all the features of a text editor.
§  JTextComponent has three direct subclasses—JTextField, JTextArea, and JEditorPane.
§  JTextField provides a component for entering and editing a single line of text.
§  A constructor for JTextField where the parameter specifies how many characters wide the field is.
o   JTextField(int numChars);
§  Another constructor for JTextField is:
o   JTextField(String text);
JTextArea Class
§  A JTextArea object displays multiple lines of text in a single font and style and optionally allows the user to edit the
text.
§  JTextArea does not handle scrolling, but implements the swing Scrollable interface.
§  JTextArea uses the rowsand columns properties to indicate the preferred size of the viewport when placed inside
a JScrollPane to match the functionality provided by java.awt.TextArea .
§  Constructors used for JTextArea
o   JTextArea(int rows, int columns) creates a new empty TextArea with the specified number of rows and
columns.
o   JTextArea(String text) creates a new TextArea with the specified text displayed.
o   JTextArea(String text, int rows, int columns) creates a new TextArea with the specified text and number of
rows and columns.
JList Class
§  JList class is used to display a list of items, such as list of students, a list of files, and so forth.
§  A JList object is constructed in a manner similar to the way a JComboBox object is constructed, that is, by
passing an array of String.
o   String[] names = {″Mark″,
o   ″Antonio″, ″Lea″, ″Sheila″};
§  JList list = new JList(names);
§  JList three selection modes:
o   single-selection
o   single-interval
o   Multiple-interval.
§  Statements show how to set the three selection modes:
o   list.setSelectionMode(ListSelectionModel. SINGLE_SELECTION);
o   list.setSelectionMode(ListSelectionModel. SINGLE_INTERVAL_SELECTION);
o   list.setSelectionMode(ListSelectionModel,MULTIPLE_INTERVAL_SELECTION);
JComboBox Class
§  The JComboBox is a component that combines two features:
o   display area showing an option, and
o   a list box containing additional options.
§  You can build a JComboBox by using a constructor with no arguments and then adding items (e.g., Strings) to the
list with the addItem() method.
JComboBox fruitChoice = new JComboBox();
fruitChoice.addItem(″Apple″);
fruitChoice.addItem(″Banana″);
fruitChoice.addItem(″Cherry″);
§  Alternatively, you can construct a JComboBox using an array of Objects as the constructor argument.
The Objects in the array become the listed items within the JComboBox.
String[] fruitArray = {″Apple, Banana, Cherry″};
JComboBox fruitChoice = new JComboBox(fruitArray);
AbstractButton Class
§  AbstractButton is an abstract base class of button and menu objects
(e.g., JButton, JToggleButton , JCheckBox, JRadioButton , and JMenuItem).
§  It defines much of the functionality for all button types.
§  Methods defined here are applicable to all subclasses.
JButton Class
§  JButtons act as push buttons which invoke some action when clicked. These are not buttons that are toggled on
and off.
§  To construct a JButton object, use the new keyword. Then add the button to the frame’s content pane.
The add() method of a content pane puts a JButton in the frame.
§  The getContentPane() method of a frame is used to get the reference to the content pane.
 
JToggleButton Class
§  JToggleButton is an extension of AbstractButton and is used to represent buttons that can be toggled on and off
(as opposed to buttons like JButton which, when pushed, "pop back up").
§  JToggleButton has two direct subclasses— JCheckBox and JRadioButton .JCheckBox Class
§  Creates four JCheckBox objects – one with no label and unselected, two with labels and unselected, and one with
a label and selected.
JCheckBox box1 = new JCheckBox();
JCheckBox box2 = new JCheckBox(″Check here″);
JCheckBox box3 = new JCheckBox(″Check here″, false);
JCheckBox box4 = new JCheckBox(″Check here″, true);
§  If you do not initialize a JCheckBox with a label and you want to assign one later, or if you want to change an
existing label, you can use the setText() method as in
box1.setText(″Check this box!″);
§  The state of a JCheckBox can be changed with the setSelected() method.
box1.setSelected(false);
§  The isSelected() method is used to check if a checkbox button is selected (i.e., has a check mark) or deselected.
§  When the status of a JCheckBox changes from unchecked to checked or vise versa, an ItemEvent is generated
and the itemStateChanged() method is executed.
§  You can use the getItem() method to determine which object generated the event and
the getStateChange() method to determine whether the event was a selection or a deselection.
§  The getStateChange() method returns an integer that is equal to one of two class variables
– ItemEvent.SELECTED or ItemEvent.DESELECTED .JRadioButton Class
§  Constructors of the JRadioButton:
o   JRadioButton(Icon icon, Boolean selected) creates a radio button with the specified image and selection state,
but no text.
o   JRadioButton(String text) creates an unselected radio button instance with the specified text.
o   JRadioButton(String text, boolean selected) creates a radio button with the specified text and selection state.
o   JRadioButton(String text, Icon icon) creates a radio button that has the specified text and image, and that is
initially unselected.
JScrollPane Class
§  The JScrollPane container can hold components that require more display area than they have been allocated.
§  The JScrollPane constructor takes one of four forms:
o   JScrollPane() creates an empty JScrollPane in which both horizontal and vertical scroll bars appear when
needed.
o   JScrollPane(Component) creates a JScrollPane that displays the contents of the specified component.
o   JScrollPane(Component, int, int) creates a JScrollPane that displays the specified component and includes both
vertical and horizontal scroll bar specification.
o   JScrollPane(int, int) creates a JScrollPane with both vertical and horizontal scroll bar specifications.
§  Creates a scroll pane displaying an image named picture, a vertical scroll bar, and no horizontal scroll bar.
JScrollPane scroll = new JScrollPane(picture, ScrollPaneConstants.VERTICAL_SCROLLBAR_ ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBA R_NEVER);
About Layout Managers
§  A layout manager is an object that controls the placement (size and position or layout) of components inside
a Container object.
§  Layout managers are interface classes that are part of the Java SDK. These align your components so they neither
crowd each other nor overlap.
§  Each layout manager defines methods that arrange components within a Container.
BorderLayout Class
§  BorderLayout divides a rectangular screen area into five regions—a central region surrounded by four border
regions.
§  The following class constants are the predefined names that identify the corresponding regions (by common
convention, North is assumed to be at the top):
o   BorderLayout.NORTH
o   BorderLayout.SOUTH
o   BorderLayout.EAST
o   BorderLayout.WEST
o   BorderLayout.CENTER
FlowLayout Class
§  The FlowLayout manager class provides a simple layout manager that is used, by default, by the JPanel objects.
§  It sizes each component according to its preferred size and arranges them in horizontal wrapping lines so that they
are evenly spaced.
§  The advantages of the FlowLayout manager include its ease of use, and the guarantee that each component can
be seen.
GridLayout Class
§  The GridLayout manager class arranges components in a grid within a container.
§  The GridLayout manager ignores the preferred size of each component and resizes them to exactly fit each cell's
dimensions.
§  When you create a GridLayout object, you indicate the numbers of rows and columns you want, and the container
space is divided into a grid accordingly.
§  To create a GridLayout object, we pass two arguments: number of rows and number of columns.
contentPane.setLayout(new GridLayout(2,3));
§  If the value provided for the number of rows is nonzero, then the value specified for the
§  number of columns is irrelevant. The layout will create the designated number of rows and adjust the number of
columns so that all components will fit in the designated number of rows.
CardLayout Class
§  The CardLayout manager generates a stack of containers or components, one on top of another.
§  Each card can be any component type (e.g., JButton, JLabel, or JPanel).
§  The CardLayout is used when you want multiple components to share the same display space.
§  A card layout is created from the CardLayout class using one of two constructors:
o   CardLayout() creates a card layout without a horizontal or vertical gap.
o   CardLayout(int hgap, int vgap) creates a card layout with the specified horizontal and vertical gaps. The
horizontal gaps are placed at the left and right edges. The vertical gaps are placed at the top and bottom edges.
 

 Lesson Proper for Week 10


Java Applet
Applets 
▪ In general, an applet is a small program or utility with limited features, requiring minimal resources, and usually
designed to run within a larger program. 
▪ A Java applet is such a program written in the Java programming language and typically designed to run from a
web browser. 
▪ An applet is designed to be called from within another document written in HTML. 
▪ When you create an applet, you do the following: 
o Write the applet in Java, and save it with a .java file extension, just as when you write a Java application. 
o Compile the applet into bytecode using the javac command, just as when you write a Java application. 
o Write an HTML document that includes a statement to call your compiled Java class. 
o Load the HTML document into a Web browser (such as Mozilla Firefox or Microsoft Internet Explorer), or open the
HTML document using the Applet Viewer. 
▪ The tag that begins every HTML document is , which is surrounded by angle brackets.
▪ The html within the tag is an HTML keyword that specifies that an HTML document follows the keyword. 
▪ The tag that ends every HTML document is

Three attributes of the given object tag: 


o code = followed by the name of the compiled applet you are calling 
o width = followed by the width of the applet on the screen 
o height = followed by the height of the applet on the screen NOTE: Instead of the tag pair, you can use the tag set in
your HTML applet host documents.
Running an Applet 
Two ways of running an applet: 
o by opening the associated HTML file on a Webbrowser 
o the appletviewer 
NOTE: The appletviewer is used mainly for testing applets. It is, in effect, a web browser that recognizes only the tags
associated with the execution of an applet. 
Writing a Simple Applet 
▪ In creating an applet, you must also do the following: 
o Include import statements to ensure that necessary classes are available. 
o Learn to use some user interface (UI) components, such as buttons and text fields, and applet methods. 
o Learn to use the keyword extends. 
▪ Creators of Java created an applet class named JApplet that you can import using the statement,
Lesson Proper for Week 11

Handling Events in an Applet


§  To respond to user events within any Applet you create, you must do the following:
o   Prepare your Applet to accept event messages.
o   Tell your Applet to expect events to happen.
o   Tell your Applet how to respond to the events.
Example
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class JHello extends JApplet implements ActionListener {


Container con = getContentPane();
JLabel question = new JLabel(″What’s your name?″);
JTextField answer = new JTextField(10);
JButton press = new JButton(″Press me″);
 
public void init() {
con.add(question);
con.add(answer);
con.add(press);
con.setLayout(new FlowLayout());
press.addActionListener(this);}
 
public void actionPerformed(ActionEvent e) {
String name = answer.getText();
System.out.println(″You pressed the button, ″ + name);}}
 
The Applet Life Cycle
§  There are four life cycle methods of an Applet class on which any applet is built.
o   init(): This method is called to initialize an applet.
o   start(): This method is called after the initialization of the applet.
o   stop(): This method is automatically called whenever the user moves away from the page containing applets.
o   destroy(): This method is only called when the browser shuts down normally.

Example
Using the setLocation() Method
§  The setLocation() method is used to place a component at a specific location within the Applet window.
§  Any component placed on the screen has a horizontal, or x-axis, position as well as a vertical, or y-axis, position on
the Applet window.
§  The upper-left corner of any display is position 0,0.

Example:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MoveJLabel extends JApplet
implements ActionListener {
Container con = getContentPane();
JLabel moveMsg = new JLabel(″STI Incorporated″);
JButton press = new JButton(″Press here″);
int xLoc = 20, yLoc = 20;
public void init() {
con.setLayout(new FlowLayout());
con.add(moveMsg);
con.add(press);
press.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
moveMsg.setLocation(xLoc+=10, yLoc+=10);
}
}
 
Using the setEnabled() Method
·         The setEnabled()
o   A method that can be use to make a component unavailable and then make it
available again.
o   Takes an argument of true if you want to enable a component, or false if you want to disable a component.
 
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MoveJLabel extends JApplet
implements ActionListener {
Container con = getContentPane();
JLabel moveMsg = new JLabel(″STI Incorporated″);
JButton press = new JButton(″Press here″);
int xLoc = 20, yLoc = 20;
public void init() {
con.setLayout(new FlowLayout());
con.add(moveMsg);
con.add(press);
press.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
moveMsg.setLocation(xLoc+=10, yLoc+=10);
if(yLoc == 280)
press.setEnabled(false);
}
}
 
 
 

 
 

You might also like