Java Programming Chapter 1(1)
Java Programming Chapter 1(1)
Java Basics
What is a Variable?
type name
Creating Variables (continued)
pageCount
loadFile
anyString
threeWordVariable
POP QUIZ
• Which of the following are valid variable
names?
1)$amount
2)6tally
3)my*Name
4)salary
5)_score
6)first Name
7)total#
Statements
• A statement is a command that causes
something to happen.
• All statements in Java are separated by
semicolons ;
• Example:
System.out.println(“Hello, World”);
- 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 Hungry = true;
boolean fileOpen = false;
Character Data Types
• 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 = '?' ;
Integers
Data Type Description
byte Variables of this kind can have a value from:
-128 to +127 and occupy 8 bits in memory
short Variables of this kind can have a value from:
-32768 to +32767 and occupy 16 bits in memory
int Variables of this kind can have a value from:
-2147483648 to +2147483647 and occupy 32 bits in memory
long Variables of this kind can have a value from:
-9223372036854775808 to +9223372036854775807 and occupy
64 bits in memory
Primitive Data Types (cont)
Real Numbers
Data Type Description
• Examples:
3 + 5 // uses + operator
14 + 5 – 4 * (5 – 3) // uses +, -, * operators
– Arithmetic operators
– Assignment operator
– Increment/Decrement operators
– Relational operators
– Conditional operators
Arithmetic Operators
• Java has 5 basic arithmetic operators
+ add
- subtract
* multiply
/ divide
% modulo
(remainder)
• 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 (Comparison) Operators
• Relational operators compare two values
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)
Conditional Operators
Symbol Name
&& AND
|| OR
! NOT
(x || y) evaluates to true
(true && x) evaluates to true
• Examples:
(a && (b++ > 3))
(x || y)
(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.
Bitwise Operators
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise complement
Operator Notes
++ --
+- Addition, subtraction
== != Equality
& AND
^ XOR
| OR
|| Logical OR
= += -= *= /= %= ^= Various assignments
POP QUIZ
1) What is the value of number? -12
int number = 5 * 3 – 3 / 6 – 9 * 3;
statement
statement
statement
statement
statement statement
What are Control Structures?
• 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-Else Statement
if (expression) {
statement1;
}
else{
statement2;
}
next_statement;
execute execute
if (expression){
statement1 statement2
statement1;
} else {
statement2;
} execute
rest_of_program rest_of_program
Chained If-Else Statements
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.");
Switch Statements
• The switch statement enables you to test several cases
generated by a given expression.
• 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
Break Statements in Switch Statements
• 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
Remember the Chained If-Else . . .
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.");
}
int sum = 0;
int i = 1;
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
The for Loop
for (init_expr; loop_condition; increment_expr) {
statement;
}
int sum = 0;
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
• 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;
}
Specifies an array of
variables of type int
We are creating
a new array object
• For example:
int[] prices;
String[] names;
Creating a New "Empty" Array
prices[0] = 6.75;
prices[1] = 80.43;
prices[2] = 10.02;
Constructing Arrays
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];
• 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
Output:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)
Exception Message Details
Exception message format:
[exception class]: [additional description of exception]
at [class].[method]([file]:[line number])
Example:
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)
Exception Error
Runtime Exception
• Exception class is used for exceptional conditions
that user programs should catch.
• Exception of type RuntimeException are
automatically defined for the programs that you
write.
• Error class defines exceptions that are not
expected to be caught under normal
circumstances.
Uncaught Exceptions
• When Java runtime system detects an
exception
– It throws this exception.
– Once thrown it must be caught by an exception
handler and dealt with immediately.
– If exception handling code is not written in the
program , default handler of java catch the
exception.
– The default handler displays a string describing
the exception & terminates the program.
• Handling exceptions by ourselves
provides 2 benefits.
try {
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}
Exception Handling Example
class example{
public static void main(String args[])
int d,a;
try
{
d=0;
a=42/d;
}catch (ArithmeticException e) {
System.out.println(“Division by
zero.");
}
}
• Once an exception is thrown program
control transfers to the try block from a
catch.
• NullPointerException
reference is null and should not be
• IllegalArgumentException
method argument is improper is some way
Checked Exceptions
Exception
ArrayIndexOutofBounds FileNotFoundException
NullPointerException MalformedURLException
llegalArgumentException SocketException
etc. etc.