Introduction To Java Programming - 1
Introduction To Java Programming - 1
Introduction To Java Programming - 1
programming
as OOP Language
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
5
6
A small history
• Java is a programming language.
– Created by James Gosling from Sun Microsystems in 1991.
7
Java Virtual machine
• The Java virtual machine (JVM) is a software implementation
of a computer that executes programs like a real 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).
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.
• 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.
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).
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.
• At some point the programmer (or the IDE) calls the Java compiler
(javac). The Java compiler creates the bytecode instructions.
*Note:
bytecode file ≈ .class file
18
Java Development Environment (IDE)
19
Your first Java program
// A small Java program
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.
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"
24
Methods
• What is System.out.println? It is a method:
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
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
System.out.println("Final Variable:"+finalvariable);
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
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
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.
60
The if-then Statement
Here’s an example:
if (userAge<=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.
65
_____________________________
Your grade is F
Not so bad.
66
Braces are your friend
• The right one is to use braces as:
67
The if-then Statement
public class EvalScore {
}
}
68
The if-then-else Statement
// Using if_else
//Program to test if student score is greater than or less than 60
class EvalScore {
else
}
}
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.
Display the
quotient
72
The if-then-else Statement
{
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:
Assignment
76
Boolean Operators
|| or logical disjunction
Example
(3 > 2) && (5 >= 5) is true, because (3 > 2) and (5 >= 5) are both true.
79
Boolean Operators
80
public class TestBoolean {
} } 81
A runtime error
For example,
(x != 0) & (100 / x) is a runtime error
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).
}
}
_____________________________
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