Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

1

CS 241: OBJECT
ORIENTED
PROGRAMMING
Dr. Ibrahim Eldesoky
Ibrahim_desoky@hotmail.com
2

A Simple Console Application Program


//A Java application program that prints “Hello World!”

public class Example1


{ public static void main (String args[ ])
{ //print message
System.out.println (“Hello World!”);
} //end main
} //end class Example1
3

A Simple Console Application Program


(cont.)
• Every Java application program defines a class.

• Use the keyword class to declare a class.

• The name of a class is an identifier. Uppercase and


lowercase letters are different.
• The name of the class must be same as the the file
holding that class (Example1.java)
4

A Simple Console Application Program


(cont.)
• Our class contains only one method.
• Every console application program should contain a
main method.
• It may contain other methods too.
• The method main should be declared using public and
static keywords.
• Our main method contains only one executable
statement
• This is a method invocation statement (print statement)
• // single line comments
• /* ... */ multi line comments
• Use white space between words/lines/blocks to make
easier to read programs.
5

A Simple Console Application Program


(cont.)
• Using a text editor, put this application program into the
file Example1.java
• To compile: javac Example1.java
• creates Example1.class file (if there are no syntax
errors in the code)
• To run: java Example1
• java interpreter will interpret the byte-codes in
Example1.class file.
• As a result, we will see Hello appear on the screen.
6

Simple Java Program (cont.)


• What do we have in our simple Java program?
• Identifiers – Example1,args,...
• Reserved Words – public, class, static, ...
• Literals – “Hello there, World!”
• Operators -- .
• Delimiters -- { } ( ) [ ] ;
• Comments -- // end of class
• When these parts are combined according to
certain rules (the syntax of Java), a syntactically
correct Java program is created.
7

Identifiers
• We make up words for class names, method names, and
variables.
• These words are called identifiers.
• For example,
• Example1
is identifier in our simple program.
8

Identifiers (cont.)
• An identifier can be composed of any combination of
letters, digits, the under score character, and the dollar
sign; but it cannot start with a digit.
• We can use both upper case letters and lower case letters
in identifiers. But Java is case sensitive. Identifiers Val,
val and VAL are all different variables.
• Some Legal Identifiers: x val count_flag Test1 $amount
val1 stockItem

• Some Illegal Identifiers: 1val x# x-1 x+


9

Identifiers (cont.)
• Although we can choose any legal identifier to be
used, but it is nice to follow certain style
guidelines when make up an identifier.
• Choose meaningful names (not too long, not too short,
descriptive words)
• First character of a class name should be an uppercase
letter.
• First character of a method name and a variable should
be a lower case letter.
10

Reserved Words
• Reserved words are identifiers that have a
special meaning in a programming language.
• For example,
• public, void, class, static are reserved
words in our simple programs.
• In Java, all reserved words are lower case
identifiers (Of course we can use just lower case
letters for our own identifiers too)
• We cannot use the reserved words as our own
identifiers (i.e. we cannot use them as variables,
class names, and method names).
11

Reserved Words ( cont.)


• Data declaration: boolean, float, int, char
• Loop keywords: for, while, continue
• Conditional keywords: if, else, switch
• Exceptional keywords: try, throw, catch
• Structure keywords: class, extends,
implements
• Modifier and access keywords: public, private,
protected
• Miscellaneous: true, null, super, this
12

Sample Java Program - Example

/*
HelloWorld application program
*/
public class HelloWorld // Class header
{ // Start class body
public static void main(String argv[]) //main method
{
System.out.println(“HelloWorld!”);
} // end of main
} // end HelloWorld

Circled words are those that we make up ourselves


13

Sample Java Program - Example

/*
HelloWorld application program
*/
public class HelloWorld // Class header
{ // Start class body
public static void main(String argv[]) //main method
{
System.out.println(“HelloWorld!”);
} // end of main
} // end HelloWorld

Circled words are reserved for special purposes in the language


are called reserved words
14

Sample Java Program – Example

/*
HelloWorld application program
*/
public class HelloWorld // Class header
{ // Start class body
public static void main(String argv[]) //main method
{
System.out.println (“HelloWorld!”);
} // end of main
} // end HelloWorld

Circled words that are not in the language, but were used by
other programmers to make the library
15

JAVA API (Application Programming


Interface)
• The Java API is a set of a class libraries.

• The classes of the Java API are grouped into packages.

• Each package contains related classes.

• A package may contain another packages too.


16

JAVA API (cont.)


• Some packages in the Java API.
• java.lang
• general support, it is automatically imported into all Java
programs
• java.io
• perform a wide variety of input output functions
• java.awt
• graphics related stuff
• java.applet
• to create applets
• java.math
• mathematical functions.
.
17

The import Statement


• We can access a class by giving its full name such as
java.awt.Graphics. But we will repeat this over
and over again in our programs.

• The import statement identifies the packages and the


classes of the Java API that will be referenced in our
programs.

• import is like include statement in C;


18

The import Statement (cont.)


import package.class
identify the particular package that will be used in our
program.
example: import java.applet.Applet

import package.*
we will be able to access all classes in that package.
example: import java.awt.*
19

Structure of a Simple Console Application


Program
imported classes;

public class < name> {


- declarations

public static void main (String args[])


throws IOException {
- declarations of local variables
- executable statements
}

other methods if they exist


}
20

Structure of a Method

Public <its return type> <its name> ( <its arguments> )


{
• declarations of local variables
• executable statements
}
21

Executable Statements
• All statements which are executed during the
execution of a program
-- assignment statement
-- method call statement
-- conditional statement
-- loop statement
Examples:
System.out.println (“Hello there, World!”);
f(1,2);
x = y+2;
if (x<1) x=x+1;
else x=x-1;
22

Another Simple Console Application


Program
public class Example2
{
public static void main(String args[])
{
// print the city and its population.
System.out.println ("The name of the city is ” + “cairo”);
System.out.println (“Its population is” + 15000000);

// Different usages of + operator


System.out.println (“Sum of 5+4: “ + (5+4));

// Different output method – print


System.out.print (“one..”);
System.out.print (“two..”);
System.out.println (“three..”);
System.out.print (“four..”);
} // end of main

} // end of Example class


23

The println and print Methods

System.out.println (”Make the most of each day.");

Class Static Field


Information provided to the method
method (parameters which is String for this method)

System is a class in java.lang package


24

The println and print Methods


• println prints its argument and moves to the next line.

• print prints its argument and it does not move to the


next line.
25

Another Simple Application Program


(cont.)
• The operator + is a string concatenation
operator.
• “abc” +”de”  “abcde”
• 15000000 is converted to a String and this string is concatenated
with the string literal “Its population is”.

• The operator + is also a regular add operator for


numeric values. The + in (5+4) is a regular
addition operator for numeric values.
26

Another Simple Application Program


(cont.)
• In other words, the + operator is overloaded.

• The output of our program will be:


The name of the city is cairo
Its population is 15000000
Sum of 5+4: 9
one..two..three..
four..
Simple Outputs

System.out.println ("Hello " + "World!"); System.out.println (3+4);


Output: Output:
Hello World 7

System.out.println(3+4+"=
System.out.println ("Answer = " + 7); 7");
Output: Output:
Answer = 7 7=7
28

Variables
• A variable is a name for a location in memory
• A variable must be declared, specifying the variable's
name and the type of information that will be held in it

data type variable name

int total;

int count, temp, result;

Multiple variables can be created in one declaration


29

Variables
• A variable can be given an initial value in the declaration
• int sum = 0;
• int base = 32, max = 149;
• When a variable is referenced in a program, its current value is
used
30

Assignment
• An assignment statement changes the value of
a variable total = 5;

• The assignment operator is the = sign


• The expression on the right is evaluated and the result
is stored in the variable on the left
• The value that was in total is overwritten
• You can only assign a value to a variable that is
consistent with the variable's declared type
31

Constants

• A constant is an identifier that is similar to a variable


except that it holds one value for its entire existence

• The compiler will issue an error if you try to change a


constant.

• In Java, we use the final modifier to declare a


constant

final int HEIGHT = 69;


32

Constants (cont.)

• As a style, we choose upper case letter for


identifiers representing constants.
• Constants are better than literals because:
• they make code more readable by giving a name to a value.

• they facilitate easy updates in the programs because the value


is only specified in one place.
33

Data Types

• Each value in memory is associated with a


specific data type.

• Data Types in Java:


• Primitive Data Types
• Object Data Types

• Data type of a value determines:


• size of the value (how many bits) and how these bits are
interpreted.
• what kind of operations we can perform on that data.
34

Primitive Data Types


• There are exactly eight primitive data types in
Java
• Four of them represent integers:
• byte, short, int, long
• Two of them represent floating point numbers:
• float, double
• One of them represents characters:
• char
• And one of them represents boolean values:
• boolean
35

Java numerical primitive types


Type Storage Min Value Max Value
byte 8 bits -128 127
short 16 bits -215 215-1
int 32 bits -231 231-1
long 64 bits -263 263-1
-3.4e+38 +3.4e+38
float 32 bits
(-1.4e-45) (+1.4e-45)
-1.8e+308 +1.79e+308
double 64 bits
(-4.9e-324) (+4.9e-324)

They differ by the amount of the memory used to store them.


Internally, integers are represented using two’s complement representation.
36

Arithmetic Expressions

• Arithmetic Operators:
+ addition
- subtraction
* multiplication
/ division
% mod operator (remainder)
++,-- increment, decrement operators (they can be
postfix or prefix)
+, - unary operators
37

boolean
• A boolean value represents a true or false
condition.

• The reserved words true and false are only


valid values for a boolean type.

int i, j;
boolean x, y;
x = true;
y = (i < j);
38

Characters

• A char value stores a single character from


Unicode character set.
• A character set is an ordered list of characters.
Each character is represented by a sequence
of bits.
• The Unicode character set uses 16 bits per
character (65636 unique characters) and
contains international character sets from
different languages, numbers, symbols.
39

Characters (cont.)
• ASCII character set is a subset of the Unicode
character set. It uses only 8 bits (256
characters). In fact, the first 256 characters of
the Unicode character set are ASCII
characters.
• 32 space
• 48-57 0 to 9
• 65-90 A to Z
• 97-122 a to z
• Character literals:
• ‘a’ ‘A’ ‘1’ ‘0’ ‘+’
• Note that ‘1’ and 1 are different literals (character
and integer)
40

Escape Sequences
• What if we wanted to print a double quote character?
• The following line would confuse the compiler because
it would interpret the second quote as the end of the
string

System.out.println ( "I said "Hello" to you." );

• An escape sequence is a series of characters that


represents a special character
• An escape sequence begins with a backslash
character (\), which indicates that the character(s) that
follow should be treated in a special way

System.out.println ("I said \"Hello\" to you.");


41

Java Escape Sequences


• Some Java escape sequences.

Escape Sequence Meaning

\b backspace
\t tab
\n newline
\r carriage return
\" double quote
\' single quote
\\ backslash
42

Literals
• Literals are explicit values used in a program.
• Certain data types can have literals.
• String literal – “Hello there,World!”
• int literals -- 12 3 77
• double literals – 12.1 3.45
• char literals – ‘a’ ‘1’
• boolean literals -- true false
43

Literal Assigned type

6 int (default type)


6L long (To force a literal to be long)
6l long
1,000,000,000 int
2.5 (or 2.5e-2) double (default type)
2.5F float
2.5f float
‘x’ char
‘\n’ char (new line)
‘\u0039’ char represented by unicode 0039
true boolean
“\tHello World!\n” String (not a primitive data type!)
44

Statements
• Conditional Statements
if statement
switch

• Loops
while
do-while
for
45

if Statement
if-then structure: condition

if ( condition ) true false


statement-true
statement-true
where condition is a Boolean expression, and
statement-true is any simple or compound
statement.
if-then-else structure:
if ( condition ) condition
statement-true true false
else
statement-false statement-true statement-false
46

if-statement Examples

if (y != 0)
x = x / y;
else
System.out.println(“y is zero”);

if (x >= 0)
System.out.println (“positive”);
else
System.out.println (“negative”);
47

Compound Statements

• A set of statements contained within a pair of curly


braces { } , is called a compound statement.
• The body of a method is also a compound statement.

• A compound statement can be used anywhere in a


program that a single statement can be used.
• After a compound statement, we should not put a
semicolon. If we put one, this means that we have
inserted an empty statement.
48

Compound Statement -- Examples

if (discountRate != 0) {
discount = price * discountRate;
price = price – discount;
}

if (x>y) {
temp = x ;
x = y;
y = temp;
}

if (x != y) {
System.out.println (“x and y have different values”);
System.out.println (“x: “+x+” y: “+y);
}
else
System.out.println (“x and y have same value: “ + x);
49

Simple Boolean Expressions


• There are only two possible values for a Boolean
expression:
• true false
• a simple Boolean expression with a relational operator
operand1 relational-operator operand2
Where, operands are usually arithmetic operations.
• Relational Operators:
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to (do not confuse with =)
!= not equal to
50

Simple Boolean Expressions -- Examples

• int x = 10, y=5;

Boolean Expressions Results


x>1  true
x<5  false
x >= 10  true
(y +2)< x  true
y != 5  false
x == (y+1)  false
y <= x  true
51

Boolean Expressions

• Boolean Operators
&& logical AND
|| logical OR
! negation (NOT)
^ exclusive or (XOR)

• a Boolean expression with a boolean operator


• operand1 Boolean-operator operand2
• where operands are Boolean expressions
52

Boolean Expressions -- Examples

• int x = 10, y=5

Boolean Expressions Results


(x>1) && (y<5)  false
(x>1) || (y<5)  true
!(y<5)  true
(x<1) ^ (y>1)  true
53

Truth Tables of Boolean Operators

E1 E2 E1 && E2 E1 || E2 E1 ^ E2
false false false false false
false true false true true
true false false true true
true true true true false

E !E
false true
true false
54

Operator Precedence
Precedence Operator Operation Associates
Level

1 ++ -- postfix increment, postfix decrement L to R

2 ++ -- + - pre-increment, post-increment, unary minus and R to L


! plus
logical not

3 * / % multiplication, division, remainder L to R

4 + - addition, subtraction L to R

5 < <= > >= less than, less than equal, greater than, greater than L to R
equal

6 == != equal, not equal L to R

7 ^ xor L to R

8 && logical and L to R

9 || logical or L to R

10 ?: conditional operator R to L

11 = += ...... assignment operators R to L


55

Operator Precedence -- Example

(x>1) || (y<2) && (z==3) && is evaluated first

(x>1) && (y<2) && (z==3) left to right

(x>1) || (y<2) || (z==3) left to right

Boolean Assignment:
• we may declare Boolean variables and save Boolean values in
those variables.

boolean flag;
flag = (x>y);
56

Short Circuit Evaluation


• If the value of the first operand of an && operator is false,
the second operand is not evaluated.
• If the value of the first operand of an || operator is true,
the second operand is not evaluated.

(x>y) && (x>z) if (x>y) is false the value of (x>z) is


not evaluated
(x>y) || (x>z) if (x>y) is true the value of (x>z) is
not evaluated

• We have to be careful when using operations with side


effects.
int x=2;
(x > 5) && (x++ <10)  false, x is not incremented
(x < 5) && (++x < 10)  true, x is incremented
(x++ < 10) && (x > 5)  false, x is incremented
57

Nested if-statements
• If-statements can also be used to implement decisions
involving more than two alternatives.
• A nested if-statement is an if-statement whose true-
statement and/or false-statement are also if-
statements.

if (x < 10)
System.out.println (“x has one digit”);
else if (x < 100)
System.out.println (“x has two digits”);
else
System.out.println (“x has more than two
digits”);
58

Dangling Else Problem


• Java compiler always associates an else-statement with the previous if-statement (the
closest one). This can only be changed by using a compound statement.

THE FOLLOWING EXAMPLE IS INCORRECT!! {try x = 7, y = 3}


if (x > 5)
if (y > 5)
System.out.println (“x and y are greater than 5”);
else
System.out.println (“x is less than or equal to 5”);

THIS IS THE CORRECT WAY TO ACHIEVE THE PROPER RESULT


if (x > 5) {
if (y > 5)
System.out.println (“x and y are greater than 5”);
}
else
System.out.println (“x is <= 5”);

You might also like