Anda di halaman 1dari 63

University of the Philippines Cebu College

Object-Oriented
Programming
Using JAVA

Java Programming Language


University of the Philippines Cebu College

Course Overview
This course covers the following areas:
• Fundamentals of the Java programming
language.
• Object-oriented concepts in Java.
• Graphical user interface (GUI)
programming.
• Introduction to Multi-threading.

Java Programming Language


University of the Philippines Cebu College

What is Java?

Java is just a small, simple, safe,


object-oriented, interpreted or
dynamically optimized, byte-coded,
architecture-neutral, garbage-
collected, multithreaded programming
language with a strongly typed
exception-handling mechanism for
writing distributed, dynamically
extensible programs.

Java Programming Language


University of the Philippines Cebu College

Small, simple, safe and garbage


collected
• C++ minus (pointers and memory
management have been omitted;
operator overloading and multiple
inheritance have been omitted)
• garbage collector automatically frees
unused memory
• strict type checking mechanism (most
errors are detected at compile time)

Java Programming Language


University of the Philippines Cebu College

Interpreted, byte-coded, architecture


neutral
Java Source
filename.java
javac filename.java

Java ByteCode
Filename.class

java filename

VM Java VM Java VM Java


NT Unix OS/2

Java Programming Language


University of the Philippines Cebu College

The Java Virtual Machine


• Provides hardware platform specifications
• Reads compiled byte codes that are
platform independent
• Is implemented as software or hardware
• Is implemented in a Java technology
development tool or a Web browser

Java Programming Language


University of the Philippines Cebu College

The Java Virtual Machine


• JVM provides definitions for the:
 Instruction set
 Register set
 Class file format
 Stack
 Garbage-collected heap
 Memory area

Java Programming Language


University of the Philippines Cebu College

JVM
JAVA API
Class Class Loader Class
files files

bytecodes

Execution Engine

Native
functions/methods
Operating System

Java Programming Language


University of the Philippines Cebu College

Class Loader

Method Heap Stack Registers Constant


Area Pool

Runtime Data Areas

Execution Engine

Java Programming Language


University of the Philippines Cebu College

Two types of Java programs

Applets are programs written in Java


programming language that reside on
WWW servers, are downloaded by a
browser to a client’s system, and are run
by that browser.
Applications are standalone programs
that do not require a Web browser to
execute. They are typically general-purpose
programs that run on any machine where
the Java runtime environment (JRE) is
installed.
Java Programming Language
University of the Philippines Cebu College

Sample Java Application

public class MyFirst {


public static void main(String[] args) {
System.out.println("Hello participants!");
}
}

Java Programming Language


University of the Philippines Cebu College

Sample Java Applet

import java.applet.*;
import java.awt.*;

public class MyFirstApplet extends Applet {

public void paint(Graphics g) {


g.drawString("Hello participants!",50,50);
}
}

Java Programming Language


University of the Philippines Cebu College

GETTING STARTED WITH JAVA

• The Java Developer’s Kit

• The Java API

Java Programming Language


University of the Philippines Cebu College

public class MyFirst {


public static void main(String[] args) {
System.out.println(“Hello world!”);
}
}

Java Programming Language


University of the Philippines Cebu College

J ava Tokens

I dentifiers
Keywords
Literals
Separators
Operators
Comments

Java Programming Language


University of the Philippines Cebu College

Identifiers

- either reserved words or titles given to variables, methods,


and component elements of classes.

- can be named anything as long as they begin with an


alphabet, a dollar sign or an underscore

- the more descriptive the identifier, the better

- case sensitive.

Java Programming Language


University of the Philippines Cebu College

Keywords
- are reserved words, meaning they cannot be used
in
any way other than how Java intends for them to
be
used.
- these special tokens are always in lowercase.
- these are used as application flow controls,
Reserved Words class
declarations, in Java
identifiers, and expressions.
Declaration Keywords
boolean float
byte int
char long
double short
Java Programming Language
University of the Philippines Cebu College

Loop Keywords
break
continue
do
for
while
Conditional Keywords
case
else
if
switch
Exception Keywords
catch
finally
throw
try
Java Programming Language
University of the Philippines Cebu College

Structure Keywords
abstract implements
class instanceof
default interface
extends

Modifier and Access Methods


final static
native synchronized
new threadsafe
private transient
protected void
public

Java Programming Language


University of the Philippines Cebu College

Miscellaneous Keywords
false return
import super
null this
package true

Byvalue inner
Cast operator
Const outer
Future rest
Generic var
goto

Java Programming Language


University of the Philippines Cebu College

Literals
- represent data in Java, and are based on character and
number representations.
- types of literals : integer, floating-point, boolean,
character,
and string.
- every variable consists of a literal and a data type; the
difference between the two is that literals are entered
explicitly into the code, while data types are information
about how much room will be reserved in memory for
such
variable, as well as possible value ranges.

Types of Literals
1. Integer Literals
- whole numbers such as 8 and 1930.
- can either be decimal(base 10), octal (base 8) or
Java Programminghexadecimal
Language (base 16).
University of the Philippines Cebu College

Integer Literal Types


a. Decimal Literals
- decimal literals cannot start with 0, as in 02364, because
numbers beginning with 0 are reserved for octal and
hex literals.
- decimal literals : any combination from 0-9.

b. Octal Literals
- start with 0 and can be followed by any number 0-7.

c. Hex Literals
- start with 0x or 0X, followed by one or more hex digits.
- letters A-F in hex integer can either be in upper or lower
case.
- values available : 1-9, A-F, and 1-f.

Java Programming Language


University of the Philippines Cebu College

. Floating-Point Literals
- represents a number that has a decimal point in it such as 4.8

Single-Precision Floating Point Numbers


- consist of a 32-bit space and are designated by uppercase
or lowercase f.

Double-Precision Floating Point Numbers


- consist of a 64-bit space and are designated by uppercase
or lowercase d.

- by default, unless specified, compiler assumes double-precisio


- therefore 4.8, is a double-precision floating-point number, and
4.8f is a single-precision floating-point number.

Java Programming Language


University of the Philippines Cebu College

When to use Single-Precision or Double-Precision Floats ?


- it depends on the size of the number, like if there’s a
room to grow out of range or there’s a need of
greater precision, declare it double.
- compile-time errors occur if a nonzero float literal is out
of range.

Range :
Single-Precision : ±1.40239846e-45f to ±3.40282347e+38f
Double-Precision: 4.94065645841246544e-324 to
±1.79769313486231570e+308

- Floating-point numbers can also be expressed using


exponents using uppercase or lowercase e, and
scientific notations.
Example : 2.1e3f = 2100
Java Programming Language
University of the Philippines Cebu College

Boolean Literals

- either of the words true or false.


- unlike other programming language, you cannot
alternate numeric values such any nonzero for true
and zero(0) for false.

- Booleans are used extensively in control flow logic.

Java Programming Language


University of the Philippines Cebu College

Character Literals

- programmers often use single character as a value,


and in Java, this is represented by character literals.

- value : character enclosed in single quotes like ‘j’

- values such as a single quote, backslash, or other


nonprintable characters are preceded by a
backslash(\) to be part of the command.

Example : to characterize the single quote


--> ‘\’’

Java Programming Language


University of the Philippines Cebu College

Specifying Character Literals


Description or Escape Sequence Output
Sequence
Any character 'y' y
Backspace(BS) '\b' Backspace
Horizontal tab (HT) '\t' Tab
Linefeed(LF) '\n' Linefeed
Formfeed(FF) '\f' Form feed
Carriage return (CR) '\r' Carriage return
Double quote '\"' "
Single quote '\'' '
Backslash '\\' \
Octal bit pattern '\ddd' Octal value of ddd
Hex bit pattern '\xdd' Hex value of ddd
Unicode character '\udddd' Actual unicode character
of dddd

Java Programming Language


University of the Philippines Cebu College

String Literals
- sequence of characters enclosed in double quotes
such
as “Hello World !!!”, or even a “” for a null
character string.

- can be concatenated.
Example :
“This is the beginning“ -- one string
“ of a new relationship.” -- another
string

“This is the beginning” + “ of a new relationship.”

- As with character literals, the backslash is used to


Javadenote
Programming Language
University of the Philippines Cebu College

Separators

- Java uses the following separators :


() [] {} ; , .

- compiler uses these to divide the code into segments.

- can also be used to force arithmetic precedence


evaluation within an expression.

- as known, these are useful for visual and logical


locators for programmers.

Java Programming Language


University of the Philippines Cebu College

Operators
- are symbols used for arithmetic and logical operations.
- operators except the plus sign (+), are used only for
arithmetic calculations. The + operator can be used
in strings literal concatenation.

Java Arithmetic Operators


Operator Operation Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * B
/ Division a / b
% Modulus a % b

Java Programming Language


University of the Philippines Cebu College

Java Assignment Operators


Operator Operation Example Meaning
= Assign value a = 8 a = 8
+= Add to current variable a += b a = a + b
-= Subtract from current a -= b a = a - b
*= Multiply current a *= b a = a * b
/= Divide current a /= b a = a / b
%= Modulus current a %= b a = a % b
Java Increment and Decrement Operators
Operator Operation Example Meaning
++ Increment by 1 a++ or ++a a = a + 1
Decrement by 1 a-- or --a a = a - 1
--
Java Programming Language
University of the Philippines Cebu College

Java comparison operators (which return true or false)


Operator Operation Example Meaning
== Equal A == b Is a equal to b ?
!= Not equal A != b Is a not equal to
b?
< Less than A < b Is a less than b?
> Greater than A > b Is a greater than
b?
<= Less than or A <= b Is a less than or
equal equal to b?
>= Greater than or A >= b Is a greater than
equal or equal to b?

Java Programming Language


University of the Philippines Cebu College

Java Bitwise Operators


Operator Operation
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Left Shift
>> Right Shift
>>> Zero fill right shift
~ Bitwise complement
<<= Left shift assignment
>>= Right shift assignment
>>>= Zero fill right shift assignment
x&=y AND assignment
X|=y OR assignment
x^=y XOR assignment
Java Programming Language
University of the Philippines Cebu College

Logical Operators

! for NOT

Short circuit boolean operators

&& for AND

((a >=b) && (b>=c))

|| for OR

((a>=b) || (b >= c))

Java Programming Language


University of the Philippines Cebu College

Right­Shift Operators >> and >>>
•Arithmetic or signed right shift (>>) is used as follows: 
128 >> 1 returns 128/21 = 64
256 >> 4 returns 256/24 = 16
-256 >> 4 returns -256/24 = -16

•The sign bit is copied during the shift. 
A logical or unsigned right­shift operator (>>>) is: 
•Used for bit patterns. 
•The sign bit is not copied during the shift. 

Java Programming Language


University of the Philippines Cebu College

Left­Shift Operator (<<) 
•Left­shift works as follows: 
128 << 1 returns 128 * 21 = 256
16 << 2 returns 16 * 22 = 64

Java Programming Language


University of the Philippines Cebu College
String Concatenation With +

•The + operator: 
•Performs String concatenation 
•Produces a new String: 
String salutation = "Dr.";
String name = "Pete" + " " + "Seymour";
String title = salutation + " " + name;

•One argument must be a String object. 
•Non­strings are converted to String objects 
automatically. 

Java Programming Language


University of the Philippines Cebu College

Comment Indicators

Start Text End Comment


/* Text */
/** Text */
// Text (everything to the end of the
line is ignored by the
compiler)

Java Programming Language


University of the Philippines Cebu College

Primitive Data Types


- can only have one value at a time, they
cannot
reference other data or indicate sequence in
a group
of data.
Primitive
- simplest built-inData Type
forms Keywords
of data in Java.
boolean
byte
char
int
float
double
long
short

Java Programming Language


University of the Philippines Cebu College

Integer Data Type


Ranges
Type Length Minimum Value Maximum Value
byte 8 bits -128 127
short 16 bits -32768 32767
int 32 bits -2147483648 147483647
long 64 bits -9223372036854775808 9223372036854775807

Note : During operations, on special cases Java expands


smaller integer to the same length in memory
of the larger integer, and the resulting value
will follow the format of the larger integer.

Java Programming Language


University of the Philippines Cebu College

char Data Types

- 16 bit unsigned integer that represents a


Unicode value.

Floating Point Data Types


float
- 32 bit floating-point number.

double
- 64 bit floating-point number.

boolean Data Types


- 1-bit logical quantity.
Java Programming Language
University of the Philippines Cebu College

Reference Data Types


- are sequence or identifiers that point to
dynamically
allocated objects.

Reference vs Primitive Data Type


- contains the address of a value, rather than the
value itself.
Advantage
- can contain addresses that point to a collection of
other
data types.
Types
1. Array
2. Class
3. Interface
Java Programming Language
University of the Philippines Cebu College

Casting 
If information might be lost in an assignment, the 
programmer must confirm the assignment with a cast. 
•The assignment between long and int requires an explicit 
cast.
 long bigValue = 99L;
int squashed = bigValue; // Wrong, needs a cast
int squashed = (int) bigValue; // OK

int squashed = 99L; // Wrong, needs a cast


int squashed = (int) 99L; // OK, but...
int squashed = 99; // default integer literal

Java Programming Language


University of the Philippines Cebu College

Promotion and Casting of Expressions 
•Variables are automatically promoted to a longer form 
(such as int to long). 
•Expression is assignment­compatible if the variable type is 
at least as large (the same number of bits) as the 
expression type. 

long bigval = 6; // 6 is an int type, OK


int smallval = 99L; // 99L is a long, illegal

double z = 12.414F; // 12.414F is float, OK


float z1 = 12.414; // 12.414 is double, illegal
Java Programming Language
University of the Philippines Cebu College

Expression Evaluation Order


- Java evaluates from LEFT to RIGHT
Precedence Rules
Highest Lowest
[] ()
-- ! ~ instanceof
new (type) expression
* / %
+ -
<< >> >>>
< > <= >=
== !=
&
^
&&
||
?:
= Op=

Java Programming Language


University of the Philippines Cebu College

Sample Declarations

Integer types
byte byteVar; //8 bits
short shortVar; //16 bits
int intVar; //32 bits
long longVar; //64 bits

Floating-Point Types
float floatVar; //32 bits
double doubleVar; //64 bits

Character Types
char charVar1; //holds one character
char charVar2 = ‘y’; //declares variable
//
and assigns y to it
Java Programming Language
University of the Philippines Cebu College

Arrays
char myCharArray[]; //one-dimensional array
char twoDimArray[][]; //two-dimensional array
int integerArray[]; //one-dimensional array of integers
int[]integerArray; //equivalent to integerArray[];

Java Programming Language


University of the Philippines Cebu College

Sample Operations

Unary Operations
myHeight++; //myHeight is incremented by 1
myWeight--; //myWeight is decremented by 1

Assignment Operations
a = 5; //assigns 5 to a
a -= 7; //assigns a-7 to a
a +=8 //assigns a+8 to a
a /=4 //assigns a/4 to a

Binary Operations
c = b + 5; // b+5 is the binary operation

Arithmetic Operations
a = c / b + (45*a/d) - 283
Java Programming Language
University of the Philippines Cebu College

Control Flow

- instructs the program how to make a decision and how


further processing should proceed based on the decision.

Building Blocks of Control Flow

( , ) , if , while , do, for, switch

- each of these can be used to control how your


program executes by determining the result of your
conditional expression.

Java Programming Language


University of the Philippines Cebu College

Blocks and Statements

Statement

- is a line of code ending in a semicolon.


- can either be an expression, a method call, or an declaration.

Block

- is a group of statements that form a single compound stmt.


- { } collects statements into one group

Java Programming Language


University of the Philippines Cebu College

Conditional Expressions

- are used to evaluate whether a condition is true or false


and will branch out to different sections of code on the
basis of the answer.

if construct

if (expression) statement;

if (expression) {
statement(s);
}

Java Programming Language


University of the Philippines Cebu College

Sample if Statement

int number=10;
if ( (number % 2) == 0) {
System.out.println(“even”);
}
else {
System.out.println(“odd”);
}

Java Programming Language


University of the Philippines Cebu College

switch construct
- a variation of the if statement is the switch statement, which
performs a multi-way branch instead of a simple binary
branch.

Form :
switch (expression) {
case value : statement(s);
break;
case value : statement(s);
break;
. . . . . . .
default : statement(s);
break;
}

Java Programming Language


University of the Philippines Cebu College

Sample switch Statement

static void ParseChar (char KeyboardChar) {


switch (KeyboardChar) {
case ‘l’: System.out.println(“left”);
break;
case ‘r’: System.out.println(“right”);
break;
case ‘q’: //note no break here, falls through
case ‘\n’: break;
case ‘h’ : //note no break here either

default :
System.out.println(“Syntax: (l)eft, (r)ight, (q)uit”);
System.out.println(“Please enter a valid character”);
break;
}
}
Java Programming Language
University of the Philippines Cebu College

Looping Expressions

- generally continues to loop through a section of code until


a certain condition is met.
- conditions are checked before or after executing code
sections depending on the loop construct used.

while loops
Form:
while ( expression ) statement;

or

while ( expression ) {
statement(s);
}

Java Programming Language


University of the Philippines Cebu College

Sample while loop

public static long factorial(int n) {


long prod = 1;
int i = 1;
while ( i <= n ) {
prod *= i++;
}
return prod;
}

Java Programming Language


University of the Philippines Cebu College

do-while loops

Form:

do statement; while ( expression) ;

or

do {
statement(s);
}while (expression) ;

Java Programming Language


University of the Philippines Cebu College

Sample do-while loop

public static long factorial(int n) {


long prod = 1;
int i = 1;
do {
prod *= i++;
} while ( i <= n);
return prod;
}

Java Programming Language


University of the Philippines Cebu College

for loops

Form:

for (initialization; expression; modification)


statement;

or

for (initialization; expression; modification) {

statement(s);

Java Programming Language


University of the Philippines Cebu College

Sample for loop

public static long factorial(int n) {


long prod = 1;
for (int i=1; i <= n; i++) {
prod *= i;
}
return prod;
}

Java Programming Language


University of the Philippines Cebu College

break

- used to break out of the middle of for, while, or do loop.

Sample Code :

for (int index=0; index < ArraySize; index++) {


if (Array[index] < 0) {
System.out.println(“ERROR: Negative number, index =“ + ix);
break;
}
ProcessArray(Array[index]);
}

Java Programming Language


University of the Philippines Cebu College

continue

- can be used to short-circuit parts of a for, do, or while loop.

Sample Code :

for (int index=0; index < ArraySize; index++) {

if (Array[index] < 0) {
System.out.println(“ERROR: Negative number, index =“ + ix);
continue;
}
ProcessArray(Array[index]);
}
Java Programming Language
University of the Philippines Cebu College

Using break with labels:  Using continue with labels: 
outer: test:
do do
{ {
statement; statement;
do { do{
statement; statement;
if (boolean expression) if (condition is true)
{ {
break outer; continue test;
} }
statement; statement;
} while (boolean expression); } while (condition is true);
statement; statement;
} while (boolean expression); } while (condition is true);

Java Programming Language