All Slides Before OOP
All Slides Before OOP
program
compiler compiler
compiler
Unix
Win
MAC
Java is a little different.
Java compiler produces bytecode not
machine code.
Bytecode can be run on any computer
with the Java interpreter installed. Win
compiler Interpreter
Unix
Advantages:
Java is platform independent. Once it's compiled, you can run the
bytecode on any machine with a Java interpreter. You do not have to
recompile for each platform.
Disadvantages:
Running bytecode through the interpreter is not as fast as running
machine code, which is specific to that platform.
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Although the file name includes the .class extension , this part of the name must be left off when
running the program with the Java interpreter
Java is an object-oriented programming
language
Example 2: Cars
States: color, model, speed, direction
Behaviors: accelerate, turn, change gears
Definition: A class is a blueprint that defines the
states and the behaviors common to all objects of
a certain kind.
type name
Now you have the variable (highScore), you
will want to assign a value to it.
highScore = 98;
String studentName;
boolean gameOver;
The name that you choose for a variable is called
an identifier. In Java, an identifier can be of any
length, but must start with:
a letter (a – z),
a dollar sign ($),
or, an underscore ( _ ).
pageCount
loadFile
anyString
threeWordVariable
Which of the following are valid variable
names?
1)$amount
2)6tally
3)my*Name
4)salary
5)_score
6)first Name
7)total#
A statement is a command that causes
something to happen.
All statements in Java are separated by
semicolons ;
Example:
System.out.println(“Hello, World”);
long -9223372036854775808 to
+9223372036854775807
Here are some examples of when you would
want to use integer types:
- byte smallValue;
smallValue = -55;
- int pageCount = 1250;
- long bigValue = 1823337144562L;
double g = 7.7e100 ;
double tinyNumber = 5.82e-203;
float costOfBook = 49.99F;
Example:
boolean monsterHungry = true;
boolean fileOpen = false;
Character is a data type that can be used to
store a single characters such as a letter,
number, punctuation mark, or other symbol.
Example:
char firstLetterOfName = 'e' ;
char myQuestion = '?' ;
• Examples:
3 + 5 // uses + operator
14 + 5 – 4 * (5 – 3) // uses +, -, * operators
Arithmetic operators
Assignment operator
Increment/Decrement operators
Relational operators
Conditional operators
Java has 6 basic arithmetic operators
+ add
- subtract
* multiply
/ divide
% modulo (remainder)
^ exponent (to the power of)
double x = 63;
double y = 35;
System.out.println(x / y);
Ouput: 1.8
count = count - 1;
can be written as:
--count; or count--;
int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = ++numOranges + numApples;
numFruit has value 16
numOranges has value 6
int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = numOranges++ + numApples;
numFruit has value 15
numOranges has value 6
• Relational operators compare two values
• Produces a boolean value (true or false)
depending on the relationship
operation is true when . . .
a == b a is equal to b
a != b a is not equal to b
int x = 3;
int y = 5;
boolean result;
3) result = (x != x*y);
now result is assigned the value true because the product of
x and y (15) is not equal to x (3)
Symbol Name
&& AND
|| OR
! NOT
Conditional operators can be referred to as boolean
operators, because they are only used to combine
expressions that have a value of true or false.
x y x && y x || y !x
(x || y) evaluates to true
(true && x) evaluates to true
(x || y)
What happens if x is true?
Similarly, Java will not evaluate the right-hand
operator y if the left-hand operator x is true, since
the result is already determined in this case to be
true.
1) What is the value of number? -12
int number = 5 * 3 – 3 / 6 – 9 * 3;
statement statement
a simple program
statement
statement
statement
statement
statement statement
Control structures alter the flow of the
program, the sequence of statements that are
executed in a program.
if (expression) { yes
statement1;
} execute
statement
rest_of_program
execute
rest_of_program
if (expression) {
statement1;
}
else{
statement2;
}
next_statement;
For example:
switch (expression) {
case value1:
statement1;
case value2:
statement2;
default:
default_statement;
}
Every statement after the true case is executed
Do default action
Continue the
program
The break statement tells the computer to exit
the switch statement
For example:
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
default:
default_statement;
break;
}
switch (expression){ expression y
case value1: equals Do value1 thing break
// Do value1 thing value1?
break;
case value2: n
// Do value2 thing
break;
expression y
... equals Do value2 thing break
default: value2?
// Do default action
break;
} n
// Continue the program
do default action
Continue the
break
program
if (grade == 'A')
System.out.println("You got an A.");
else if (grade == 'B')
System.out.println("You got a B.");
else if (grade == 'C')
System.out.println("You got a C.");
else
System.out.println("You got an F.");
This is how it is accomplished with a switch:
switch (grade) {
case 'A':
System.out.println("You got an A.");
break;
case 'B':
System.out.println("You got a B.");
break;
case 'C':
System.out.println("You got a C.");
break;
default:
System.out.println("You got an F.");
}
if-else chains can be sometimes be rewritten as a
“switch” statement.
switches are usually simpler and faster. Why???
A loop allows you to execute a statement or
block of statements repeatedly.
int sum = 0;
int i = 1;
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
for (init_expr; loop_condition; increment_expr) {
statement;
}
int sum = 0;
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
Example 3:
int n = 0;
for(; n <= 100;) {
System.out.println(++n);
}
The for loop
Initialize count
The while loop
n n
Test condition Test condition
is true? is true?
y
y
Execute loop
statement(?) Execute loop
statement(s)
Increment
Next statement count
New statement
The continue statement causes the program
to jump to the next iteration of the loop.
/**
* prints out "5689"
*/
for(int m = 5; m < 10; m++) {
if(m == 7) {
continue;
}
System.out.print(m);
}
Another continue example:
int sum = 0;
for(int i = 1; i <= 10; i++){
if(i % 3 == 0) {
continue;
}
sum += i;
}
For example:
int[] prices;
String[] names;
Use this syntax: new int[20]
The new keyword creates an array of type
int that has 20 compartments
The new array can then be assigned to an
array variable:
int[] prices = new int[20];
When first created as above, the items in the
array are initialized to the zero value of the
datatype
int: 0 double: 0.0 String:
null
Every compartment in an array is assigned an
integer reference.
prices[0] = 6.75;
prices[1] = 80.43;
prices[2] = 10.02;
To construct an array, you can declare a
new empty array and then assign values
to each of the compartments:
Another example:
int[] powers = {0, 1, 10, 100};
String[] names = {
"David", "Qian", "Emina",
"Jamal", "Ashenafi" };
int numberOfNames = names.length;
System.out.println(numberOfNames);
Output: 5
Output:
Hello Aisha.
Hello Tamara.
Hello Gikandi.
Hello Ato.
Hello Lauri.
Modifying Array Elements
Example:
names[0] = “Bekele"
b. int[] arr;
arr = new int[4];
0 1
The arrays we've used so far can be
thought of as a single row of values. 0 8 4
A 2-dimensional array can be thought
of as a grid (or matrix) of values 1 9 7
Each element of the 2-D array is
accessed by providing two indexes:
2 3 6
a row index and a column index value at row index 2,
column index 0 is 3
(A 2-D array is actually just an array of arrays)
2-D Array Example
Example:
A landscape grid of a 20 x 55 acre piece of land:
We want to store the height of the land at each
row and each column of the grid.
inputs outputs
method
Square Root Method
Square root is a good example of a method.
Example:
int absoluteValue (int num){
if (num < 0)
return –num;
else
return num;
}
void Methods
class SayHi {
public static void main(String[] args) {
System.out.println("Hi, " + args[0]);
}
}