0% found this document useful (0 votes)
17 views28 pages

Chapter - 0 Introduction To Java Programming

Uploaded by

teddytadesse490
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views28 pages

Chapter - 0 Introduction To Java Programming

Uploaded by

teddytadesse490
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Overview of Java Programming

 Java is an object-oriented programming


language
 The Java programming language was created by
Sun Microsystems, Inc.
 It was introduced in 1995 and it's popularity has
grown quickly
Chapter 0  Its primary feature is that it could function nicely
in a networked environment.
Overview of Java Programming  The explosion of WWW created an environment
in which the language could live.
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides Programming(CoSc3053) lecture slides
2

1 2

Overview of Java Programming… Characteristics of Java


 Java technology can be seen as both a language  Java Is Simple
and a platform.  Java Is Object-Oriented
 Using it you can write applications that can run  Java Is Distributed
on practically any device, including a PC, PDA, a  Java Is Interpreted
cellular phone or a television.  Java Is Robust
 Java Is Secure
 The Java platform is formed from two
 Java Is Architecture-Neutral
components:
◦ The Java application programming interface (Java API)
 Java Is Portable
 Set if libraries that are used to accomplish tasks such as creating  Java's Performance
GUIs, performing file I/O and establishing network comm.
 Java Is Multithreaded
◦ The Java Virtual Machine (JVM)
 Is in charge of executing your code in a specific environment.
 Java Is Dynamic

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
3 Programming(CoSc3053) lecture slides
4

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 }

 A Java application always contains a method called }

main
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
5 Programming(CoSc3053) lecture slides
6

5 6

Development Environments The Compiler and the Java Virtual Machine


 There are many tools to do java programming, to the  A programmer writes Java programming statements
very least you need to have: for a program called source code
◦ Java Development Kit (JDK Recent version)
◦ Text editor such as Microsoft Notepad ◦ A text editor is used to edit and save a Java source code file.
 Integrated Development Environment IDE for Java ◦ Source code files have a .java file extension.
◦ NetBeans (from Sun/Oracle)  A compiler is a program that translates source code
◦ Eclipse (from IBM) into an executable form.
◦ Borland JBuilder
◦ A compiler is run using a source code file as input.
◦ BlueJ
◦ JCreator ◦ Syntax errors caught during compilation if exist.
◦ DrJ ◦ Syntax errors are mistakes that violate the rules of the
◦ IntelliJ programming language.
◦ Android Studio and others ◦ Compiler creates another file that holds the translated
instructions and it is called byte code.
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
7 Programming(CoSc3053) lecture slides
8

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

Compiling Java Source Code Program Development Process


 With Java, you write the program once, and compile the
source program into a special type of object code, known Saves Java statements
Text editor Source code
as bytecode. (.java)
 The bytecode can then run on any computer with a Java
Virtual Machine, as shown below.
 Java Virtual Machine is a software that interprets Java Produces Byte code
Java compiler (.class)
bytecode Java Bytecode

Java Virtual
Machine

Any
Computer
Java Results in Program
Virtual Execution
Machine

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
11 Programming(CoSc3053) lecture slides
12

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

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
13 Programming(CoSc3053) lecture slides
14

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.

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
15 Programming(CoSc3053) lecture slides
16

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

Java applications are large programs that run


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!"); Source Code 
}

stand-alone, with the support of a virtual machine.


}

Compile Source Code


Byte code (generated by the compiler for JVM i.e., javac Welcome.java
to read and interpret, not for you to understand)

Method Welcome() If compilation errors
0 aload_0

Applet is a relatively small Java program executed


stored on the disk

Bytecode

Method void main(java.lang.String[])
0 getstatic #2 …
3 ldc #3 <String "Welcome to
Java!">
by web browser (inside an appletviewer).
5 invokevirtual #4 …

Applets are great for creating dynamic and


8 return Run Byteode
i.e., java Welcome

Result
interactive web applications
If runtime errors or incorrect result

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
17 Programming(CoSc3053) lecture slides
18

17 18

Types of Java Program… Types of Java Program…


 Applets on client-side and servlets on server-side  Advantages of Applets :
makes Java a truly "Internet-based language".  Execution of applets is easy in a Web browser and
 To execute applets, the browsers come with JRE does not require any installation or deployment
(Java Runtime Environment). procedure in real-time programming (where as
servlets require).
 The browsers with Java Runtime Environment (or
 Writing and displaying (just opening in a browser)
to say, JVM) loaded are known as Java enabled
graphics and animations is easier than
browsers. applications.
 Note: Browser do not have a Java compiler as a  In GUI development, constructor, size of frame,
compiled applet file (.class file) is given to window closing code etc. are not required (but
browser to execute. are required in applications).
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
19 Programming(CoSc3053) lecture slides
20

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.

◦ Comments are ignored by the compiler.

◦ 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.

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
21 Programming(CoSc3053) lecture slides
22

21 22

Basics in Java Programming… Java Identifiers


 Short Review • All java components requires names
• Names used for classes,Variables and methods
◦ Java applications must have a main method.
are called identifiers.
◦ For every left brace, or opening brace, there must be a
corresponding right brace, or closing brace.
 What is a Variable?
◦ Every java statements are terminated with semicolons. ◦ Variables are places where information can be stored
while a program is running.
◦ Comments, class headers, method headers, and braces
◦ Their values can be changed at any point over the
are not considered as Java statements. course of a program.
 Don’t need semicolons

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
23 Programming(CoSc3053) lecture slides
24

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;

int highScore ;  Examples of other types of variables:


String studentName;
type name boolean gameOver;
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
25 Programming(CoSc3053) lecture slides
26

25 26

Naming Variables Naming Variables…


 The name that you choose for a variable is called an  Java is a case-sensitive language – the
identifier.
 In Java, an identifier can be of any length, but must capitalization of letters in identifiers matters.
start with:
A rose is not a Rose is not a ROSE
a letter (a – z, A-Z),
a dollar sign ($),
or, an underscore ( _ ).  It is good practice to select variable names that
 The rest of the identifier can include any character give a good indication of the sort of data they
except those used as operators in Java such as + , - , hold
*.
 In addition, there are certain keywords reserved ◦ For example, if you want to record the size of a hat,
(e.g., "class") in the Java language which can never be hatSize is a good choice for a name where as qqq
used as identifiers. would be a bad choice
 see Reserved words
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
27 Programming(CoSc3053) lecture slides
28

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

Java Statements Variables and Statements


 A statement is a command that causes  One way is to declare a variable and then
something to happen. assign a value to it with two statements:
int e; // declaring a variable
 All statements in Java are separated by
e = 5; // assigning a value to a variable
semicolons ;

 Example:  Another way is to write a single initialization


System.out.println(“Hello,World”); statement:
 You have already used statements to create a int e = 5; // declaring AND assigning

variable and assign it a value.

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
31 Programming(CoSc3053) lecture slides
32

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.

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
33 Programming(CoSc3053) lecture slides
34

33 34

Integer Data Types Integer Data Types…


 There are four data types that can be used to  Here are some examples of when you would
store integers. want to use integer types:

 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

 Note: In the last example we added an F to the


 In this course, we will always use double when end of the value. Without the F, it would have
dealing with decimal values. automatically been considered a double instead.

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
37 Programming(CoSc3053) lecture slides
38

37 38

Boolean Data Type Character Data Types


 Boolean is a data type that can be used in  Character is a data type that can be used to store
situations where there are two options, either a single characters such as a letter, number,
true or false. punctuation mark, or other symbol.

 Example:  Example:
boolean monsterHungry = true; ◦ char firstLetterOfName = 'e' ;
boolean fileOpen = false; ◦ char myQuestion = '?' ;

 Note that you need to use singular quotation


marks when assigning char data types.
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
39 Programming(CoSc3053) lecture slides
40

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.

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
41 Programming(CoSc3053) lecture slides
42

41 42

Operators The Operator Groups


 What are Operators?  There are 5 different groups of operators:
◦ Operators are special symbols used for:
 mathematical functions ◦ Arithmetic operators
 assignment statements
◦ Assignment operator
 logical comparisons
• Examples: ◦ Increment/Decrement operators
3 + 5 // uses + operator
14 + 5 – 4 * (5 – 3) // uses +, -, *
◦ Relational operators
operators
◦ Conditional operators
 Expressions can be combinations of variables,
primitives and operators that result in a value

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
43 Programming(CoSc3053) lecture slides
44

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)

Without parentheses, Java will choose the second


 Order of operations (or precedence) when evaluating an case
expression is the same as you learned in school
(PEMDAS).  Note: you should be explicit and use parentheses
to avoid confusion

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
45 Programming(CoSc3053) lecture slides
46

45 46

Integer Division Integer Division…


 In the previous example, we were lucky that  Example
(10 + 15) / 5 gives an exact integer answer (5).  int i = 63;
int j = 35;
System.out.println(i / j);
 But what if we divide 63 by 35? Output: 1

 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

The increment/decrement operator has two forms: Relational (Comparison) Operators


◦ The prefix form ++count, --count
first adds 1 to the variable and then continues to any other operator  Relational operators compare two values
in the expression
 Produces a boolean value (true or false)
int numOranges = 5;
int numApples = 10; depending on the relationship
int numFruit;
numFruit = ++numOranges + numApples;
numFruit has value 16 operation is true when . . .
numOranges has value 6
a > b a is greater than b
◦ The postfix form count++, count-- a >= b a is greater than or equal to b
first evaluates the expression and then adds 1 to the variable
int numOranges = 5; a == b a is equal to b
int numApples = 10; a != b a is not equal to b
int numFruit;
numFruit = numOranges++ + numApples; a <= b a is less than or equal to b
numFruit has value 15
numOranges has value 6 a < b a is less than b
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
51 Programming(CoSc3053) lecture slides
52

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)

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
53 Programming(CoSc3053) lecture slides
54

53 54

Truth Table for Conditional Operators Examples of Conditional Operators


boolean x = true;
boolean y = false;
boolean result;

1. Let result = (x && y);

now result is assigned the value false


(see truth table!)
2. Let result = ((x || y) && x);
(x || y) evaluates to true
(true && x) evaluates to true
now result is assigned the value true

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
55 Programming(CoSc3053) lecture slides
56

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

POP QUIZ References


1) What is the value of number?
int number = 5 * 3 – 3 / 6 – 9 * 3;  Summary of Java operators
-12
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/opsummary.
2) What is the value of result? html
int x = 8;
int y = 2;
boolean result = (15 == x * y); false

 Order of Operations (PEMDAS)


3) What is the value of result?
boolean x = 7; 1. Parentheses
boolean result = (x < 8) && (x > 4); true
2. Exponents
4) What is the value of numCars? 3. Multiplication and Division from left to right
int numBlueCars = 5;
int numGreenCars = 10; 4. Addition and Subtraction from left to right
int numCars = numGreenCars++ + numBlueCars + 27
++numGreeenCars;

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
59 Programming(CoSc3053) lecture slides
60

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

Appendix II: Primitive Data Types… Arrays


 Real Numbers  A way to organize data
Data Type Description
float Variables of this kind can have a value from:
1.4e(-45) to 3.4e(+38)
double Variables of this kind can have a value from:
4.9e(-324) to 1.7e(+308)

 Other Primitive Data Types


char Variables of this kind can have a value from:
A single character
boolean Variables of this kind can have a value from:
True or False

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
63 Programming(CoSc3053) lecture slides
64

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

 An array is a collection of data values of the same


The array object is of
type. The name of
the array type int
and has ten elements index values

 An array can hold only one type of data!


primes[0] primes[1] primes[2] primes[3] primes[4] primes[9]
E.g. int[] can hold only integers
char[] can hold only characters
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
65 Programming(CoSc3053) lecture slides
66

65 66

Declaring an Array Variable Creating a New "Empty" Array


 Array declarations use square brackets. Use this syntax: new int[20]
datatype[] variable_name;  The new keyword creates an array of type int
that has 20 compartments
 For example:  The new array can then be assigned to an array
variable:
int[] prices;
int[] prices = new int[20];
String[] names;
 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

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
67 Programming(CoSc3053) lecture slides
68

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

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
69 Programming(CoSc3053) lecture slides
70

69 70

Filling an Array Constructing Arrays


 Assign values to compartments:  To construct an array, you can declare a
new empty array and then assign values to
prices[0] = 6.75;
each of the compartments:
prices[1] = 80.43; String[] names = new String[5];
prices[2] = 10.02; names[0] = "David";
names[1] = "Qian";
names[2] = "Emina";
names[3] = "Jamal";
names[4] = "Ashenafi";

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
71 Programming(CoSc3053) lecture slides
72

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

Example Modifying Array Elements


String[] names = {
"Aisha", "Tamara", "Gikandi", "Ato", "Lauri"};
 Example:
names[0] = “Bekele"
for(int i = 0; i < names.length; i++){
System.out.println("Hello " + names[i] + ".");
}
 Now the first name in names[] has been
changed from "Aisha" to "Bekele".
Output:
 So the expression names[0] now evaluates to
Hello Aisha.
Hello Tamara. "Bekele".
Hello Gikandi.
Hello Ato.  Note: The values of compartments can change,
Hello Lauri.
but no new compartments may be added.
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
75 Programming(CoSc3053) lecture slides
76

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

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
79 Programming(CoSc3053) lecture slides
80

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

a row index and a column index


}
c = [12, 14, 16, 0]  (A 2-D array is actually just an array of arrays)

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
81 Programming(CoSc3053) lecture slides
82

81 82

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.

 We declare a 2D array two sets of square brackets: Decision & Repetition Statements
double[][] heights = new
double[20][55];

 This 2D array has 20 rows and 55 columns

 To access the acre at row index 11 and column index 23


user: heights[11][23]
AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
83 AU/Computer Sc. Dept./OOP lecture slides 84

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

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
85 Programming(CoSc3053) lecture slides
86

85 86

Decision Statements If Statement


 A decision statement allows the code to if (expression) {
statement;
execute a statement or block of statements }
conditionally. rest_of_program;

 Two types of decisions statements in Java:  expression must evaluate to a boolean


value, either true or false
◦ if statements
◦ switch statements  If expression is true, statement is
executed and then rest_of_program
 If expression is false, statement is not
executed and the program continues at
rest_of_program
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
87 Programming(CoSc3053) lecture slides
88

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.

execute  If expression is false, statement2 is executed and then


rest_of_program next_statement is executed.

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
89 Programming(CoSc3053) lecture slides
90

89 90

If-Else Flow Diagram Chained If-Else Statements


The if-else decision
statement executes a if (grade == 'A')
is
statement if an expression is yes no System.out.println("You got an A.");
“expression”
true and a different statement true? else if (grade == 'B')
if it is not true.
System.out.println("You got a B.");
else if (grade == 'C')
execute execute
if (expression){ statement1 statement2 System.out.println("You got a C.");
statement1; else
} else { System.out.println("You got an F.");
statement2;
execute
} rest_of_program
rest_of_program
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
91 Programming(CoSc3053) lecture slides
92

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

 The expression must evaluate to a char, byte, short or


int, but not long, float, or double.
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
93 Programming(CoSc3053) lecture slides
94

93 94

Break Statements in Switch Statements Break Statements in Switch Statements…

 The break statement tells the computer to exit the


switch statement switch (expression){
case value1:
expression
equals
y
Do value1 thing break
// Do value1 thing value1?

 For example: break;


n
case value2:
switch (expression) { // Do value2 thing
case value1: break; expression y
equals Do value2 thing
statement1; ... value2?
break

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

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
95 Programming(CoSc3053) lecture slides
96

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."); }

 if-else chains can be sometimes be rewritten as a “switch”


statement.
 switches are usually simpler and faster

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
97 Programming(CoSc3053) lecture slides
98

97 98

Repetition statement while Loop


 Repetition statements are known as loops while (expression){
statement;
 A loop allows you to execute a statement or
}
block of statements repeatedly.

 This while loop executes as long as the given logical


 Three types of loops in Java: expression between parentheses is true.
1. while loops  When expression is false, execution continues with the
statement following the loop block.
2. for loops
3. do-while loops
 The expression is tested at the beginning of the loop, so if it
is initially false, the loop will not be executed at all.

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
99 Programming(CoSc3053) lecture slides
100

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.

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55 3. The third part of the control information, the


increment_expr, is usually used to increment the loop
counter. This is executed at the end of each loop iteration.
AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java
Programming(CoSc3053) lecture slides
101 Programming(CoSc3053) lecture slides
102

101 102

For example: Example :


int sum = 0;
for(int div = 0; div < 1000; div++){
if(div % 2 == 0) {
for (int i = 1; i <= 10; i++) {
System.out.println("even: " + div);
sum += i; } else {
} System.out.println("odd: " + div);
}
}

 What is the value of sum?  What will this for loop do?

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55 prints out each integer from 0 to 999,


correctly labeling them even or odd

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
103 Programming(CoSc3053) lecture slides
104

103 104
for loop… loop statements…
 If there is more than one variable to set up or The for loop

increment they are separated by a comma. Initialize count


The while loop

for(i=0, j=0; i*j < 100; i++, j+=2) {


System.out.println(i * j); n
} Test condition n Test condition
is true? is true?

 You do not have to fill all three control expressions y y

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

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
105 Programming(CoSc3053) lecture slides
106

105 106

The continue Statement The continue Statement…


 The continue statement causes the program  Another continue example:
to jump to the next iteration of the loop.
int sum = 0;
for(int i = 1; i <= 10; i++){
/** if(i % 3 == 0) {
* prints out "5689" continue;
}
*/ sum += i;
for(int m = 5; m < 10; m++) { }
if(m == 7) {
continue;
 What is the value of sum?
}
System.out.print(m);
}
1 + 2 + 4 + 5 + 7 + 8 + 10 = 37

AU/Computer Sc. Dept/Java AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
107 Programming(CoSc3053) lecture slides
108

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.

AU/Computer Sc. Dept/Java


Programming(CoSc3053) lecture slides
111
49

111 112

You might also like