0% found this document useful (0 votes)
11 views

Chapter I - Overview of Java Programming

Uploaded by

noah05609
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Chapter I - Overview of Java Programming

Uploaded by

noah05609
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 95

Advanced Programming

Chapter 1 – Overview of
Java Programming
Data types and
variables

– A variable provides us with named storage that our programs


can manipulate.
– Each variable in Java has a specific type, which determines
• the size and layout of the variable's memory;
• the range of values that can be stored within that memory; and
• the set of operations that can be applied to the variable.
– You must declare all variables before they can be used.
– The basic form of a variable declaration is
data_type variable [ = value][, variable [= value] ...] ;
– data type is one of Java's datatypes and variable is the name of
the variable.
• Following are valid examples of variable declaration and
initialization in Java:
– int a, b, c; // Declares three ints, a, b, and c.
– int a = 10, b = 10; // Example of initialization
– byte B = 22; // initializes a byte type variable B.
– double pi = 3.14159; // declares and assigns a value of PI.
– char a = 'a'; // the char variable a is initialized with
value 'a’
– There are three kinds of variables in Java:
1.Local variables
2.Instance variables
Local Variables
– Local variables are declared in methods, constructors, or
blocks.
– Local variables are created when the method, constructor
or block is entered and the variable will be destroyed
once it exits the method, constructor or block.
– Access modifiers cannot be used for local variables.
– Local variables are visible only within the declared scope
– There is no default value for local variables so local
variables should be declared and an initial value should be
assigned before the first use.
• When the program executed local variable
batchYear and year produce output as
follows
Instance variables:
– Instance variables are declared in a class, but outside a method,
constructor or any block.
– Instance variables are created when an object is created
with the use of the keyword 'new' and destroyed when the object
is destroyed.
– Instance variables hold values that must be referenced by
more than one method, constructor or block, or essential parts of
an object's state that must be present throughout the class.
– Instance variables can be declared in class level before or
after use.
– Access modifiers can be given for instance variables.
Conn… Instance Variable
– The instance variables are visible for all methods, constructors
and block in the class.
– Instance variables have default values. For numbers the default
value is 0, for Booleans it is false and for object references it is
null.
– Values can be assigned during the declaration or within the
constructor.
– Instance variables can be accessed directly by calling the variable
name inside the class.
– However within static methods and different class (when
instance variables are given accessibility) should be called using
the fully qualified name.
– ObjectReference.VariableName.
Class/static variables:
– Class variables also known as static variables are
declared with the static keyword in a class, but outside a
method, constructor or a block.
– There would only be one copy of each class variable
per class, regardless of how many objects are created
from it.
– Static variables are rarely used other than being declared
as constants. Constants are variables that are declared as
public/private, final and static.
– Constant variables never change from their initial value.
– Static variables are stored in static memory.
– Static variables are created when the program starts and
destroyed when the program stops.
– Visibility is similar to instance variables.
– Default values are same as instance variables.
– Static variables can be accessed by calling with the class
name. ClassName.VariableName
– When declaring class variables as public static final, then
variables names (constants) are all in upper case.
– Instance variable: It will be different from object to object and
object's property while static variable is Class's property.
• If the static variables are not public and final the naming
syntax is the same as instance and local variables.
• Use instance variables when : Every variable has a different
value for different object. E.g. name of student, roll number
etc..
• use static variables when : The value of the variable is
independent of the objects (not unique for each object). E.g.
number of students.
• Example:
Java identifiers
– Identifiers are the names of variables, methods, classes, packages and
interfaces.
– Unlike literals they are not the things themselves, just ways of referring to
them.
– In the HelloWorld program, HelloWorld , String , args , main and println
are identifiers.
– Valid Java identifiers:
• Each identifier must have at least one character.
• The first character must be picked from: alpha, underscore, or dollar sign.
The first character can not be a digit.
• The rest of the characters (besides the first) can be from: alpha, digit,
underscore, or dollar sign.
Datatypes
– Variables are nothing but reserved memory locations to store
values. This means that when you create a variable you reserve
some space in memory.
– Based on the data type of a variable, the operating system
allocates memory and decides what can be stored in the reserved
memory.
– There are two data types available in Java:
• Primitive Data Types
• Reference/Object Data Types
– Primitive data types are predefined by the language and
named by a keyword.
– There are eight primitive data types supported by Java.
Primitive Data Types
Data type Length Min value Max value Default
byte 8 bit signed -127*(-2^7) 127(2^7-1) 0
short 16 bit signed -32,768 (-2^15) 32,767(2^15 -1) 0

int 16 bit signed - 2,147,483,648.(-2^31) 2147483647(2^31 -1) 0


-9,223,372,036,854,775,808.(- 9,223,372,036,854,775,
long 64 bit signed 2^63) 807 (2^63 -1) 0L
float 32 bit floating point 0.0f
double 64 bit floating point 0.0d
boolean 1 bit information FALSE

'\uffff' (or 65,535


char 16 bit Unicode character '\u0000' (or 0). inclusive)
Reference Data Types
– Reference variables are created using defined constructors of
the classes. They are used to access objects.
– These variables are declared to be of a specific type that cannot be
changed.
– Default value of any reference variable is null.
– A reference variable can be used to refer to any object of the
declared type or any compatible type.
Example: Animal animal = new Animal( );
Decision and Repetition
Statements

OOP Prepared By: Daniel Tesfy 21


Control Flow Statement

– By default, all statements in a Java program are


executed in the order they appear in the program.
– Sometimes you may want to execute a set of statements
repeatedly for a number of times or as long as a
particular condition is true.
– All of these are possible in Java using control flow
statements. If block, while loop, and for loop statements
are examples of control flow statements.
OOP Prepared By: Daniel Tesfy 22
Decision Making Statements

• There are two types of decision-making statements in


Java. They are:
– If statements
– Switch statements
• The IF Statement
– An if statement consists of a Boolean expression
followed by one or more statements.
OOP Prepared By: Daniel Tesfy 23
Syntax:
if(Boolean_expression)
{
// Statements will
execute if the
Boolean expression is
true
}
OOP Prepared By: Daniel Tesfy 24
If statement example

OOP Prepared By: Daniel Tesfy 25


The if----else Statement

– An if statement can be followed by an optional


else statement , which executes when the
Boolean expression is false.
– Syntax

OOP Prepared By: Daniel Tesfy 26


OOP Prepared By: Daniel Tesfy 27
If----else example

OOP Prepared By: Daniel Tesfy 28


The if...else if...else Statement

• An if statement can be followed by an optional else if...else statement,


which is very useful to test various conditions using single if...else if
statement.
• When using if , else if , else statements there are few points to keep in
mind.
– An if can have zero or one else's and it must come after any else if’s.
– An if can have zero to many else if's and they must come before the
else.
– Once an else if succeeds, none of the remaining else if's or else's will
be tested.
OOP Prepared By: Daniel Tesfy 29
• Syntax :

OOP Prepared By: Daniel Tesfy 30


OOP Prepared By: Daniel Tesfy 31
if ---else if----else example

OOP Prepared By: Daniel Tesfy 32


Nested if...else Statement:

– It is always legal to nest if-else statements which means


you can use one if or else if statement inside another if or
else if statement.
– Syntax

OOP Prepared By: Daniel Tesfy 33


OOP Prepared By: Daniel Tesfy 34
Nested If statement example

OOP Prepared By: Daniel Tesfy 35


The switch Statement

– A switch statement allows a variable to be tested for


equality against a list of values.
– Each value is called a case, and the variable being switched
on is checked for each case.
– Syntax:

OOP Prepared By: Daniel Tesfy 36


• The following rules apply to a switch statement:
– The variable used in a switch statement can only be a byte, short, int, or char.
– You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
– The value for a case must be the same data type as the variable in the switch
and it must be a constant or a literal.
– When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.
– When a break statement is reached, the switch terminates, and the flow of
control jumps to the next line following the switch statement.
OOP Prepared By: Daniel Tesfy 37
OOP Prepared By: Daniel Tesfy 38
Switch Statement Demo

• It takes an integer user


input
• It returns the string
equivalent of the given
numeric month

OOP Prepared By: Daniel Tesfy 39


– Not every case needs to contain a break. If no break
appears, the flow of control will fall through to
subsequent cases until a break is reached.
– A switch statement can have an optional default case,
which must appear at the end of the switch.
– The default case can be used for performing a task when
none of the cases is true.
– No break is needed in the default case
OOP Prepared By: Daniel Tesfy 40
Loop Control

– There may be a situation when we need to execute


a block of code several number of times, and is
often referred to as a loop.
– Java has very flexible three looping mechanisms.
You can use one of the following three loops:
1. while Loop
2. do...while Loop
3. for Loop
OOP Prepared By: Daniel Tesfy 41
The while Loop
– A while loop is a control structure that allows you to repeat a task a
certain number of times.
– Syntax :

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

OOP Prepared By: Daniel Tesfy 42


OOP Prepared By: Daniel Tesfy 43
– key point of the while loop is that the loop might
not ever run.
– When the expression is tested and the result is
false, the loop body will be skipped and the first
statement after the while loop will be executed.

OOP Prepared By: Daniel Tesfy 44


While loop example

OOP Prepared By: Daniel Tesfy 45


The do...while Loop
• A do...while loop is similar to a while loop, except that a
do...while loop is guaranteed to execute at least one time.
• Syntax:

• Notice that the Boolean expression appears at the end of


the loop, so the statements in the loop execute once
before the Boolean is tested.
OOP Prepared By: Daniel Tesfy 46
OOP Prepared By: Daniel Tesfy 47
• If the Boolean expression is true, the flow of control
jumps back up to do, and the statements in the loop
execute again. This process repeats until the Boolean
expression is false.

OOP Prepared By: Daniel Tesfy 48


The for Loop
– A for loop is a repetition control structure that allows you to efficiently write a
loop that needs to execute a specific number of times.
– A for loop is useful when you know how many times a task is to be repeated.
– Syntax

OOP Prepared By: Daniel Tesfy 49


OOP Prepared By: Daniel Tesfy 50
• flow of control in a for loop
 The initialization step is executed first, and only once.
 Next, the Boolean expression is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow of control
jumps to the next statement past the for loop.
 After the body of the for loop executes, the flow of control jumps back up to the
update statement.
 This statement allows you to update any loop control variables.
 The Boolean expression is now evaluated again. If it is true, the loop executes and
the process repeats itself (body of loop, then update step, then Boolean
expression). After the Boolean expression is false, the for loop terminates.
OOP Prepared By: Daniel Tesfy 51
For loop example

OOP Prepared By: Daniel Tesfy 52


The break Keyword

– The break keyword is used to stop the entire loop.


– The break keyword must be used inside any loop
or a switch statement.
– The break keyword will stop the execution of the
innermost loop and start executing the next line of
code after the block.
– Syntax:
OOP Prepared By: Daniel Tesfy 53
OOP Prepared By: Daniel Tesfy 54
Break Test

OOP Prepared By: Daniel Tesfy 55


The continue Keyword

• The continue keyword can be used in any of the loop


control structures. It causes the loop to immediately
jump to the next iteration of the loop.
 In a for loop, the continue keyword causes flow of control to immediately jump to
the update statement.
 In a while loop or do/while loop, flow of control immediately jumps to the Boolean
expression.
 Syntax
OOP Prepared By: Daniel Tesfy 56
OOP Prepared By: Daniel Tesfy 57
Continue

OOP Prepared By: Daniel Tesfy 58


Java array

OOP Prepared By: Daniel Tesfy 59


Java Array
– An array is a collection of similar type of elements that have a
contiguous memory location.
– Java array is an object which contains elements of a similar data type .
It is a data structure where we store similar elements .
– We can store only a fixed set of elements in a Java array.
– Array in java is index-based

OOP Prepared By: Daniel Tesfy 60


• Advantages
– Code Optimization: It makes the code optimized, we
can retrieve or sort the data efficiently.
– Random access: we can get any data located at an
index position.
• Disadvantage
– Size Limit: we can store a fixed size of elements in an
array. It doesn’t grow its size at runtime.
OOP Prepared By: Daniel Tesfy 61
Types of array in Java
– One Dimensional Array
– Multidimensional Array
• One Dimensional Array in Java

OOP Prepared By: Daniel Tesfy 62


Example

OOP Prepared By: Daniel Tesfy 63


Example 2

OOP Prepared By: Daniel Tesfy 64


Multidimensional Array

OOP Prepared By: Daniel Tesfy 65


Multidimensional Array

OOP Prepared By: Daniel Tesfy 66


Exception Handling
Exception Handling
• The Exception Handling in Java is one of the
powerful mechanism to handle the runtime errors so that
the normal flow of the application can be maintained.

• Hence, in this lecture we will learn about Java exceptions,


Exception Types, and the difference between checked
and unchecked exceptions.
What is Exception?
• An exception is a problem or an abnormal Condition that
arises during the execution of a program.

• When an Exception occurs the normal flow of the program is


disrupted and the program/Application terminates
abnormally, which is not recommended, therefore, these
exceptions needs to be handled.
• It is an object thrown at runtime.
Exception … Cont
• An exception can occur for many different reasons. Following are
some scenarios where an exception occurs.
– Attempting to divide by zero (arithmetic exception)

– Reading a decimal value when an integer is expected (number


format exception)
– Attempting to write to a file that does not exist (I/O exception)

– Referring to a non existent character in a string or non existent


array index (Array index out of bounds exception)
– A network connection has been lost in the middle of
communication, or JVM has run of memory, hard disk failure
The causes of exception
 User error (Invalid input): Exceptions can be triggered when
the program receives invalid or unexpected input from the user.
E.g., attempting to convert a non-numeric string to a number or
dividing by zero can result in exceptions.

 Resource unavailability: Exceptions can occur when a required


resource is not available or cannot be accessed. This could
include file I/O errors, network connectivity issues, or database
connection problems.

 Programming errors: Mistakes in the code, such as logical


Introduction cont.
• No matter how well-designed a program is, there is always the
chance that some kind of error arises during its execution.

• Raising an exception halts normal execution abruptly and


alternative statements are sought to be executed.

• A well-designed program should include code to guard against


errors and other exceptional conditions when they arise.

• In Java, the preferred way of handling such conditions is to use


Exception Handling – an approach that separates a program’s
normal code from its error-handling code.
Introduction cont.
• Valid Java programming language code must honour the Catch
or Specify Requirement.

• This means that code that might throw certain exceptions


must be enclosed by either of the following:
– A try statement that catches the exception.
try... catch
– A method that specifies that it can throw the exception.
throws or throw

• Code that fails to honour the Catch or Specify Requirement will


not compile.
Java Exception Hierarchy
• Java class library contains number of predefined exceptions

• All exception classes are subtypes of the java.lang.Exception


class.

• The Exception class is a subclass of the Throwable class.


Throwable class has another subclass called Error.

• Errors are not normally trapped/handled from the Java


programs. These conditions normally happen in case of
server/serious failure, which are not handled by the java
programs.
Hierarchy of Java Exception classes
Types of Exception
• Some of exceptions are caused
by
– User error,

– Programmer error,

– Physical resources that have failed


in some manner.

• Based on these, we have


three categories of
exception
Checked Exception
• The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions.

• Any code that may throw a checked exception must either


catch the exception using a try-catch block or specify that it
throws the exception in the method signature using the
"throws" keyword.
• For example,
– IOException, SQLException, ClassNotFoundException etc.

• Checked exceptions are checked at compile-time.


Checked Exception Conn…
• A checked exception is an exception that is checked (notified)
by the compiler at compilation time, these are also called as
compile time exceptions.

• These exceptions cannot simply be ignored, the programmer


should take care of (handle) these exceptions
– For example, if you use FileReader class in your program to

read data from a file, if the file specified in its constructor


doesn't exist, then a FileNotFoundException occurs, and the
compiler prompts the programmer to handle the exception.
Example
import java.io.*;
import java.io.FileNotFoundException;
public class FileNotFoundExceptionDemo {
public static void main(String args[]) throws FileNotFoundException
{
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
Unchecked Exception
• The classes that inherit the RuntimeException are known as
unchecked exceptions and the compiler does not enforce the
Catch or Specify Requirement for them.

• For example, ArithmeticException, NullPointerException,


ArrayIndexOutOfBoundsException, etc.

• Unchecked exceptions are not checked at compile-time, but


they are checked at runtime.
Categories of Exception - Errors
 Errors represent exceptional conditions that are generally
beyond the control of the application, such as
OutOfMemoryError or StackOverflowError, network connection
problem, thread death.

 unlike unchecked exceptions, errors do not need to be


declared in a method's throws clause, and the Catch or Specify
Requirement does not apply to them.
Java Exception Keywords
Keyword Description

try The "try" keyword is used to specify a block where we


should place an exception code. It means we can't use try
block alone. The try block must be followed by either
catch or finally.

catch The "catch" block is used to handle the exception. It must


be preceded by try block which means we can't use catch
block alone. It can be followed by finally block later.
Java Exception Keywords cont.
Keyword Description

finally The "finally" block is used to execute the necessary code of


the program. It is executed whether an exception is
handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It


specifies that there may occur an exception in the
method. It doesn't throw an exception. It is always used
with method signature.
Sample Program [1]
What’s the output of the following program?

public class SampleProgram {


public static void main(String args[]) {
String[] greek = {"Alpha", "Beta",
"Gamma"};
System.out.println(greek[3]);
}
}

85
Sample Program [1] cont.
• Compiles successfully but encounters a problem when it
runs

• The Java interpreter made note of the exception by


displaying the error message and stopped the program.

• An object of type ArrayIndexOutOfBoundException is


created to alert the user – you have used an array
element that isn’t within the array’s boundaries.

• ArrayIndexOutOfBoundException is a subclass of
What happens when exception
occurs?
• When an exception occurs within a method, the method creates an
object and hands it off to the runtime system.

• The object created is called an exception object, contains information


about the error, including its type and the state of the program when the
error occurred.

• Creating an exception object and handing it to the runtime


system is called throwing an exception.

• After a method throws an exception, the runtime system attempts to find


something to handle it. The set of possible "somethings" to handle the
exception is the ordered list of methods that had been called to get to the
Call Stack

 The runtime system searches the call stack for a method that
contains a block of code that can handle the exception. This block of
code is called an exception handler.
 The search begins with the method in which the error occurred and
proceeds through the call stack in the reverse order in which the methods
were called.
 If the runtime system exhaustively searches all the methods on the call
SumNumbers [1]
public class SumNumbers {
public static void main(String[] arguments) {
float sum = 0;
for (int i=0; i < arguments.length; i++)
sum += Float.parseFloat(arguments[i]);
System.out.println("Those numbers add up to "+
sum);
}
}

89
SumNumbers [2]
public class SumNumbers {
public static void main(String[] arguments) {
float sum = 0;
for (int i=0; i < arguments.length; i++)
sum += Float.parseFloat(arguments[i]);
System.out.println("Those numbers add up to "+
sum);
}
}

90
Example [1]
import java.util.Scanner;

public class InputMismatch {


public static void main(String[] arguments) {
Scanner sc = new Scanner(System.in);
int x;
x = sc.nextInt();
}
}

If we give either 5.6 or some string “asas” or character


to the above code while entering from keyboard, we get
java.util.InputMismatchException 91
Handling an Exception
• Exception handling is accomplished through
 “try…catch” mechanism OR
 by “throws or throw” clause in method declaration

• For any code that throws a checked exception, we should


either handle ourselves or pass the exception “up the
chain” (to a parent class)

• To handle, we write “try…catch” block

• To pass, we declare a throws clause in our method or


Handling an Exception cont.
• Using a try-catch block: This allows you to handle the exception within
try
the same method or {block of code.
// Code that may throw a checked exception
} catch (SomeCheckedException e) {
// Handle the exception here
}

• Specifying the exception in the method signature: You can declare that a
method throws a checked exception by including the exception type in the
method signature using the "throws" keyword. This means that any code
calling the method must either handle the exception or declare it to be
thrown as well.
public void someMethod() throws
SomeCheckedException {
// Code that may throw a checked
exception
Catching Exceptions in a try-catch
Block
try {
// Code that may throw an exception
} catch (ExceptionType1 ex1) {
// Exception handling for ExceptionType1
} catch (ExceptionType2 ex2) {
// Exception handling for ExceptionType2
} finally {
// Code that is always executed,
// regardless of whether an exception occurred or
not
NewSumNumbers [1]
public class NewSumNumbers {
public static void main(String[] arguments) {
float sum = 0;
for (int i=0; i<arguments.length; i++){
try {
sum += Float.parseFloat(arguments[i]);
}
catch (NumberFormatException e) {
System.out.println(arguments[i] + " isn’t a
number.");
}
}
System.out.println("Those numbers add up to "+ sum);
}
}
NewSumNumbers [Output]
Catching Several Different Exceptions
public class DivideNumbers {
public static void main(String[] arguments) {
if (arguments.length == 2) {
int result = 0;
try {
result =
Integer.parseInt(arguments[0])/Integer.parseInt(arguments[1]);
System.out.println("Result = " + result);
}
catch (NumberFormatException e) {
System.out.println("Both arguments must be numbers.");
}
catch (ArithmeticException e) {
System.out.println("You cannot divide by zero");
}
}
}
}
finally : Example
public class ExcepTest {

public static void main(String args[]) {


int a[] = new int[2];
try {
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println(“Finally statement is executed");
}
}
}
Exceptions Methods
Following is the list of important methods available in the
Throwable class.
No. Method & Description

1 public String getMessage()


Returns a detailed message about the exception that has occurred.
This message is initialized in the Throwable constructor.

2 public Throwable getCause()


Returns the cause of the exception as represented by a Throwable
object.
3 public String toString()
No. Method & Description

4 public void printStackTrace()


Prints the result of toString() along with the stack trace to System.err,
the error output stream.

5 public StackTraceElement [] getStackTrace()


Returns an array containing each element on the stack trace. The
element at index 0 represents the top of the call stack, and the last
element in the array represents the method at the bottom of the call
stack.
6 public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack
trace, adding to any previous information in the stack trace.

You might also like