Sie sind auf Seite 1von 72

CSC435

Object Oriented Programming

CHAPTER 2
Java Programming Basics

MISS NUR LAILA BTE AB GHANI


Faculty of Computer and Mathematical Sciences
Universiti Teknologi MARA

Content
Data Types
Primitives

Object

Control Structures
Sequence
Selection

Repetition

Array of Primitives

The Basics of a Java Program


Java program: A collection of classes.
There is a main method in every Java
application program.
Token: The smallest individual unit of a
program.

Special Symbols

Word Symbols

int
float
double
char

void
public
static
throws
return

Java Identifiers
Names of things.
Consists of:
Letters
Digits
The underscore character (_)
The dollar sign ($)

Must begin with a letter, underscore, or the


dollar sign.

Illegal Identifiers

Data Types
The objective of a Java program is to manipulate data.
Different programs manipulate different data .
Data type: A set of values together with a set of
operations.

Data type can be divided into Primitive data type and Object
data type.

Primitive Data Types

Integers

Decimal numbers

Logical values

Ex: 1,5,10,-3

Ex: 1.5, -3.0,+6.1

Ex: true or false

Integral Data Types

Deals with integers, or numbers without a decimal part .

Floating-point Data Types


Represent real numbers in scientific notation.
Ex: 75.924 7.5924 * 101 7.592400E1 in Java

Has two types :


float:
Values: -3.4E+38 3.4E+38
Precision: 6 or 7 (4bytes)
double:
Values: -1.7E+308 1.7E+308
Precision: 15

(8 bytes )

The default type of floating-point numbers is double.

int or double ?
When do we know to use int and when do we use double?
If the data value you are going to use might be fractional then
choose double.
If it will always going to be a whole number choose int.

Consider the following cases. What would you choose?


Counting how many people have used a computer during a day.
The area of the lecture room in meters.
Average age of the students in CS230 .

Boolean Data Types


Has Two values:

true
false
These are called the logical (Boolean) values.
The central purpose of this data type is to manipulate
logical (Boolean) expressions.
Ex: a != A true

Guidelines for selecting data types


To represent integral values use type int. If a larger range of values is
needed, use type long.
On some computers, long will take longer to execute, so care may be
needed if a lot of arithmetic is being performed.
To represent non-integral values, use type double. Type float has similar
properties but less precision and a smaller range.
If speed of execution is very important, the float type may offer
advantages on some computers.
These are all what we call primitive types in Java. There are other types
available.

Relational Operator
Allows you to make comparisons in a program

Order of Precedence
1. *
2. +

%
-

(same precedence)
(same precedence)

Operators in 1 have a higher precedence than


operators in 2.
When operators have the same level of
precedence, operations are performed from
left to right .(i.e. associativity of arithmetic
operators from left to right )
To avoid confusion use parentheses ( ) to
group arithmetic expressions.
Ex: 3 + 4 * 5 (3 +4) * 5 35

Type Conversion (Casting)


Used :
to change one data type to another .
to avoid implicit type coercion as (1 + 8 =57)

By the use of cast operator.


Syntax:
(dataTypeName) expression

Expression evaluated first, then the value is


converted to dataTypeName

Type Conversion (Casting)

Examples:
1.
2.
3.
4.
5.
6.
7.
8.

(int)(7.9) + (int)(6.7) = 7+6= 13


(int)(7.9 + 6.7) = (int) 14.6 =14
(double)(17) = 17.0
(double)(8+3) = (double)11 = 11.0
(double)(7) /2 = 7.0/2 = 3.5
(double)(7/2) = 3.0
(int)(7.8+(double)(15)/2) = (int)15.3 =15
(int)(7.8+(double)(15/2))=(int)14.8 =14

9.

x=15 ,y = 23 , z= 3.75
(double) (y/x) + z = (double)(1)+3.75= 4.75
(double) (y) /x + z = 1.5333+3.75 =5.28333

10.
11.
12.
13.

(int)(A) = 65
(int)(8) = 56
(char) (65) = A
(char) (56) = 8

Object Data Types


Primitive type variables directly store data into
their memory space.

Reference variables store the address of the


object containing the data.
Object variables are used to access an object.
Contains a pointer to a desired object.
Contain no other value of any kind.

Object Data Type and Reference Variables


Example 1:
int x;
String str;
x = 45;
str = "Java Programming";

//Line
//Line
//Line
//Line

1
2
3
4

20

Object Data Type and Reference Variables


Example 2:
String str;
str = "Hello there!";

21

Object Data Type -The class String


We've seen almost all of the primitive types in use.
Java also defines a lot of types in addition to the primitive types.
Let's say you want a value to which is more than one character.
In English we'd call this a string. But there is NO string primitive
type!!
In Java, there is a class called String. It provides a lot of
methods that allow you to manipulate sequences of characters.
A type that comes from a class always starts with a capital
letter (String).
Have you noticed that all primitive type names start with lower
case
letters? (int, short, long, double, float, byte,
char...)

Object Data Type -The class String (contd)

Contains operations to manipulate strings.


String:

Sequence of zero or more characters.


Enclosed in double quotation marks .
Is processed as a single unit .
Null or empty strings have no characters.
Every character in a string has a relative position in
that string , the first character is in position 0 .

Object Data Type -The class String (contd)


Length of the string is the number of characters in it .
Numeric strings consist of integers or decimal
numbers.
When determining the length of a string , blanks
count .
Example :
Empty String has length = 0
abc has length = 3 , position of a = 0 ,b= 1 , c= 2
a boy has length = 5

Comparing Strings
Strings are compared character by character, using the
collating sequence, until one of three conditions is met:
1. A mismatch is found.
2. One string is exhausted.
3. The last characters have been compared and
are equal.

class String
Method compareTo (<0 , 0 , >0)
Method equals
(true or false)

Given string str1 and str2


an integer 0 if string str1 str2

str1.compareTo(str2) 0 if string str1 is equal to string str2


an integer 0 if string str1 str2

Comparing Strings
String
String
String
String
String

str1
str2
str3
str4
str5

=
=
=
=
=

"Hello";
"Hi";
"Air";
"Bill";
"Bigger";

Prepared by Nur
Laila bte Ab Ghani

Comparing Strings

Comparing Strings

Comparing Strings

Comparing Strings

Control Structures
Three methods of processing a program:
In sequence
Branching : Altering the flow of program execution
by making a selection or choice.
Looping : Altering the flow of program execution by
repeating statements.

Selection
One-way selection
Two-way selection
Compound (block of) statements
Multiple selections (nested if)
switch structures

One-Way Selection
Syntax:
if (expression)
statement
Expression referred to as decision maker.
Statement referred to as action statement.

Prepared by Nur
Laila bte Ab Ghani

One-Way Selection
Example:
//Determine the absolute value of an integer
import javax.swing.JOptionPane;
public class AbsoluteValue
{
public static void main(String[] args)
{
int number;
int temp;
String numString;
numString =
JOptionPane.showInputDialog
("Enter an integer:");
//Line 1
number = Integer.parseInt(numString); //Line 2
temp = number;
//Line 3
if (number < 0)
//Line 4
number = -number;
//Line 5

JOptionPane.showMessageDialog(null,
"The absolute value of " + temp
+ " is " + number,
"Absolute Value",
JOptionPane.INFORMATION_MESSAGE);
//Line 6
System.exit(0);

Two-Way Selection
Syntax:
if (expression)
statement1
else
statement2
else statement must be paired with an if.

Two-Way Selection
Example:
if (hours > 40.0)
wages = 40.0 * rate +
1.5 * rate * (hours - 40.0);
else
wages = hours * rate;

Compound (Block of) Statements


Syntax:
{
statement1
statement2
.
.
.
statementn
}

Compound (Block of) Statements


Example:
if (age > 18)
{
System.out.println("Eligible to
vote.");
System.out.println("No longer a
minor.");
}
else
{
System.out.println("Not eligible to
vote.");
System.out.println("Still a minor.");
}

Multiple Selection: Nested if


Syntax:
Else is associated with the
if (expression1)
most recent incomplete if.
statement1
Multiple if statements can be
used in place of ifelse
else
statements.
if (expression2)
May take longer to evaluate.
statement2
else
statement3

Multiple Selection: Nested if


Example :
if (score >= 90)
System.out.println (Grade is
else if (score >=80 )
System.out.println (Grade is
else if (score >=70 )
System.out.println (Grade is
else if (score >=60 )
System.out.println (Grade is
else System.out.println (Grade

A);
B);

C);
D);
is F);

switch Structures
Syntax:
switch (expression)
{
case value1:
statements1
break;
case value2:
statements2
break;
...
case valuen:
statementsn
break;
default: statements
}

Expression is also
known as selector.
Expression can be
an identifier.
Value can only be
integral.

switch Structures

Why Is Repetition Needed?


There are many situations in which the same
statements need to be executed several times.
Example:
Formulas used to find average grades for students
in a class.

Java has three repetition, or looping, structures


that let you repeat statements over and over
again until certain conditions are met:
While
for
dowhile

The while Looping (Repetition) Structure


Syntax:
while (expression)
statement
Statements must change value of expression to false.
A loop that continues to execute endlessly is called an
infinite loop .(expression is always true)

The while Looping (Repetition) Structure


Example:
i = 0;
while (i <= 20)
{
System.out.print(i + " ");
i = i + 5;
}
System.out.println();

Output
0 5 10 15 20

//Line 1
//Line 2
//Line 3
//Line 4
//Line 5

The while Looping (Repetition) Structure


Typically, while loops are written in the following form:
//initialize the loop control variable(s)
while (expression)
//expression tests the LCV
{
.
.
.
//update the loop control variable(s)
.
.
.
}

The for Looping (Repetition) Structure


Specialized form of while loop.

Its primary purpose is to simplify the writing of


counter-controlled loops. For this reason, the
for loop is typically called a counted or
indexed for loop. .
Syntax:
for (initial statement; loop condition;
update statement)
statement

The for Looping (Repetition) Structure

Execution:
1. Initial statement executes.
2. Loop condition is evaluated.
3. If loop condition evaluates to true,
1. execute for loop statement and
2. execute update statement.

4. Repeat step 2 until loop condition is false.

The for Looping (Repetition) Structure


Example:
The following for loop prints the first 10
nonnegative integers:
for (i = 0; i < 10; i++)
System.out.print(i + " ");
System.out.println();

The for Looping (Repetition) Structure


Example:
1. The following for loop outputs the word Hello and a star (on
separate lines) five times:

2.

for (i = 1; i <= 5; i++)


{
System.out.println("Hello");
System.out.println("*");
}
The following for loop outputs the word Hello five times and the star
only once:
for (i = 1; i <= 5; i++)
System.out.println("Hello");
System.out.println("*");

The for Looping (Repetition) Structure


Does not execute if loop condition is initially false.
Update expression changes value of loop control
variable, eventually making it false.
If loop condition is always true, result is an infinite
loop.
Infinite loop can be specified by omitting all three
control statements.
If loop condition is omitted, it is assumed to be
true.

Action of for loop ending in semicolon is empty.

The dowhile Loop (Repetition) Structure


Syntax:
do
statement
while (expression);
Statements are executed first and then expression is evaluated.
Statements are executed at least once and then continued if
expression is true.

dowhile Loop (Post-Test Loop)


Example :
i = 0 ;
do {
System.out.print(i + ) ;
i = i + 5 ;
}while ( i <= 30 ) ;
o/p : 0

10

15

20

25

30

break Statements
Used to
exit early from a loop. (while, for, and do...while)
skip remainder of switch structure.

Can be placed within if statement of a loop.


If condition is met, loop is exited immediately.

After the break statement executes, the program


continues to execute with the first statement after the
structure

break Statements
Example :
int count ;
for ( count = 1 ; count <= 10 ,count ++ )
{
if ( count == 5)
break ;
System.out.print(count + );
}

continue Statements
Used in while, for, and do...while structures.

When executed in a loop, the remaining statements


in the loop are skipped; proceeds with the next
iteration of the loop.
When executed in a while/dowhile structure,
expression is evaluated immediately after continue
statement.
In a for structure, the update statement is executed
after the continue statement; the loop condition
then executes.

continue Statements
Example :
int count ;
for ( count = 1 ; count <= 10 ,count ++ )
{
if ( count == 5)
continue;
System.out.print(count + );
}

Nested Control Structures


Provides new power, subtlety, and complexity.
if, ifelse, and switch structures can be placed
within while loops.
for loops can be found within other for loops.

Prepared by Nur Laila bte Ab Ghani

Nested Control Structures


Example:
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
System.out.print(" *");
System.out.println();
}
Output:
*
**
***
****
*****

Array
A structured data type with a fixed number of
components.
Every component is of the same type.
Components are accessed using their relative
positions in the array.

One-Dimensional Arrays
Syntax to instantiate an array:
dataType[ ] arrayName;
arrayName = new dataType[intExp]
dataType[ ] arrayName = new dataType[intExp]

Syntax to access an array component:


arrayName[indexExp]
intExp = number of components in array >= 0
0 <= indexExp <= intExp

Instantiating an Array
int[] num = new int[5];

Instantiating an Array

Specifying Array Size During Program Execution


int arraySize;
System.out.print("Enter the size of "
+ "the array: ");
arraySize = console.nextInt();
System.out.println();
int[] list = new int[arraySize];

Array Initialization During Declaration


double[] sales = {12.25, 32.50, 16.90, 23,
45.68};
The values, called initial values, are placed between braces and
separated by commas.
Here, sales[0]= 12.25, sales[1]= 32.50, sales[2]= 16.90,
sales[3]= 23.00, and sales[4]= 45.68.
When declaring and initializing arrays, the size of the array is
determined by the number of initial values within the braces.
If an array is declared and initialized simultaneously, we do not use the
operator new to instantiate the array object.

Arrays and the Instance Variable length


A public instance variable length is associated with
each array that has been instantiated.
The variable length contains the size of the array.
The variable length can be directly accessed in a
program using the array name and the dot operator.

This statement creates the array list of six components


and initializes the components using the values given.
Here list.length is 6.
int[] list = {10, 20, 30, 40, 50, 60};

Arrays and the Instance Variable length


This statement creates the array numList of 10 components and
initializes each component to 0.
int[] numList = new int[10];
The value of numList.length is 10.
These statements store 5, 10, 15, and 20, respectively, in the first four
components of numList.
numList[0] = 5;
numList[1] = 10;
numList[2] = 15;
numList[3] = 20;
You can store the number of filled elements, that is, the actual number
of elements, in the array in a variable, say noOfElement. It is a
common practice for a program to keep track of the number of filled
elements in an array.

Processing One-Dimensional Arrays


Loops used to step through elements in array and perform
operations.
int[] list = new int[100];
int i;

for (i = 0; i < list.length; i++)


list[i] = console.nextInt();

for (i = 0; i < list.length; i++)


System.out.print(list[i] + " ");

Processing One-Dimensional Arrays

Some operations on arrays:

Initialize
Input data
Output stored data
Find largest/smallest/sum/average of elements

Example 1
public class SumAverage
{
public static void main (String[]args)
{
//Initialize the array
double[] sales = new double[10];
int i;
double sum = 0, average;
//Code to read data into array
for (i = 0; i < sales.length; i++)
sales[i] = console.nextDouble();
//Code to print array
for (i = 0; i < sales.length;i++)
System.out.print(sales[i] + " ");
//Code to find sum and average
for (i= 0; i < sales.length; i++)
sum = sum + sales[i];
if (sales.length != 0)
average = sum / sales.length;
else
average = 0.0;
}
}

Example 2
public class LargestElement
{
public static void main (String[]args)
{
//Initialize the array
double[] sales = new double[10];
int i, maxIndex = 0;
double largestSale;
//Code to read data into array
for (i = 0; i < sales.length; i++)
sales[i] = console.nextDouble();
//Code to print array
for (i = 0; i < sales.length;i++)
System.out.print(sales[i] + " ");
//Code to find largest element in array
for (i = 1; i < sales.length;i++)
if (sales[maxIndex] < sales[i])
maxIndex = i;
largestSale = sales[maxIndex];
}

Determining Largest Element in Array