Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 59

Object-Oriented

Programming
Using JAVA
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.
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)
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
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
The Java Virtual Machine
• JVM provides definitions for the:
 Instruction set
 Register set
 Class file format
 Stack
 Garbage-collected heap
 Memory area
JVM

JAVA API
Class files Class Loader
Class files

bytecodes

Execution Engine

Native functions/methods

Operating System
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.
Sample Java Application

public class MyFirst {


public static void main(String[] args) {
System.out.println("Hello participants!");
}
}
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);
}
}
GETTING STARTED WITH JAVA

• The Java Developer’s Kit

• The Java API


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

Identifiers
Keywords
Literals
Separators
Operators
Comments
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.
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,
declarations, class identifiers, and expressions.

Reserved Words in Java


Declaration Keywords
boolean float
byte int
char long
double short
Loop Keywords
break
continue
do
for
while
Conditional Keywords
case
else
if
switch
Exception Keywords
catch
finally
throw
try
Structure Keywords
abstract implements
class instanceof
default interface
extends

Modifier and Access Methods


final static
native synchronized
new threadsafe
private transient
protected void
public
Miscellaneous Keywords
false return
import super
null this
package true

Byvalue inner
Cast operator
Const outer
Future rest
Generic var
goto
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
hexadecimal (base 16).
- can be positive, zero or negative.
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.
2. 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-precision.


- therefore 4.8, is a double-precision floating-point number, and
4.8f is a single-precision floating-point number.
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
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.


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


--> ‘\’’
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
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 denote


symbols that otherwise would not work.
Example : the double quote is represented by
--> “\””
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.
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 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 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 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
Logical Operators

! for NOT

Short circuit boolean operators

&& for AND

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

|| for OR

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


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.
Comment Indicators

Start Text End Comment


/* Text */
/** Text */
// Text (everything to the end of the
line is ignored by the
compiler)
Primitive Data Types
- can only have one value at a time, they cannot
reference other data or indicate sequence in a group
of data.
- simplest built-in forms of data in Java.

Primitive Data Type Keywords


boolean
byte
char
int
float
double
long
short
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.
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.
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
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
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
Expression Evaluation Order
- Java evaluates from LEFT to RIGHT
Precedence Rules
Highest Lowest
[] ()
-- ! ~ instanceof
new (type) expression
* / %
+ -
<< >> >>>
< > <= >=
== !=
&
^
&&
||
?:
= Op=
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
Arrays

char myCharArray[]; //one-dimensional array


char twoDimArray[][]; //two-dimensional array
int integerArray[]; //one-dimensional array of integers
int[]integerArray; //equivalent to integerArray[];
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
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.
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
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);
}
Sample if Statement

int number=10;
if ( (number % 2) == 0) {
System.out.println(“even”);
}
else {
System.out.println(“odd”);
}
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;
}
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;
}
}
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);
}
Sample while loop

public static long factorial(int n) {


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

Form:

do statement; while ( expression) ;

or

do {
statement(s);
}while (expression) ;
Sample do-while loop

public static long factorial(int n) {


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

Form:

for (initialization; expression; modification)


statement;

or

for (initialization; expression; modification) {

statement(s);

}
Sample for loop

public static long factorial(int n) {


long prod = 1;
for (int i=1; i <= n; i++) {
prod *= i;
}
return prod;
}
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]);
}
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]);
}
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);

You might also like