Overview of Java
Chapter One
J ava Programming
By Temesgen T.(MSc)
2 Course
outline
Chapter one: Overview of Java
Programming
Data types and variables
Arrays
Decision and Repetition statement
Exception handling overview and syntax
3 Chapter I
Overview of Java Programming
Java is a general-purpose, class-based, object-oriented programming
language designed for having lesser implementation dependencies.
It is a computing platform for application development.
Java is fast, secure, and reliable, therefore, It is widely used for developing
Java applications in laptops, data centers, game consoles, scientific
supercomputers, cell phones, etc.
History of Java Programming Language
4
Here are important landmarks from the history of the Java language:
The Java language was initially called OAK.
Originally, it was developed for handling portable devices and set-top boxes. Oak was a
massive failure.
In 1995, Sun changed the name to “Java” and modified the language to take
advantage of the burgeoning www (World Wide Web) development business.
Later, in 2009, Oracle Corporation acquired Sun Microsystems and took ownership
of three key Sun software assets: Java, MySQL, and Solaris.
James Gosling developed the Java platform at Sun Microsystems, and the Oracle
Corporation later acquired it.
Java Programming
5
The Java Programming Language is a high-level language. Its Syntax is similar to C
and C++, but it removes many of the complex , confusing features of C and C++.
The Java Programming Language includes the feature of automatic storage management
by
using a garbage collector.
The Java programming language source code is compiled into the bytecode instruction
set which can be run inside the Java Virtual Machine (JVM) process.
Java Application
In the Java Language, all of the source code is written in plain text files with the
.java extension
Java Programming …
6
The java source code files are then compiled into .class extension files by the
command javac
A .class file contains bytecode which is a platform independent instruction set
The java command then runs the application
Java application translation from source code to byte code procedure.
7 Java Programming …
Oracle has two products that implement Java Platform Standard Edition, Java SE
development Kit and Java SE Runtime Environment
Java Programming …
8 Java Application Example
Step 1: create a sample source code file [Link]
Step 2. Compile the Source code to generate the Class file
javac [Link]
Step 3. Run the Application
java HelloWorld
Step 4. Print out the result
Hello World!
9
Java Programming …
The Java Development Kit (JDK) is a software development environment used
for developing Java applications and applets.
It includes the Java Runtime Environment (JRE), an interpreter/loader (java), a
compiler (javac), an archiver (jar), a documentation generator (javadoc) and other tools
needed in Java development.
The Java Virtual Machine gives runtime support to the application and can make the
application independent from different hardware systems.
10 Data types and variables
Java has primitive and non-primitive data types. Primitive data types are a special group
of data types that do not use the keyword new when initialized.
There are eight primitive data types that are used to store data during a program's
operation.
11 Data types and variables…
Java creates them as automatic variables that are not references, which are stored in
memory with the name of the variable.
To display Variables
The println() method is often used to display variables. To combine both text and a
variable, use the + character:
Data Type Size Example Data Data Description
boolean 1 bit true, false true, false
1 byte
byte 12, 128 Stores integers from -128 to 127
(8 bits)
12 Data types and variables…
Stores a 16-bit Unicode
char 2 bytes 'A', '5', '#'
character
short 2 bytes 6, -14, 2345 Stores integers from -32,768 to 32,767.
4 Stores integers from:
int 6, -14, 2345
bytes -2,147,483,648 to 2,147,483,647
8 Stores integers from:-9,223,372,036,854,775,808
long 3459111, 2
bytes to 9,223,372,036,854,775,807
4 Stores a positive or negative decimal
float 3.145, .077
bytes number from: 1.4023x10-45 to
3.4028x10+38
8 Stores a positive or negative decimal
double .0000456, 3.7
bytes number from: 4.9406x10-324 to
1.7977x10+308
13 Data types and variables…
Variables are containers for storing data values. Variable is a name of memory location.
In Java, there are different types of variables, for example: String- stores text, such
as "Hello". String values are surrounded by double quotes
int- stores integers (whole numbers), without decimals, such as 123 or -123 3. float-
stores floating point numbers, with decimals, such as 19.99
Declaring Variables and Using Literals
•The keyword new is not used when initializing a variable primitive type.
• Instead, a literal value should be assigned to each variable upon initialization.
•A literal can be any number, text, or other information that represents a value.
• Examples of declaring a variable and assigning it a literal value:
14 Data types and variables…
There are three types of variables in Java:
i. local variable
ii. instance variable
iii. static variable
15 Data types and variables…
i. local variable: is a variable declared inside the body of the method. You can use this
variable only within that method and the other methods in the class aren't even
aware that the variable exists.
A local variable cannot be defined with "static" keyword.
ii. instance variable: A variable declared inside the class but outside the body of
the method, is called an instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared
among instances.
iii. Static variable: A variable that is declared as static is called a static variable. It
cannot be local. You can create a single copy of the static variable and share it among all
the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the
memory.
16 Data types and variables…
17 Array
s data types: The non-primitive data types include Arrays, Classes, and
Non-primitive
Interfaces.
An array is a data type that stores a collection of items of the same data type stored in
a container object.
These items are sometimes referred to as the elements of the array.
All elements must be of the same type BUT there is no restriction on which type this
is.
Length of the array is set when the array is declared, so the size is fixed.
arrays can be used to hold a collection of int values; or a collection of char values;
BUT they cannot be used to hold a mixture of int and char values.
Declaring arrays
18
Need to state
the size of the array ;
the type of each individual array element .
The array type and size are then put together with a special new
operator.
For example
Declaring arrays
19
Example 2
The effect on computer memory of declaring an array
Naming the array elements
20
The first element in the temperature array is temperature[0]
The second element is temperature[1] and so on:
Initializing an array
21
This is the only instance in which all the elements of an array can be assigned
explicitly by listing out the elements in a single assignment statement.
Accessing array elements
Array can be used like any other variable of the given type in Java.
The assignment operator can be used to enter a value.
You must specify which element to place the value in.
For example: Allowing the user of the program to enter the value of the first temperature:
Assume that i is some integer variable:
2D Array
• A 2D array, also known as a two-dimensional array, is a data
structure that stores elements in a grid-like format with rows and
columns.
• It can be visualized as a table with rows and columns, where each
cell holds a value or an element.
• To create a 2D array, you define the number of rows and columns
it should have. The size of a 2D array is usually denoted as rows x
columns.
• For example, a 2D array with 3 rows and 4 columns would have a
size of 3x4.
Example
// Creating a 2D array
int[][] array2D = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12} };
// Accessing elements in the 2D array
• [Link](array2D[0][0]); // Output: 1 (accessing the first element in the
first row)
• [Link](array2D[1][2]); // Output: 7 (accessing the third element in the
second row)
• [Link](array2D[2][3]); // Output: 12 (accessing the fourth element in
the third row)
// Creating a 2D array
int[][] array2D = new int[3][4];
// Populating the array with values
int value = 1;
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < array2D[i].length; j++) {
array2D[i][j] = value;
value++;
}}
// Accessing elements in the 2D array
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < array2D[i].length; j++) {
[Link](array2D[i][j] + " ");
}
[Link]();
}
Operators in Java
23
Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups:
Arithmetic Operators Assignment Operators
Relational Operators Bitwise Operators
Other Operators
Logical Operators
Arithmetic operators: are used in mathematical expressions in the same way that they
are used in algebra. These are addition, Subtraction, multiplication, division, modulus,
increment and decrement operators.
Operators in Java
24 The following program is a simple example which demonstrates the arithmetic operators.
Operators in Java
25
output
Operators in Java
26 Relational operators
Java has six relational operators used to test primitive or literal numerical values.
Relational operators are used to evaluate if-else and loop conditions
Logic Operators
Java has three logic operators used to combine
Boolean expressions into complex tests.
Operators in Java
27
Relational operator example: output
Decision and Repetition statement
28
Control structures alter the flow of the program, the sequence of statements that are executed
in a program.
They act as "direction signals" to control the path a program takes.
Two types of control structures in Java:
decision statements
Repeating / iterating statements
Decision statements have one or more conditions to be evaluated or tested by the program,
along with a statement or statements that are to be executed if the condition is determined
to be true, and optionally, other statements to be executed if the condition is determined to
be false.
Types of decisions statements in Java:
if statements, if else statement, if else if, else statement
switch statements
Decision and Repetition statement
29
If Statement
if (expression) {
statement;
}
rest_of_program;
expression must evaluate to a boolean value, either true or false
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
Decision and Repetition statement
30 If-Else Statement If-Else Statement Example
if (expression) {
statement1;
}
else{
statement2;
}
next_statement;
Again, expression must produce a boolean value
If expression is true, statement1 is executed and then next_statement is
executed.
If expression is false, statement2 is executed and then next_statement is
Decision and Repetition statement
31 Chained If-Else Statement syntax Chained If-Else Statement Example
if-else chains can be sometimes be rewritten as a “switch” statement. switches are
usually simpler and faster
Decision and Repetition statement
32 switch Statement switch Statement Example
The switch statement enables you to test
several cases generated by a given expression.
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, Character, Byte,
Short, Integer, String, enum but not float, or
double or long
33 Decision and Repetition/Itration statement
Iteration is the form of program control that allows us to repeat a section of code.
This form of control is often also referred to as repetition.
The programming structure that is used to control this repetition is often called a loop.
There are three types of loops in Java:
for loop;
while loop;
do…while loop.
The ‘for’ loop
If we wish to repeat a section of code a fixed number of times we would use Java's for
loop.
The for loop is usually used in conjunction with a counter to keep track of how many
times we have been through the loop so far:
The ‘for’
for (init_expr; loop_condition; increment_expr) {
34 loop statement;
}
The control of the for loop appear in parentheses and is made up of three parts:
1. The first part, the init_expression, sets the initial conditions for the loop and is
executed before the loop starts.
2. Loop executes so long as the loop_condition is true and exits otherwise.
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.
Example
output
Decision and Repetition statement
35
while loop: while loop statement in Java programming language repeatedly executes a
target statement as long as a given condition is true.
Here, statement(s) may be a single statement or a block of
while Statement syntax
statements.
The condition may be any expression, and true is any non
zero value. When executing, if the boolean_expression result
is true, then the actions inside the loop will be executed.
This will continue as long as the expression result is true.
When the condition becomes false, program control passes
to the line immediately following the loop
Decision and Repetition statement
36 while Statement Example
output
Decision and Repetition statement
37
do...while: A do...while loop is similar to a while loop, except that a do...while loop
is guaranteed to execute at least one time.
Notice that the Boolean expression appears at the end of
do…while Statement syntax
the loop, so the statements in the loop execute once
before the Boolean is tested.
If the Boolean expression is true, the control jumps back
up to do statement, and the statements in the loop execute
again.
This process repeats until the Boolean expression is false.
38 Decision and Repetition statement
do…while Statement Example
output
39 Exception handling overview
What is an Exception? is a problem that arises during the execution of a program that
disrupts the program flow and may cause a program to fail or terminates abnormally, which
is not recommended, therefore, these exceptions are to be handled
Some examples are:.
Accessing an out-of-bounds array element
Performing illegal arithmetic
Illegal arguments to methods
Hardware failures
Writing to a read-only file
40
Exception Class Hierarchy
■ All exceptions are instances of classes that are subclasses of Exception
41 Exception terminologies
When an exception happens we say it was thrown or raised
When an exception is dealt with, we say the exception was handled or caught
Unchecked Exceptions: is an exception that occurs at the time of execution. These are also called
as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of
an API. Runtime exceptions are numerous and ignored at the time of compilation.
Checked Exceptions: an exception that occurs at the compile time, these are also called as compile
time exceptions. These exceptions cannot simply be ignored at the time of compilation, the
programmer should take care of (handle) these exceptions.
Example reading data from a non existing file.
42
Exception handling overview
For example, if you have declared an array of size 2 in your program, and trying to call the
3rd element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
public class ExceptionExample {
public static void main(String
args[]) {
String[] greek =
{"Alpha", "Beta"};
[Link](greek[2]);
}
}
Exception in thread "main"
[Link]: 2
at [Link]([Link])
Exception handling overview
43
Exception Message Details
Exception message format:
[exception class]: [additional description of
exception] at [class].[method]([file]:[line number])
Example:
[Link]: 2
at
[Link]([Link])
What exception class? ArrayIndexOutOfBoundsException
Which array index is out of bounds? 2
What method throws the exception? main
What file contains the method? [Link]
What line of the file throws the exception? 4
44 Exception Handling
Use a try-catch block to handle exceptions that are thrown
try {
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}
45 Example
The following is an array declared with 2 elements. Then the code tries to access the 3 rd element of the array which
throws an exception.