You are on page 1of 77

Introduction to Java

programming
as OOP Language

Dr. Mohamed M. Eltaweel

1
How to make a jam sandwich
instructions

2
How to make a jam sandwich
instructions

3
How to make a jam sandwich
instructions

4
How to make a jam sandwich
instructions

Programming is the Same

Input Processing Output

5
6
A small history
• Java is a programming language.
– Created by James Gosling from Sun Microsystems in 1991.

– Initially called Oak, in honor of the tree outside Gosling's


window, its name was changed to Java because there was
already a language called Oak.

– The first publicly available version of Java (Java 1.0) was


released in 1995.

– The current version of Java is Java 1.7 which is also known


as Java 7.

7
Java Virtual machine
• The Java virtual machine (JVM) is a software implementation
of a computer that executes programs like a real machine.

• The Java virtual machine is written specifically for a specific


operating system,
e.g. for Linux a special implementation is required as well
as for Windows.

• Java programs are compiled by the Java compiler into so-


called bytecode.

• The Java virtual machine interprets this bytecode and


executes the Java program.
8
Java Virtual machine

* The target of Java is to write a program once and then run this program on multiple
operating systems.
9
Java Runtime Environment vs. Java
Development Kit
• Java comes in two flavors, the Java Runtime
Environment (JRE) and the Java Development Kit (JDK).

• The Java runtime environment (JRE) consists of the


JVM and the Java class libraries and contains the
necessary functionality to start Java programs.

• The JDK contains in addition the development tools


necessary to create Java programs. The JDK consists
therefore of a Java compiler, the Java virtual machine,
and the Java class libraries.
10
Java Runtime Environment vs. Java
Development Kit

11
Java Characteristics
Java has the following properties:
• Platform independent:
– Java programs use the Java virtual machine as abstraction and do not
access the operating system directly. This makes Java programs highly
portable. And supports all platforms, e.g. Windows or Linux.

• Object-orientated programming language:


– Except the primitive data types, all
elements in Java are objects.

• Code Security
– Through using a Bytecode Verifier that tests the format of the code
fragments and checks the code fragments for illegal code that can
violate access rights to objects
12
Java Characteristics,cont.
• Interpreted and compiled language:
– Java source code is transferred into the bytecode format which
does not depend on the target platform. These bytecode
instructions will be interpreted by the Java Virtual machine
(JVM).
– The JVM contains a so called Hotspot-Compiler which translates
performance critical bytecode instructions into native code
instructions.

• Automatic memory management:


– Java manages the memory allocation and de-allocation for
creating new objects. The program does not have direct access
to the memory. The so-called garbage collector deletes
automatically objects to which no active pointer exists.
13
Memory Allocation in Java,cont.

14
Java Program
The Java language and runtime environment
enables two different kinds of programs:
1. Applets:
• Applets require a Java enabled browser to run
(on a web page).

• When that page is accessed by a browser it


automatically downloads the applet code from the
server and runs it on the local machine (on
Sandbox).

•A Sandbox prevent downloaded program from


doing certain system tasks such as creating or
16
editing files on the local file system.
Java Program,cont.
2. Applications.
• Java applications are similar to application programs
developed in other languages.
• They do not require a browser to run - they have no
built-in downloading mechanism.
• An application has full access to system services and
resources (can write/read).

Note:
other shape of java programs is the Servlets :
Servlets are modules of Java code that run in a server application (hence the name "Servlets",
17
similar to "Applets" on the client side) to answer client requests.
Development Process with Java
• The programmer writes Java source code in a text editor which
supports plain text.

• Normally the programmer uses an Integrated Development


Environment (IDE) for programming.

• At some point the programmer (or the IDE) calls the Java compiler
(javac). The Java compiler creates the bytecode instructions.

• These instructions are stored in .class files and can be executed by


the Java Virtual Machine.

*Note:
bytecode file ≈ .class file

18
Java Development Environment (IDE)

19
Your first Java program
// A small Java program

public class HelloWorld


{
public static void main(String[] args)
{
System.out.println("Hello to OOP World");
System.out.print(“My");
System.out.print(“Dear Students");
}
}
__________________________________________
Hello to OOP World
My Dear Students

Note:
Save the source code in your javadir directory with the HelloWorld.java filename. The name of a Java 20
source
file must always equals the class name (within the source code) and end with the .java extension.
Comments in Java
• comments are preceded:
– by two slashes (//) in a line, When
the compiler sees //, it ignores all
text after // in the same line.

– or enclosed between /* and */ in one


or multiple lines. When it sees /*,
it scans for the next */ and ignores
any text between /* and */.

21
Reserved Words
• Reserved words or keywords are
words that have a specific
meaning to the compiler and
cannot be used for other
purposes in the program.

– For example,
• class, public, static, and void.

22
Statements
• A statement represents an action
or a sequence of actions.

– The statement
System.out.println("Hello to OOP World”)
in the previous program in is a
statement to display the greeting
"Hello to OOP World"

– Every statement in Java ends with a


semicolon (;).
23
Blocks
• A pair of braces in a program
forms a block that groups
components of a program.

public class Test {


public static void main(String[] args) { Class block
System.out.println("Welcome to Java!"); Method block
}
}

24
Methods
• What is System.out.println? It is a method:

– a collection of statements that performs a sequence of


operations to display a message on the display.

•The main method:


–provides the control of program flow. The Java
interpreter executes the application by invoking
the main method.

The main method looks like this:


public static void main(String[ ] args) {
// Statements;
}

25
Conditions for class’ names
1. Start by capital letter
2. No spaces
3. No symbols = + - , . ; / \
4. Underscore is accepted
5. May contain digits but must start by a letter
6. The class must be stored in a file with the
same name

26
Primitive Types of variables
• Boolean bool true or false
• Character char 2 bytes
• Integer
type Size Range
name bytes bits minimum maximum
byte 1 8 -128 +127
short 2 16 -32,768 +32,767
+2,147,483,
int 4 32 -2,147,483,648
647
+9,223,372,
-9,223,372,
long 8 64 036,854,775
036,854,775,808
,807

27
Primitive Types of variables
• Real
type Size Range
+/- 3.4 *
float 4 32
1038
+/- 1.8 *
double 8 64
10308

28
Conditions for variable’s names

1. Start by a letter (capital or small)


2. No spaces
3. No symbols = + - , . ; / \
4. Underscore is accepted
5. May contain digits but must start by a letter
6. Differentiate between small letters and
capital letters
7. Can not be a reserved word (for , if , void)
29
Boolean Example
/* Java boolean Example
This Java Example shows how to declare and use Java primitive boolean variable
inside a java class.
*/
public class JavaBooleanExample {

public static void main(String[] args) {


boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
Int x=10;
Int y= 3
boolean z=y>x;

// outcome of a relational operator is a boolean value


System.out.println("10 > 9 is " + (10 > 9));
}} 30
_____________________________

b is false
b is true
10 > 9 is true

31
Initializers
• May be used to give variables initial values
int x = 5;
int y = 6;
• Can be written more concisely
int x = 5,
y = 6;
• Can use expressions on the right hand side
int x = 5,
y = x + 1;

32
Symbolic Constants
• Useful when you want a variable whose value
never changes
• Use the modifier final in its declaration
• Example
final int US_Population = 278058881;

34
Symbolic Constants

public class FinalJavaExample {

public static void main(String[] args) {

final int finalvariable=10;

System.out.println("Final Variable:"+finalvariable);

finalvariable=15; // *Error at this line:


The final local variable finalvariable cannot be assigned.
It must be blank and not using a compound assignment
*/

35
Integer Arithmetic Operations
Symbol Operation Example
+ Addition 45 + 5 = 50
- Subtraction 657 – 57 = 600
* Multiplication 7000 * 3 = 2100
/ Division 10 / 3 = 3
% Remainder 10 % 3 = 1

36
Integer Arithmetic Operations
//Write a program to calculate the Area of a Circle (PI * radius ^2) , PI= 3.14

public class CalculateCircleArea {


public static void main(String args[]){

double radius=12.0;
double Pi=3.14;
double area;
area=Pi*raduis*raduis;
System.out.println("Area of a circle= "+area);

}
}

37
Integer Arithmetic Operations
/*
Calculate Rectangle Area using it's length and width.
*/

Assignment

38
Integer Arithmetic Operations
/*
Write a java program to read the Basic salary , Allowance, Income Tax (IT) for an
employee, then compute his Net_Salary.

Givens:
-Allowance (A) = 52% of Basic
-Income Tax (IT) = 30% of the gross salary
*/

Assignment

39
/* What is the output of executing this program: */
public class Example0103
{
public static void main(String[ ] args)
{
int a =10;
int b=20;
boolean d , e ;
d = a>b; e= b>a;
System.out.println("d = " + d);
System.out.println("e = " + e);
}
}

40
Integer Arithmetic Operations
public class Test {
public static void main(String args[]) {
int a = 10;
int b = 20;
int c = 25;
System.out.println("a + b = " + (a + b) );
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
System.out.println("b / a = " + (c/ a) );
System.out.println("b % a = " + (b % a) );
System.out.println("c % a = " + (c % a) );
41
} }
Integer Arithmetic Operations
/*
Write a program to calculate the remainder of x divided by 5, where x =27;
*/

42
//Example0103
/* What is the output of executing this program: */
public class Example0103
{
public static void main(String[ ] args)
{
int a , b ;
double d , e , f , g ;
a = 64 / 10 ; b = 64 % 10 ; d = 64 / 10 ;
e = 64.0 / 10 ; f = 64 % 10 ; g = 64.4 % 10 ;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("d = " + d);
System.out.println("e = " + e);
System.out.println("f = " + f);
System.out.println("g = " + g);
} 43
a=6
b=4
d = 6.0
e = 6.4
f = 4.0
g = 4.4

44
Precedence Rules
1. Evaluate all sub expressions in parentheses
2. Evaluate nested parentheses from the inside out
3. In the absence of parentheses or within
parentheses
a. Evaluate *, /, or % before + or –
b. Evaluate sequences of *, /, and % operators from left to
right
c. Evaluate sequences of + and – operators from left to
right

45
Precedence
① Brackets ⑥ Assignment

② Pre ++, --
⑥ Post ++, --
③ Unary +/- (sign)
⑦ Execution from left to
④ *, /, %
right in equal
⑤ +, -
precedence

46
Precedence Examples
• What is the output of the following equation:
10 * 5 + 100 / 10 – 5 + 7 % 2

47
Precedence Examples
• Example 1
6 + 37 % 8 / 5 is the same as
6 + ((37 % 8) / 5) =
6 + ( 5 / 5) = 7
• Example 2
6 + 37 % (8 / 5) =
6 + 37 % 1 =
6+0=6

48
Precedence Examples
• Find the value of the following equations

1-2+3*4/5

22-5+7-(8*5+5)/3

Assignment

49
Additional Integer Operators

• Self-assignment
temperature = temperature + 10;
• Increment
cent++;
equivalent to
cent = cent + 1;
• Decrement
cent--;
equivalent to
cent = cent - 1;
50
Difference between n++ and ++n
z = y++ ; ⇔ z =y;
y=y+1;

------------------------------------------------------

z = ++y ; ⇔ y=y+1;
z=y;

51
Difference between n++ and ++n
n++ will increment the variable prior to the operation taking place,
while ++n only increments the variable after the operation.

So take x=1
y = x++
y=1
x = 2 now

So take x = 1 again
y = ++x
y=2
x = 2 now

52
Let x=2, y=3, z=5 what is the outputs of the following:

① ++x *y / z

② x++ * -y / z

③ x *= z

④ x += z – y % z

53
//Example0105
// What is the output when executing this program

public class Example0105


{
public static void main(String[ ] args)
{
int a=2 ;
a++ ;
System.out.println( "a = " + a );

int b=2 ;
++b ;
System.out.println( "b = " + b );

int c=2 ;
System.out.println( "c = " + c++ );

int d=2 ;
System.out.println( "d = " + ++d );

54
int f, e=2 ;
f = e++ ;
System.out.println("e = " + e + " \t f = " + f ) ;

int h, g=2 ;
h = ++ g ;
System.out.println("g = " + g + " \t h = " + h );

int i = 2 , j = 2 ;
i-- ; --j ; System.out.println("i = " + i + " \t j= " + j );

int k , l , m , n ;
k = l = m = n = 10 ;
k += 2 ; l -= 2 ;
m *= 2 ; n /= 2 ;
System.out.println( "k = " + k + " \t l= " + l );
System.out.println( "m = " + m + " \t n= " + n );
}
}

55
Results
• a=3
• b=3
• c=2
• d=3
• e=3 f=2
• g=3 h=3
• i=1 j=1
• k = 12 l=8
• m = 20 n=5

56
The if-then Statement
• The if-then statement is the most basic of all
the control flow statements. It tells your
program to execute a certain section of
code only if a particular test evaluates to true.

if (condition)
{ ... // Do this clause if the condition is true. }

58
The if-then Statement

59
The if-then Statement
• Before trying out some new code, you'll need
to learn some more conditional operators.

Relational Operator Meaning


> is greater than
< is less than
>= is greater than or equal to
<= is less than or equal to
== is equal to
!= is not equal to

60
The if-then Statement
Here’s an example:

double commissionRate = 0.0;


if (salesTotal > 10000.0)
commissionRate = 0.05;

In this example, a variable named commissionRate


is initialized to 0.0 and then set to 0.05 if salesTotal
is greater than 10000.0.
61
The if-then Statement
Here’s an example that uses a block rather than a single
statement:

double commissionRate = 0.0;


if (salesTotal > 10000.0)
{ commissionRate = 0.05;
commission = salesTotal * commissionRate;
}
In this example, the two statements within the braces are
executed if salesTotal is greater than $10,000. Otherwise,
neither statement is executed.
62
The if-then Statement
public class Example0105
{

public static void main(String[ ] args)


{
int userAge=18;

if (userAge<=22)

System.out.println(“user Age is less than 22");

}
}

Note:
The opening and closing braces are optional, provided that the "then" clause contains only one
statement 63
Braces are your friend
• Braceless if considered harmful and could change
the output results.

//... What does this print?


int marks=70;
String comment = "Not so bad.";
String grade = "A";

if (marks < 60)


comment = "This is terrible.";
grade = "F";

System.out.println("Your grade is " +grade);


System.out.println(comment);

65
_____________________________

Your grade is F
Not so bad.

66
Braces are your friend
• The right one is to use braces as:

//... What does this print?


int marks=70;
String comment = "Not so bad.";
String grade = "A";

if (marks < 60)


{
comment = "This is terrible.";
grade = "F";
}

System.out.println("Your grade is " +grade);


System.out.println(comment);

67
The if-then Statement
public class EvalScore {

public static void main(String[] args) {


int score = 52;

if (score >= 60)


{ System.out.println("Not so bad“); }

if (score < 60)


{ System.out.println("This is terrible“); }

}
}

68
The if-then-else Statement
// Using if_else
//Program to test if student score is greater than or less than 60

class EvalScore {

public static void main(String[] args) {


int score = 52;

if (score > 60)


{ System.out.println(“Not so bad”); }

else

{ System.out.println(" This is terrible“); }

}
}

69
The if-then-else Statement

70
The if-then-else Statement
Programmers must write code to guard against division by
zero. Dividing by zero is a logical/runtime error.

if (divisor != 0)
{
quotient = dividend / divisor;
System.out.println(dividend + " / " + divisor + " is "
+ quotient);
}
else
{
System.out.println("Error: cannot divide by
zero.");
}
71
The if-then-else Statement
The diagram below shows how the previous if/else statement could be
depicted in a flowchart.

false divisor != 0 true

Display an quotient = dividend /


error message divisor

Display the
quotient

72
The if-then-else Statement

• Notice that there is not a semicolon after the


parenthesized Boolean expression or the key word else
in an if/else statement.

if (divisor != 0) Do not put semicolons here!

{
quotient = dividend / divisor;
System.out.println(dividend + " / " + divisor + " is " + quotient);
}
else
{
System.out.println("Error: cannot divide by zero.");
}

73
//Using else if
//Suppose we wanted to create a program to assign a letter grade
corresponding to a numeric grade entered by the user, assuming that the
numeric grade entered is a whole number and letter grades are assigned
based on the following scale:

90  numeric grades  100  letter grade of A


80  numeric grades  90  letter grade of B
70  numeric grades  80  letter grade of C
60  numeric grades  70  letter grade of D
0  numeric grades  60  letter grade of F

Grades outside these ranges are not valid.

Assignment

76
Boolean Operators

Operator Name Description

! not logical negation

&& and logical conjunction

|| or logical disjunction

^ exclusive or logical exclusion

Example

!(1 > 2) is true, because (1 > 2) is false.

(3 > 2) && (5 > 5) is false, because (5 > 5) is false.

(3 > 2) && (5 >= 5) is true, because (3 > 2) and (5 >= 5) are both true.

(3 > 2)||(5 > 5) is true, because (3 > 2) is true.


78
Boolean Operators

We can use it to test for two age ranges:

else if ( user > 18 && user < 40 )

Here, we want to check if the user is older than 18 but


younger than 40. Remember, we're trying to check what is
inside of the user variable. The first condition is "Greater than
18" ( user > 18 ). The second condition is "Less than 40" ( user
< 40). In between the two we have our AND operator ( &&).
So the whole line says "else if user is greater than 18 AND
user is less than 40."

79
Boolean Operators

80
public class TestBoolean {

public static void main(String[ ] args) {


int number = 18;
boolean result;

result= number % 2 == 0 && number % 3 == 0;

System.out.println ( "is the number divisible by 2 and 3? "+ result);

result= number % 2 == 0 || number % 3 == 0;

System.out.println ( "is the number divisible by 2 and 3? "+ result);

result= number % 2 == 0 ^ number % 3 == 0;


System.out.println ( "is the number divisible by 2 or 3, but not both? "+
result);

} } 81
A runtime error

Avoid using the single & and | operators.

For example,
(x != 0) & (100 / x) is a runtime error

(x != 0) && (100 / x) is fine.

82
Write a program that checks whether it is a leap year.
Note: A year is a leap year if it is divisible by 4 but not by 100 or if it is
divisible by 400 ( rule says that every 400 years is a leap year again).

public class LeapYear {

public static void main(String args[]) {

int year = 2008;

boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

System.out.println (year + " is a leap year? " + isLeapYear);

}
}

_____________________________
2008 is a leap year? true
84
switch Statement
Purpose of switch: select one of many possible
statements to execute
• The if statement allows you to select one of
two sections of code to execute based on a
boolean value (only two possible values).
The switch statement allows you to choose
from many statements based on an integer
(including char) or enum value.

85

You might also like