You are on page 1of 44

1

OBJECT ORIENTED PROGRAMMING


Using Java

Lecture 1:
Java Basics

Dr. Amal Khalifa, 2013


Lecture Contents
2

 Java basics
 Input/output

 Variables

 Expressions

 Conditions

 loops

Dr. Amal Khalifa, 2013


Your first Java program..
3

// indicates a
comment.

class keyword

Java is case
sensitive

braces { , }
delimit a
class body

main Method
“Everything must be in a class”
There are no global functions or global data.

Dr. Amal Khalifa, 2013


Basic language elements
4

Dr. Amal Khalifa, 2013


Text I/O
5

 Standard output.
 Flexible OS abstraction for output.
 In Java, applications use the standard output object
(System.out) to display text on terminal.

Dr. Amal Khalifa, 2013


Command line output
6

public class TestIO {


Multiple line
O/P public static void main(String[] args)
{
Formatting System.out.println(“Welcome to java”);
output
System.out.println(“Welcome to \n java”);
System.out.print(“Welcome to”);
System.out.println(“java”);
System.out.printf(“%s\n%s\n“, “Welcome
to”,”java”);

}
}
}
Dr. Amal Khalifa, 2013
Common escape sequences
7

Dr. Amal Khalifa, 2013


Printf Conversion-Characters
8

Dr. Amal Khalifa, 2013


Strings & Text
9

String msg1 = new String( “Hello” );


String msg2 = “Hello” ;
String msg3 = “Year “ + 2005; //valid??
Input
10

 Command-line inputs.
 Use command-line inputs to read in a few user values.
 Not practical for many user inputs.

 Input entered before program begins execution.

 Standard input.
 Flexible OS abstraction for input.
 By default, standard input is received from Terminal
window.
 Input entered while program is executing.

Dr. Amal Khalifa, 2013


Command line input
11

public class TestIO {


public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
System.out.println(N*N);
}
}
} % java TestIO 4
16

% java TestIO 5
25

% java TestIO 10
100

Dr. Amal Khalifa, 2013


Reading numbers
12

 use : import java.util.Scanner;


 Define an object of the Scanner class:
Scanner input = new Scanner(System.in);
 input values:
num1 = input.nextInt();
 Display after calculation:
System.out.printf(“the square is : %d
\n”, num1*num1);

Dr. Amal Khalifa, 2013


example
13
example
14

Dr. Amal Khalifa, 2013


variables
15

 Declaration, memory allocation, initialization

data type variable name

int total = 0;

int count, temp, result;

Multiple variables can be created in one declaration

Dr. Amal Khalifa, 2013


Constants
16

 A “constant variable” is an identifier that is similar to a


variable except that it holds one value for its entire existence
 Why constants:
 give names to otherwise unclear literal values
 facilitate changes to the code
 prevent inadvertent errors
 In Java:
final double PI = 3.14159265;

Dr. Amal Khalifa, 2013


Arithmetic Expressions
17

 An expression is a combination of operators and operands


 Arithmetic expressions (we will see logical expressions later)
are essentially special methods applied to numerical data
objects: compute numeric results and make use of the arithmetic
operators:

Addition +
Subtraction -
Multiplication *
Division /
Remainder %

Dr. Amal Khalifa, 2013


Assignment-related Operators
18

 Increment and decrement operators: ++, --


 Assignment operators: +=, -=, *=, /=
these three expressions have the same effect
count = count + 1;
count += 1;
count ++;

these two expressions have the same effect

count = count - 10;


count -= 10;
Dr. Amal Khalifa, 2013
Operator Precedence
19

 What is the order of evaluation in the following


expressions?
a + b + c + d + e a + b * c - d / e
1 2 3 4 3 1 4 2

a / (b + c) - d % e
2 1 4 3

a / (b * (c + (d - e)))
4 3 2 1

Dr. Amal Khalifa, 2013


Mixed-type Expressions
20

 Java is a strongly typed language, i.e., to perform the mixed-


type numerical operation, Java needs to convert the operands
to be of the same type
 remember: 4 / 8 ≠ 4.0 / 8.0
 sometimes it is more efficient (and natural) to store data
as one type, but during a computation, we may want to
treat the data as a different type to get desired results
 widening primitive conversions
 narrowing primitive conversions

Dr. Amal Khalifa, 2013


Widening Primitive Conversions
21

 Widening primitive conversions are those that do


not lose information about the overall magnitude of
a numeric value. eg:
 char  int, long, float, double
 int  long, float, double

 float  double

 They are generally safe because they tend to go


from a small data type to a larger one

Dr. Amal Khalifa, 2013


Narrowing Primitive Conversions
22

 Narrowing primitive conversions may lose overall magnitude


of a numeric value, or precision
 Java defines 23 primitive conversions as narrowing
primitive conversions
byte  char
short  byte, char
char  byte, short
int  byte, short, char
long  byte, short, char, int
float  byte, short, char, int, long
double byte, short, char, int, long, float

Dr. Amal Khalifa, 2013


How Do Data Conversions Happen?
23

 Implicitly:
 occursautomatically
 uses widening conversion,

 Examples :
4.0 / 8 (which / is it: double/double, float/float, int/int)
4 / 8.0 (which / is it: double/double, float/float, int/int)
4 + 5 / 9 + 1.0 + 5 / 9 / 10.0 (what is the value?)

Dr. Amal Khalifa, 2013


How Do Data Conversions Happen?
24

 Explicitly: Casting
 widening / narrowing conversions
 Examples:
double MyResult;
MyResult = 12.0 / 5.0; //OK
int myInt = (int) MyResult; // truncation
MyResult = (double)myInt/3.0;

Dr. Amal Khalifa, 2013


Be careful!!
25

 Example: in 1996, Ariane 5 rocket exploded after


takeoff because of bad type conversion.

Dr. Amal Khalifa, 2013


Class Math
26

 All Math class methods are static


 Each is called by preceding the name of the method with the class
name Math and the dot (.) separator
 Method arguments may be constants, variables or
expressions

Dr. Amal Khalifa, 2013


27 Dr. Amal Khalifa, 2013
Example
28

 Solve quadratic equation ax2 + bx + c = 0.


public class Quadratic {
public static void main(String[] args) {
double a,b,c,d;
// input coefficient values..

// calculate roots
d = Math.sqrt(b*b - 4.0*a*c);
double root1 = (-b + d) / (2.0*a);
double root2 = (-b - d) / (2.0*a);
// print them out
System.out.println(root1);
System.out.println(root2);
}
}
Dr. Amal Khalifa, 2013
Conditions & Branching
29

Dr. Amal Khalifa, 2013


Conditional Statements
30

 A conditional statement lets us choose which


statement will be executed next
 Conditional statements give us the power to make
basic decisions
 Java's conditional statements:
 the if and if-else statements
 the conditional operator
 the switch statement

Dr. Amal Khalifa, 2013


The if Statement
31

 The if statement has the following syntax:


The condition must be a boolean expression.
e.g., a boolean variable, a == b, a <= b.
if is a Java
It must evaluate to either true or false.
reserved word

if ( condition )
statement1;
else
statement2;

If the condition is true,


this statement is executed.
If the condition is false,
this statement is executed. Dr. Amal Khalifa, 2013
condition
evaluated

true false

Statement 1 Statement 2

32 Logic of an if-else statement


•Several statements can be grouped together into a block statement
•A block is delimited by braces ( { … } )

Dr. Amal Khalifa, 2013


Relational operators
33

Dr. Amal Khalifa, 2013


Logical Operators
34

Dr. Amal Khalifa, 2013


Loops & Iterations
35

Dr. Amal Khalifa, 2013


Loop Statements
36

 while statement while ( condition )


statement;

 do statement do
{
statement list;
} while ( condition );

 for statement
for ( initialization ; condition ; increment )
statement;

Dr. Amal Khalifa, 2013


37 While loops
while ( condition )
statement;
Dr. Amal Khalifa, 2013
Example
38

System.out.print( “Enter a month (1 to 12): “);


Look at int month = scan.nextInt();
the code
while (month < 1 || month > 12)
and {
describe System.out.println( month + “ is not a valid month.” );
the
System.out.print( “Enter a month (1 to 12): “);
output !!
month = scan.nextInt();
}

// set initial value of month so that the while condition


// below is false initially
int month = -1;
while (month < 1 || month > 12)
{
System.out.print( “Enter a month (1 to 12): “);
month = scan.nextInt();
}
39 do loops
do
{
statement;
}
while ( condition ); Dr. Amal Khalifa, 2013
Example
40

What is int month; // no need to initialize month


the
do
difference
here?? {
System.out.print( “Enter a month(1 to 12): “);
month = scan.nextInt();
} while (month < 1 || month > 12);

// beginning of the next statement

Dr. Amal Khalifa, 2013


41 for loops
for ( initialization ; condition ; increment )
statement;
Dr. Amal Khalifa, 2013
Example
42

int sum = 0;
for (int counter = 1; counter <= max; counter++)
sum += counter;
// beginning of the next statement

Establish initial value


int counter = 1
of control variable.

Determine if final
value of control true
counter <= max sum+= counter counter++
variable has been
reached.
Increment the
false Body of loop (this may be control variable.
multiple statements)
Simulation : Flipping a coin
43

public class Flip {


public static void main(String[] args) {
for (int i=0; i<1000; i++)
if (Math.random() < 0.5)
System.out.println("Heads");
else
System.out.println("Tails");
}
} % java Flip
Heads
 More examples?? % java Flip
Heads
% java Flip
Tails

Dr. Amal Khalifa, 2013


44 That’s all for today…..
Text Book:
Chap 2
Chap 4
Chap 5

Dr. Amal Khalifa, 2013

You might also like