Chapter - 0 Introduction To Java Programming
Chapter - 0 Introduction To Java Programming
1 2
3 4
Java Program Structure Java Program Structure …
In the Java programming language: // comments about the class
public class MyProgram
◦ A program is made up of one or more classes {
◦ A class contains one or more methods // comments about the method
◦ A method contains program statements public static void main (String[] args)
{
These terms will be explored in detail throughout method body
method header
the course }
main
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
5 Programming(CoSc3053) lecture slides
6
5 6
7 8
The Compiler and the Java Virtual Machine… The Compiler and the Java Virtual Machine…
A program written in a high-level language like java is Most compilers translate source code into
called a source program. executable files containing machine code.
Since a computer cannot understand a source program, a The Java compiler translates a Java source file into a
program called a compiler is used to translate the
file that contains byte code instructions.
◦ Byte code files end with the .class file extension.
source program into a machine language program called
Byte code instructions are the machine language of
an object program.
the Java Virtual Machine (JVM) and cannot be directly
The object program is often then linked with other executed by the CPU.
supporting library code before the object can be executed ◦ The JVM is a program that emulates a micro-processor.
on the machine. ◦ The JVM executes instructions as they are read.
◦ JVM is often called an interpreter.
Therefore, Java is both compiled and interpreted
Source File Compiler Object File Linker Excutable File
language.
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
9 Programming(CoSc3053) lecture slides
10
9 10
Java Virtual
Machine
Any
Computer
Java Results in Program
Virtual Execution
Machine
11 12
Multiple Compilers Java Interpreter
Because different operating systems (Windows, Macs, Java is a little different.
Unix) require different machine code, you must Java compiler produces bytecode not machine code.
compile most programming languages separately for Bytecode can be run on any computer with the Java
each platform. interpreter installed.
program
compiler compiler
compiler
Unix
Win
MAC
13 14
Your First Java Program Compiling and Running Your First Program
Open your text-editor and type the following piece of Java Open the command prompt in Windows
code exactly: To run the program that you just wrote, type at the
command prompt:
class HelloWorld { cd c:\java
public static void main(String[] args) Your command prompt should now look like this:
{ c:\java>
To compile the program that you wrote, you need to run the Java
System.out.println("Hello World!"); Development Tool Kit Compiler as follows:
} At the command prompt type:
c:\java> javac HelloWorld.java
} You have now created your first compiled Java program named
HelloWorld.class
To run your first program, type the following at the command
Save this file as HelloWorld.java (watch capitalization) in the prompt:
c:\java>java HelloWorld
following directory:
Although the file name includes the .class extension , this part of the name must be left off
c:\java when running the program with the Java interpreter.
15 16
Creating, Compiling, and Running Programs Types of Java Program
Create/Modify Source Code
All Java programs can be classified as
Source code (developed by the programmer)
Applications and Applets.
Saved on the disk
Result
interactive web applications
If runtime errors or incorrect result
17 18
19 20
Types of Java Program… Basics in Java Programming
Short Review
◦ All Java programs must be stored in a file with a .java
file extension.
◦ A .java file may contain many classes but may only have
one public class.
◦ If a .java file has a public class, the class must have the
same name as the file.
21 22
23 24
Creating Variables Creating Variables…
To create a variable, declare its name and the Now you have the variable (highScore), you will
type of information that it will store. want to assign a value to it.
The type is listed first, followed by the name.
Example: the highest score in the class exam is
Example: a variable that stores an integer 98.
representing the highest score on an exam could
be declared as follows: highScore = 98;
25 26
27 28
Naming Variables… POP QUIZ
When naming a variable, the following Which of the following are valid variable names?
convention is commonly used:
1)$amount
◦ The first letter of a variable name is lowercase
2)6tally
◦ Each successive word in the variable name begins
with a capital letter 3)my*Name
◦ All other letters are lowercase 4)salary
Here are some examples: 5)_score
6)first Name
pageCount 7)total#
loadFile
anyString
threeWordVariable
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
29 Programming(CoSc3053) lecture slides
30
29 30
31 32
Java is a Strongly-Typed Language Primitive Data Types
All variables must be declared with a data type before There are eight built-in (primitive) data types in
they are used. the Java language
Each variable's declared type does not change over ◦ 4 integer types (byte, short, int, long)
the course of the program. ◦ 2 floating point types (float, double)
◦ Boolean (boolean)
Certain operations are only allowed with certain data ◦ Character (char)
types.
**see Appendix II: Summary of Primitive Data Types for a
If you try to perform an operation on an illegal data complete table of sizes and formats**
type (like multiplying Strings), the compiler will report Appendix II: Primitive Data Types
an error.
33 34
The one you choose to use depends on the size - byte smallValue;
of the number that we want to store. smallValue = -55;
Data Type Value Range - int pageCount = 1250;
byte -128 to +127 - long bigValue = 1823337144562L;
short -32768 to +32767
int -2147483648 to +2147483647 Note: By adding an L to the end of the value in the last
long -9223372036854775808 to +9223372036854775807 example, the program is “forced” to consider the
value to be of a type long even if it was small
In this course, we will always use int when enough to be an int
dealing with integers.
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
35 Programming(CoSc3053) lecture slides
36
35 36
Floating Point Data Types Floating Point Data Types…
There are two data types that can be used to Here are some examples of when you would
store decimal values (real numbers).
want to use floating point types:
The one you choose to use depends on the size
of the number that we want to store. ◦ double g = 7.7e100 ;
Data Type Value Range ◦ double tinyNumber = 5.82e-203;
float 1.4×10-45 to 3.4×1038 ◦ float costOfBook = 49.99F;
double 4.9×10-324 to 1.7×10308
37 38
Example: Example:
boolean monsterHungry = true; ◦ char firstLetterOfName = 'e' ;
boolean fileOpen = false; ◦ char myQuestion = '?' ;
39 40
Introduction to Strings POP QUIZ
Strings consist of a series of characters inside What data types would you use to store the
double quotation marks. following types of information?
Examples statements assign String variables:
String coAuthor = "John Smith"; 1)Population of Ethiopia int
String password = "swordfish786"; 2)Approximation of π double
3)Open/closed status of a file boolean
Strings are not one of the primitive data types,
although they are very commonly used. 4)Your name String
5)First letter of your name char
Strings are constant; their values cannot be 6)$237.66 double
changed after they are created.
41 42
43 44
Arithmetic Operators Order of Operations
Java has 6 basic arithmetic operators Example: 10 + 15 / 5;
+ add
- subtract The result is different depending on whether the
* multiply addition or division is performed first
/ divide
(10 + 15) / 5 = 5
% modulo (remainder)
10 + (15 / 5) = 13
^ exponent (to the power of)
45 46
double x = 63;
Depending on the data types of the variables that
double y = 35;
store the numbers, we will get different results. System.out.println(x / y);
Ouput: 1.8
The result of integer division is just the integer part of the
quotient!
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
47 Programming(CoSc3053) lecture slides
48
47 48
Assignment Operator Increment/Decrement Operators
The basic assignment operator (=) assigns the count = count + 1;
value of var to expr can be written as:
var = expr ; ++count; or count++;
Java allows you to combine arithmetic and ++ is called the increment operator.
assignment operators into a single operator.
Examples: count = count - 1;
can be written as:
x = x + 5; is equivalent to x += 5; --count; or count--;
y = y * 7; is equivalent to y *= 7;
-- is called the decrement operator.
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
49 Programming(CoSc3053) lecture slides
50
49 50
51 52
Examples of Relational Operations Conditional Operators
int x = 3; Symbol Name
int y = 5;
boolean result; && AND
1) result = (x > y); || OR
now result is assigned the value false because
3 is not greater than 5 ! NOT
2) result = (15 == x*y);
now result is assigned the value true because the product of Conditional operators can be referred to as boolean
3 and 5 equals 15 operators, because they are only used to combine
3) result = (x != x*y); expressions that have a value of true or false.
now result is assigned the value true because the product of
x and y (15) is not equal to x (3)
53 54
55 56
Using && and || Short-Circuit Evaluations
Examples: (a && (b++ > 3))
(a && (b++ > 3)) What happens if a is false?
(x || y)
Java will not evaluate the right-hand expression (b++ >
3) if the left-hand operator a is false, since the result
Java will evaluate these expressions from left to is already determined in this case to be false. This
means b will not be incremented!
right and so will evaluate
a before (b++ > 3)
(x || y)
x before y
What happens if x is true?
Java performs short-circuit evaluation: Similarly, Java will not evaluate the right-hand operator y if
it evaluates && and || expressions from left to the left-hand operator x is true, since the result is
already determined in this case to be true.
right and once it finds the result, it stops.
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
57 Programming(CoSc3053) lecture slides
58
57 58
59 60
Appendix I: Reserved Words Appendix II: Primitive Data Types
The following keywords are reserved in the Java The following tables show all of the primitive data
language. types along with their sizes and formats:
They can never be used as identifiers: Integers
abstract assert boolean break byte Data Type Description
case catch char class const byte Variables of this kind can have a value from:
continue default do double else -128 to +127 and occupy 8 bits in memory
extends final finally float for short Variables of this kind can have a value from:
goto if implements import instanceof -32768 to +32767 and occupy 16 bits in memory
int interface long native new int Variables of this kind can have a value from:
-2147483648 to +2147483647 and occupy 32 bits in
package private protected public return
memory
short static strictfp super switch
long Variables of this kind can have a value from:
synchronized this throw throws transient
-9223372036854775808 to +9223372036854775807 and
try void violate while occupy 64 bits in memory
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
61 Programming(CoSc3053) lecture slides
62
61 62
63 64
What are Arrays? Array Visualization
An array is a series of compartments to store
Specifies an array of
data. variables of type int
We are creating
a new array object
Each compartment is appropriately sized for the
particular data type the array is declared to store. int[] primes = new int[10]; // An array of 10 integers
65 66
67 68
Array Indexes Accessing Array Elements
Every compartment in an array is assigned an To access an item in an array, type the name of
integer reference number. the array followed by the item’s index in square
brackets.
This number is called the index of the
compartment For example, the expression:
names[0];
Important: In Java (and most other languages), the
will return the first element in the names array
index starts from 0 and ends at n-1, where n is the
size of the array
69 70
71 72
Another Way to Construct Arrays Length of array
You can also specify all of the items in an array at String[] names = {
its creation. "David", "Qian", "Emina",
"Jamal", "Ashenafi" };
Use curly brackets to surround the array’s data int numberOfNames = names.length;
and separate the values with commas: System.out.println(numberOfNames);
String[] names = { "David", "Qian",
"Emina", "Jamal", "Ashenafi"};
Output: 5
Note that all the items must be of the same type.
Here they are of type String.
Important:Arrays are always of the same size:
Another example: their lengths cannot be changed once they are
int[] powers = {0, 1, 10, 100}; created!
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
73 Programming(CoSc3053) lecture slides
74
73 74
75 76
Example Exercise 1
int[] fibs = new int[10]; Which of the following sequences of statements
fibs[0] = 1; does not create a new array?
fibs[1] = 1;
for(int i = 2; i < fibs.length; i++)
{ a. int[] arr = new int[4];
fibs[i] = fibs[i-2] + fibs[i-1];
} b. int[] arr;
arr = new int[4];
After running this code, the array fibs[]
contains the first ten Fibonacci numbers: c. int[] arr = { 1, 2, 3, 4};
1 1 2 3 5 8 13 21 34 55
d. int[] arr; just declares an array variable
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
77 Programming(CoSc3053) lecture slides
78
77 78
Exercise 2 Exercise 3
Given this code fragment, Which set of data would not be suitable
for storing in an array?
int[] data = new int[10];
System.out.println(data[j]); a. the score for each of the four quarters of a Football
match
b. your name, date of birth, and score on your physics
Which of the following is a legal value of j? test // these are different types
c. temperature readings taken every hour throughout a
a. -1 // out of range day
b. 0 // legal value
d. your expenses each month for an entire year
c. 3.5 // out of range
d. 10 // out of range
79 80
Exercise 4 2-Dimensional Arrays
What is the value of c after the following code The arrays we've used so far can be
segment execute? thought of as a single row of values. 0 1
int [] a = {1, 2, 3, 4, 5}; A 2-dimensional array can be thought 0 8 4
int [] b = {11, 12, 13}; of as a grid (or matrix) of values 1 9 7
int [] c = new int[4]; 2 3 6
for (int j = 0; j < 3; j++) { Each element of the 2-D array is
value at row index 2,
c[j] = a[j] + b[j]; accessed by providing two indexes: column index 0 is 3
81 82
We declare a 2D array two sets of square brackets: Decision & Repetition Statements
double[][] heights = new
double[20][55];
83 84
Flow of Program What are Control Structures?
Java will execute the statements in your code in a specific Control structures alter the flow of the program,
sequence, or "flow". the sequence of statements that are executed in a
The "flow" of the program can be described through a program.
"flow diagram":
They act as "direction signals" to control the path
a simple program a program takes.
statement
Two types of control structures in Java:
statement
◦ decision statements
statement ◦ loops
statement
85 86
87 88
If Statement Flow Diagram If-Else Statement
if (expression){
The if decision statement executes statement1;
a statement if an expression is true }
else{
Is expression no
statement2;
true? }
next_statement;
if (expression) {
yes
statement1; Again, expression must produce a boolean value
} execute
statement If expression is true, statement1 is executed and then
rest_of_program next_statement is executed.
89 90
91 92
Switch Statements 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
93 94
break; default:
case value2: // Do default
statement2; action n
break; break;
}
default: // Continue the do default action
default_statement; program
break;
Continue the
} break program
95 96
Remember the Chained If-Else . . . Break Statements in Switch Statements…
This is how it is accomplished with a switch:
if (grade == 'A') switch (grade) {
case 'A':
System.out.println("You got an A."); System.out.println("You got an A.");
else if (grade == 'B') break;
case 'B':
System.out.println("You got a B."); System.out.println("You got a B.");
break;
else if (grade == 'C') case 'C':
System.out.println("You got a C.");
System.out.println("You got a C."); break;
default:
else System.out.println("You got an F.");
System.out.println("You got an F."); }
97 98
99 100
For example: for Loop
int sum = 0; for (init_expr; loop_condition; increment_expr)
int i = 1; {
statement;
while (i <= 10){ }
sum += i; The control of the for loop appear in parentheses and is made up of
i++; three parts:
}
1. The first part, the init_expression,sets the initial
conditions for the loop and is executed before the loop starts.
What is the value of sum?
2. Loop executes as long as the loop_condition is true and
exits otherwise.
101 102
What is the value of sum? What will this for loop do?
103 104
for loop… loop statements…
If there is more than one variable to set up or The for loop
but you must still have two semicolons. Execute loop Execute loop
statement(?) statement(s)
int n = 0; Increment
for(; n <= 100;) { count
Next statement
System.out.println(++n);
} New statement
105 106
107 108
The break Statement Nested Loops
We have seen the use of the break statement in the You can nest loops of any kind one inside another to
switch statement. any depth. What does this print?
You can also use the break statement to exit the loop for(int i = 10; i > 0; i--) {
entirely. if (i > 7) {
continue; 6
// prints out numbers unless
// num is ever exactly 400
} 5
while (num > 6) {
while (i > 3) {
if(i == 5) {
5
if(num == 400) { break; 3
break;
} 3
}
System.out.println(num);
System.out.println(--i); 2
}
num -= 8;
System.out.println(i);
1
}
}
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
109 Programming(CoSc3053) lecture slides
110
109 110
POP QUIZ
1. In the switch statement, which types can
expression evaluate to?
char, byte, short, int
2. What must be used to separate each section of a for
statement.
semicolons
3. Which statement causes a program to skip to the next
iteration of a loop.
continue
4. Write a for loop that outputs 100-1 in reverse
sequence.
5. Write a for loop that outputs all numbers that are End of the Chapter
divisible by 3 between 0-50.
111 112