Chapter 01 (1)
Chapter 01 (1)
Chapter 01 (1)
Chapter 01
Overview java
programming
1
Objectives
After studying this chapter, students should be able to:
Learn about Introduction to java
Learn about overview of Data Type and variables
Learn about overview of control statement
Learn about overview of Method and arrays
Learn about overview of exception handling
2
Introduction to java
The Genesis of Java
● During the late 1970s and early 1980s, C became the dominant computer programming
language.
Need for C++:
● Complexity is the big problem in C programming
● Once a program exceeds somewhere between 25,000 and 100,000 lines of code, it becomes
so complex that it is difficult to understanding as a totality.
● C++ was invented by Bjarne Stroustrup in 1979, and it is extends of C by adding object-
oriented features.
● World Wide Web and Internet are created one more revolution in the programming: is given
the stage for the Java.
The Creation of Java
● Java was developed by James Gosling and his team at Sun
Microsystems in the early 1990’s.
3
Cont.…
● The project initially called “Oak”, was focused on
creating a new programming language that could be used
to develop software for consumer electronics devices to
communicate with each other.
● In 1995, Oak was renamed as “Java”, because it was already a trademark by Oak
technologies.
● Gosling and his team build on the syntax of an existing language called C++, but
they also introduce new concepts such as “Garbage Collection,” which allowed
memory to be automatically managed by the program.
4
Cont..
Java Characteristics
● Java is simple; its syntax is based on C++ (so easier for programmers to learn
it after C++).
● It is strongly typed; because every variable must be declared with a data type.
● Memory Managmenet; java has automatic garbage collection system, that
helps developers to avoid memory leaks and manage memory effectively.
● Object-oriented; Java is completely object oriented, which means everything
in java is an object.
● Java is the platform-independent language, which means the same code can
run on different platforms.
● Java is multi-threaded; which means that it can execute multiple threads of
code simultaneously.
5
Cont..
● Network-Savvy: java has an extensive library of routines for coping with TCP/IP
protocols like HTTP and FTP.
● Secure & Robust: Java is intended for writing programs that are reliable and secure in a
variety of ways.
● Interpreted: Java programs are compiled to generate the byte code(.class file). This byte
code can be interpreted by the interpreter contained in JVM.
● Architecture neutral; Java byte code is not machine dependent, it can run on any
machine with any processor and with any OS.
● High Performance: Along with interpreter there will be JIT (Just In Time) compiler which
enhances the speed of execution.
● Robust (Strong/ Powerful): Java programs will not crash because of its exception handling
and its memory management features.
● Dynamic: We can develop programs in Java which dynamically change on Internet (e.g.:
Applets).
6
Data types and Variables in Java
A variable is an identifier that denotes a storage location used to store a data
value.
Unlike constants, that remain unchanged during the execution of a program, a
variable may take different values at different times during the execution of
the program.
It is the basic unit of storage in a Java program.
It is good practice to select variable names that give a good indication of the
sort of data they hold:
For example, if you want to record the size of a hat, hatSize is a good
7
Cont..
1. They should not begin with a digit.
2. Keywords should not be used as a variable name.
3. White spaces are not allowed.
4. Uppercase and lowercase are distinct. i.e. A rose is not a Rose is not a ROSE.
5. Variable names can be of any length.
It is defined by the combination of a data type, an identifier, and an optional
initializer.
Declaring Variable
● In Java, all variables must be declared before they can be used.
● The basic form of a variable declaration is shown here:
9
Data Types
Every variable in Java has a data type.
Data types specify the size and type of values that can be stored.
Java is language is rich in the data types.
Java data types are of two type:
Primitive Data Types (also called intrinsic or built-in data types)
Non-Primitive data Types (also known as Derived or reference types)
10
Scope of Variables
1. Instance Variables: are declared in a class, but outside a method,
constructor or any block.
• are created when an object is created with the use of the key word 'new' and destroyed
when the object is destroyed.
• They take different values for each object
2. Class Variables: are also known as static variables, are declared with the static
keyword in a class, but outside a method, constructor or a block.
• Are global to a class and belong to the entire set of objects that class creates.
• Only one memory location is created for each class variable.
12
Selection Statements
These statements allow us to control the flow of program execution based on
condition.
Java supports 2 selection statements:
if statements
switch statements
If statement:
It performs a task depending on whether a condition is true or false.
expression.
The if statement may be implemented in different forms depending on the complexity
of conditions to be tested:
Test False
expression
?
True 13
1. Simple if Statement
An if statement consists of a Boolean expression followed by one or more
statements.
The syntax of an if statement is:
if (expression)
{ statement-block;}
rest_of_program;
• If expression is true, statement-block is executed and then
rest_of_program.
• If expression is false, statement-block will be skipped & the
execution will jump to the rest_of_program
14
2. if … else Statement
The syntax of an if…else statement is:
if (expression)
{ True-block statement(s);}
else
{False-block statement(s);}
rest_of_program;
If expression is true, True-block statement is executed and followed by
rest_of_program block.
If expression is false, False-block Statement is executed followed by
rest_of_program block.
15
3. if … else if (else if Ladder) Statement
Is used when multiple decisions are involved.
if (expression 1)
A multiple decision is a chain of ifs in which the {
statement associated with each else is an if. statement(s)-1;
The conditions are evaluated from the top(of the }
else if (expression 2)
ladder), downwards.
{
As soon as the true condition is found, the statement statement(s)-2;
associated with it is executed and the control will }
skip the rest of the ladder. ...
When all the conditions become false, then the final else if (expression n)
{
else containing the default statement will be
statement(s)-n;
executed.
}
The syntax of an if …. else if statement is: else
default-statement;
rest_of_program;
16
4. Nested if … else Statement
if…else statements can be put inside other if…else if (expression 1)
{
statements. such statements are called nested if … else statement(s)-1;
if (expression 1.1)
statements. {
True-block Statement 1.1
Is used whenever we need to make decisions after }
else
checking a given decision. {
False-block Statement 1.1
The syntax of a nested if…else statement is shown in the }
next slide. }
True-block statement 1.1 is executed if both expression 1 else if (expression 2)
{
and expression 1.1 are true. But if expression 1 is true statement(s)-2;
}
and if expression 1.1 is false, then it is False-block ...
else if (expression n)
statement 1.1 which is going to be executed. {
statement(s)-n;
}
else
default-statement;
rest_of_program;
17
Switch statement
We can design a program with multiple alternatives using switch (expression)
if statements to control the selection. {
case value-1:
But the complexity of such programs increases statement-
block 1;
dramatically when the number alternatives increases. break;
case value-2:
Java has a multi-way decision statement called switch statement-
statement. block 2;
break;
The switch statement tastes the value of a given ......
......
variable(expression) against a list of case values and default:
when a match is found, a block of statements associated
default_statement;
with that case is executed. break;
}
rest_of_program
18
Cont..
There is no need to put braces around the statement blocks of a switch statement but it
is important to note that case labels end with a colon (:).
When the switch is executed, the value of the expression is successfully compared
against the values value-1, value-2, ….
If a case is found whose value matches with the value of the expression, then the block
of the statement(s) that follows the case are executed; otherwise the default-statement
will be executed.
The break statement at the end of each block signals the end of a particular case and
causes an exit from the switch statement.
19
Iterative/Loop Statements
The process of repeatedly executing a block of statements is known as looping.
A loop allows you to execute a statement or block of statements repeatedly until a
termination condition is met.
The statements in the block may be executed any number of times, from zero to
infinite number.
If a loop continues forever, it is called an infinite loop.
A program loop consists of two statements:
Body of the loop.
Control statements.
A looping process, in general, would include the four steps:
1. Setting and initialization of a counter .
2. Execution of the statements in the loop.
3. Test for a specified condition for execution of the loop.
4. Increment/Decrement the counter.
20
1. The while loop
Is the simplest of all the looping structures in
Java. initialization;
The while loop is an entry-controlled loop while (expression)
{
statement. Body of the loop;
The while loop executes as long as the given }
logical expression between parentheses is true.
When expression is false, execution continues Example:
int sum=0,n=1;
with the statement immediately after the body of while(n<=100)
the loop block. {
The expression is tested at the beginning of the sum+=n;
n++;
loop, so if it is initially false, the loop will not }
be executed at all. System.out.println(“Sum=“+sum;
)
The basic format of the while statement is:
21
The do…while loop
Unlike the while statement, the do… while loop initialization;
executes the body of the loop before the test is do
performed. {
On reaching the do statement, the program proceeds to Body of the loop;
evaluate the body of loop first. }
At the end of the loop, the test condition in the while while (expression);
statement is evaluated. If it is true, the program Example:
continues to evaluate the body of the loop once int sum=0,n=1;
do
again. {
When the condition becomes false, the loop will be sum+=n;
n++;
terminated and the control goes to the statement that } while(n<=100);
appears immediately after the while statement.
System.out.println(“Sum=“+s
The while loop is an exit-controlled loop statement. um);
22
3. The for loop
Is another entry-controlled loop that provides a more concise loop controlled structure.
Syntax for the for loop is:
for(initialization; test condition; increment)
{
Body of the loop;
}
We use the for loop if we know in advance for how many times the body of the loop is
going to be executed.
But use do…. while loop if you know the body of the loop is going to be executed at
least once.
The execution of the for loop statement is as follows:
1. Initialization of the control variable(s) is done first, using assignment statement.
2. The value of the control variable is tested using the test condition. The test condition is a relation
operation that determines when the loop will exit.
23
Cont.
If the condition is true, the body of the loop is executed; otherwise the loop is
terminated and the execution continues with the statement that immediately follows the
loop.
3. When the body of the loop is executed, the control is transferred back to the for statement after
evaluating the last statement in the loop.
Now the new value of the control variable is again tested to see whether it satisfies the
loop condition; if it does, the body of the loop is again executed .
int sum=0;
for(n=1; n<=100; n++)
{
sum=sum+n;
}
System.out.println(“Sum is:”+sum);
24
Reading Assignment
1. For each loop in java
2. Nested loop in java
3. Jumps in loops
25
Methods and Arrays
A. Methods
● Syntax:
● modifier returnType methodName(parameters){
// method body;
}
● In Java, it is possible to define two or more methods within the same class that share the same name, as
long as their parameter declarations are different.
● When this is the case, the methods are said to be overloaded, and the process is referred to as method
overloading.
● Method overloading is one of the ways that Java implements polymorphism.
● Example: void test()
void test(int a)
void test(int a, int b)
double test(double a)
26
Arrays
An array is a group of contiguous or related data items that share a common name.
is a container object that holds a fixed number of values of a single type.
An array can hold only one type of data!
Example:
int[] can hold only integers
char[] can hold only characters
A particular values in an array is indicated by writing a number called index number or
27
One-Dimensional Arrays
A list of items can be given one variable name using only one subscript and such a variable is called a
single-subscripted variable or a one-dimensional array.
Creating an Array
Like any other variables, arrays must be declared and created in the computer memory before they are
used.
Array creation involves three steps:
1. Declare an array Variable
2. Create Memory Locations
3. Put values into the memory locations.
Declaration of Arrays
Arrays in java can be declared in two ways:
i. type arrayname [ ];
ii. type[ ]arrayname;
Example: when creating an array, each element of the array receives a
int number[]; default value zero (for numeric types) ,false for boolean and
float slaray[];
float[] marks; null for references (any non primitive types).
28
Creation of Arrays
After declaring an array, we need to create it in the memory.
Because an array is an object, you create it by using the new keyword as follows:
arrayname =new type[ size];
Example:
number=new int(5);
marks= new float(7);
It is also possible to combine the above to steps , declaration and creation, into on statement as follows:
type arrayname =new type[ size];
Example: int num[ ] = new int[10];
Initialization of Arrays
Each element of an array needs to be assigned a value; this process is known as initialization.
Example:
number [0]=23;
number[2]=40;
29
Cont..
It is also possible to assign an array object to another array object.
Example:
int array1[]= {35,40,23,67,49};
int array2[];
array2= array1;
Array Length
In Java, all arrays store the allocated size in a variable named length.
We can access the length of the array array1using array1.length. Example:
int size = array1.length;
Example
30
Two-Dimensional Arrays
A 2-dimensional array can be thought of as a grid (or matrix) of values.
Each element of the 2-D array is accessed by providing two indexes: a row index and a column index
A 2-D array is actually just an array of arrays.
A multidimensional array with the same number of columns in every row can be created with an array
creation expression:
Example:
int myarray[][]= int [3][4];
Initialize
For example,
int myarray[2][3]= {0,0,0,1,1,1};
or
int myarray[][]= {{0,0,0},{1,1,1}};
31
Variable Size Arrays
Java treats multidimensional array as “array of arrays”.
It is possible to declare a two-dimensional array as follows:
int x[][]= new int[3][];
x[0] = new int[2];
x[1] = new int[4];
x[2] = new int[3];
This statement creates a two-dimensional array having different length for each row as
shown below:
32
Java Exception Handling
What is “Exception”?
● An exception is an unexpected event that occurs during program execution.
● It affects the flow of the program instructions which can cause the program to
terminate abnormally.
An abnormal event in a program is called an Exception.
Exception may occur at compile time or at runtime.
An exception can occur for many reasons. Some of them are:
Invalid user input Opening an unavailable file
Device failure Code errors etc.
Loss of network connection
33
Exception Hierarchy
All exceptions are sub-classes of the built-in class Throwable.
Throwable contains two immediate sub-classes:
1. Exception – exceptional conditions that programs should catch. The class includes:
a) RuntimeException – defined automatically for user programs to include: division by zero, invalid array
indexing, etc.
b) user-defined exception classes
2. Error – exceptions used by Java to indicate errors with the runtime environment; user programs are not
supposed to catch them
● Errors in java are exceptional conditions that cannot be handled by the java program.
● It represent irrecoverable conditions such as hardware failures, out of memory error, stack overflow
errors, infinite recursion, etc.
● These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer.
● When an error occurs, the program terminates abruptly, and the application stops working.
34
Hierarchy of Exception Classes
35
Checked Exceptions
Inherit from class Exception but not from RuntimeException
Compiler enforces catch-or-declare requirement
Compiler checks each method call and method declaration
determines whether method throws checked exceptions.
If so, the compiler ensures checked exception caught or declared in throws clause.
If not caught or declared, compiler error occurs.
Some Common Checked Exceptions
1. NoSuchMethodException
2. NoSuchFieldException
3. InterruptedException
4. InstantiationException
5. IllegalAccessException
6. CloneNotSupportedException
7. ClassNotFoundException
36
Unchecked Exceptions
Inherit from class RuntimeException or class Error
Compiler does not check code to see if exception caught or declared
If an unchecked exception occurs and not caught
Program terminates or runs with unexpected results
Can typically be prevented by proper coding
37
Exception Handling
Code that could generate errors put in try blocks
Code for error handling enclosed in a catch clause
The finally clause always executes
Five constructs are used in exception handling:
1. try – a block surrounding program statements to monitor for exceptions
2. catch – together with try, catches specific kinds of exceptions and handles them in some way
3. finally – specifies any code that absolutely must be executed whether or not an exception
occurs
4. throw – used to throw a specific exception from the program
5. throws – specifies which exceptions a given method can throw
38
Exception Handling Blocks
General form:
try {
… // generates an
exception where:
}
1. try { … } is the block of code to
catch(Exception1 e1){
…//handles the exception monitor for exceptions
} 2. catch(Exception ex) { … } is exception
catch(Exception2 e2){
… handler for the exception Exception
} 3. finally { … } is the block of code to
finally {
execute before the try block ends
…
}
39
Example
class DivByZero
{
public static void main(String args[])
{
try {
int a = 10, b = 0, c;
c = a / b;
System.out.println("Division = " +
c);
}catch (ArithmeticException e) {
System.out.println("Error:" +
e.getMessage());
}
}
} Output:
} Error: / by zero
Quit
40
throw and throws keyword
a) throw keyword
● Used to throw a single exception explicitly. Only object of Throwable class or its sub
classes can be thrown.
● When we throw an exception, the flow of the program moves from the try block to
the catch block.
● Program execution stops on encountering throw statement, and the closest catch
statement is checked for matching type of exception.
● Syntax: throw ThrowableInstance
● We allows to use new operator to create an instance of class Throwable
new ArithmeticException(“divideByZero");
● This constructs an instance of ArithmeticException with name divideByZero.
● In the following example, the divideByZero() method throw an instance of
ArithmeticException, which is successfully handled using the catch statement and
thus, the program prints the output "Trying to divide by 0".
41
Cont.
Example: Exception handling using Java
throw
class Main {
public static void divideByZero() {
try {
throw new
ArithmeticException("divideByZero");
} catch(ArithmeticException e) {
System.out.println("Trying to divide
by 0”);
}
}
public static void main(String[] args) {
divideByZero();
} }
OUTPUT
Trying to divide by 0
42
throws keyword
● Used to declare the list of exception that a // declaring the type of exception
method may throw during execution of public static void findFile()
program. throws IOException {
● Any method that is capable of causing // code that may generate
IOException
exceptions must list all the exceptions File newFile = new
possible during its execution, so that anyone File("test.txt");
calling that method gets a prior knowledge FileInputStream stream = new
about which exceptions are to be handled. FileInputStream(newFile);
}
● Syntax: public static void main(String[]
args) {
try{
type method_name(parameters) throws exception_list{ findFile();
// definition of method }catch (IOException e) {
System.out.println(e);
} } }
OUTPUT
java.io.FileNotFoundException: test.txt
(The system cannot find the file
specified) 43
Thank you:
Question ??
Reading Assignment
Java Applet ?