Object Oriented Programming: Java Basics
Object Oriented Programming: Java Basics
Lecture 1:
Java Basics
Java basics
Input/output
Variables
Expressions
Conditions
loops
// 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.
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
Common escape sequences
7
Command-line inputs.
Use command-line inputs to read in a few user values.
Not practical for many user inputs.
Standard input.
Flexible OS abstraction for input.
By default, standard input is received from Terminal
window.
Input entered while program is executing.
% java TestIO 5
25
% java TestIO 10
100
int total = 0;
Addition +
Subtraction -
Multiplication *
Division /
Remainder %
a / (b + c) - d % e
2 1 4 3
a / (b * (c + (d - e)))
4 3 2 1
float double
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?)
Explicitly: Casting
widening / narrowing conversions
Examples:
double MyResult;
MyResult = 12.0 / 5.0; //OK
int myInt = (int) MyResult; // truncation
MyResult = (double)myInt/3.0;
// 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
if ( condition )
statement1;
else
statement2;
true false
Statement 1 Statement 2
do statement do
{
statement list;
} while ( condition );
for statement
for ( initialization ; condition ; increment )
statement;
int sum = 0;
for (int counter = 1; counter <= max; counter++)
sum += counter;
// beginning of the next statement
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