Chapter - 1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 102

SATA

TECHNOLOGY
& BUSINESS
COLLEGE
Program:
Computer
Science​
Year 4 CS
(Extension)
Java Programming

Instructor:
Addisu M. (Asst. Prof)
1
2

Ch e

Overview of Java Programming


apt
On
er
3
Outline
01 Data types and variables

Object Oriented Programming


02 Arrays

Decision and Repetition


03 Statement

04 Exception Handling
4
Java Environment
 Java environment includes a large number of development tools &
hundreds of classes and Methods.
 The development tools are part of the system known as Java

Object Oriented Programming


Development Kit (JDK) and the classes and methods are part of
the Java Standard Library (JSL), also known as Application
Programming Interface (API).
 JDK comes with a collection of tools that are used for developing
and running java programs:
 appleviewer (for viewing java applets )
 javac (java compiler)
 java (java interpreter)
 javap (java disassembler)
 javah (for C header files)
 javadoc (for creating HTML documents)
 jdb (Java debugger)
5
Overview of Java
 Java is a general-purpose, OOP language
 We can develop two types of Java program namely:
 Stand-alone application

Object Oriented Programming


 Web applets
 Executing stand-alone Java program involves two steps:
 Compiling source code into byte code javac compiler.
 Executing the bytecode program using java interpreter.
 Applets are small programs developed for Internet applications.
 An applet located on a distant computer (server) can be
downloaded via Internet and executed on a local computer (client)
using a Java-capable browser.
6
Overview of Java

Object Oriented Programming


Compiler

Two Ways of writing Java Programs


7
Simple Java Program
 The simplest way to learn a new language is to write a few
simple example programs and execute them.

Object Oriented Programming


public class Sample
{
public static void main (String args [])
{
System.out.print(“Java is better than C++.”);
}
}
8
Simple Java Program
 Let us discuss the program line by line:
• Class Declaration: the first line class Sample declares a class, which is an object

Object Oriented Programming


constructor. Class is keyword and declares a new class definition and Sample is
a java identifier that specifies the name of the class to be defined.
• Opening Brace “{“: Every class definition in java begins with an opening brace
and ends with a closing brace “}”.
• The main line: the third line public static void main(String args[]) defines a
method named as main.
• Is the starting point for the interpreter to begin the execution of the program.
9
Simple Java Program
Note:
 A java program can have any number of classes but only one of them
must include the main method to initiate the execution.

Object Oriented Programming


 Java applets will not use the main method at all.
 third line uses a number of keywords: public, static & void
 Public: is an access specifier that declares the main method as
“unprotected” and therefore making it accessible to all other classes.
 static: declares that this method as one that belongs to the entire class and
not a part of any objects of the class.
 Main must always be declared as static since the interpreter uses this
method before any objects are created.
 void : states that the main method does not return any value (but prints
some text to the screen.)
10
Simple Java Program
 All parameters to a method are declared inside a pair of parenthesis.
Here, String args[ ] declares a parameter named args, which

Object Oriented Programming


contains array of objects of the class type String.
 The Output Line: The only executable statement in the program is
System.out.println(“Java is better than C++.”);
 This is similar to cout<< constructor of C++.
 The println method is a member of the out object, which is a static
data member of System class.
11
Java Program Structure
Documentation Section Suggested

Optional
Package Statement

Object Oriented Programming


Optional
Import Statements

Optional
Interface Statements

Class Definitions Optional

Main Method class


{ Essential
Main Method Definition
}
12
Documentation Section
 comprises a set of comment lines giving the name of the
program, the author and other details, which the programmer

Object Oriented Programming


would like to refer at a later stage.
 Java supports three types of comments:
i. Single line comment //
ii. Multiple line comment /*………………
………………*/
iii. Documentation comment /**….*/
• This form of comment is used for generating documentation
automatically.
13
Main Method Class
 Since every Java stand-alone program requires a main
method as its starting point, this class is the essential part of a

Object Oriented Programming


Java program.
 A simple Java program may contain only this part.
 The main method creates objects of various classes and
establishes communications between them.
 On reaching the end of main, the program terminates and
control passes back to the operating system.
14
Compiling & Running Program
1. Create using a text editor the following program
Class Hello {

Object Oriented Programming


public static void main(String[] args) {
System.out.println(“Hello class!”);
}
}
2. Save the file in D: drive under the folder JavaExample by the file
name Hello.java
3. Open the command prompt(cmd)
4. Use cd command to change the director to JavaExample D:\
JavaExample>
15
Compiling & Running Program
5. Use javac to compile the file Hello.java

Object Oriented Programming


 D:\JavaExample> javac Hello.java
The above command creates the class file Hello.class
6. Run the application using the command java
 D:\JavaExample> java Hello
 To Compile : javac Hello.java
 To Run : java Hello
16
Reserved keywords
 words with special meaning to the compiler
 The following keywords are reserved in Java language.
 They can never be used as identifiers:

Object Oriented Programming


abstract assert boolean break byte
case catch char class const
continue default do double else
extends final finally float for
goto if implements import instanceof
int interface long native new
package private protected public return
short static strictfp super switch
synchronized this throw throws transient
try void violate while
 Some are not used but are reserved for further use. (Eg.: const, goto)
17
Variable
 Variables are places where information can be stored while a
program is running.
 Their values can be changed at any point over the course of a

Object Oriented Programming


program
 Naming Variable
 name (programmer given) that you choose for a variable is
called an identifier
 identifier - Identify classes, methods, variables, objects,
packages
 An identifier can be of any length, but must start with letter (a
– z), dollar sign ($), or an underscore ( _ )
 rest of the identifier can include any character except those
used as operators in Java such as + , - , * .
 keywords can never be used as identifiers
18
Variable
 Creating Variable
 declare its name & type of data that it will store
 type is listed first, followed by the name.

Object Oriented Programming


 Example: a variable that stores an integer representing the
highest score on an exam could be declared as:
int highScore ;

type name
 You may assign a value to it highScore = 98;
 Examples of other types of variables:
String studentName;
boolean gameOver;
19
Statements
A statement is a command that causes something to happen.
All statements are separated by semicolons ;
Example: System.out.println(“Hello, World”);

Object Oriented Programming


Variables and Statements
One way is to declare a variable and then assign a value to it
with two statements:
int e; // declaring a variable
e = 5; // assigning a value to a variable
Another way is to write a single initialization statement:
int e = 5; // declaring AND assigning
20
Data Types
All variables must be declared with a data type before they are used.
Certain operations are only allowed with certain data types
If you try to perform an operation on an illegal data type (like multiplying

Object Oriented Programming


Strings), the compiler will report an error
two basic types
 Primitive types
 Reference types
21
Data Types
Integer :
There are four types that can be used to store integers.
The one you choose to use depends on the size of the number that

Object Oriented Programming


we want to store
Data Type Value Range
byte -128 to +127
short -32768 to +32767
int -2147483648 to +2147483647
long -9223372036854775808 to +9223372036854775807
 Examples - when you want to use integer types:
- byte smallValue = -55;
- int pageCount = 1250;
- long bigValue = 1823337144562L;
22
Data Types
Floating Point :
 There are two data types that can be used to store decimal values
(real numbers).

Object Oriented Programming


 The one you choose to use depends on the size of the number that
we want to store.
Data Type Value Range
float 1.4×10-45 to 3.4×1038
double 4.9×10-324 to 1.7×10308
Boolean :
 has a value true or false (there is no conversion b/n Boolean and other
types).
 used in situations where there are two options (true or false)
 Example: boolean fileOpen = false;
23
Data Types
Character :
 can be used to store a single characters such as a letter, number,
punctuation mark, or other symbol.

Object Oriented Programming


 Example:
 char firstLetterOfName = 'e’ ;
 char myQuestion = '?’ ;
 Note: you need to use singular quotation marks when assigning
char data types.
String :
 series of characters inside double quotation marks.
 Examples statements assign String variables:
 String coAuthor = "John Smith";
 String password = "swordfish786";
 are constant; their values cannot be changed after they are created
24
Scope & Lifetime of variables
scope is the region of a program within which the variable can be
referred to by its simple name
scope also determines when the system creates and destroys memory for

Object Oriented Programming


the variable
block defines a scope - each time you create a block of code
Variables are created when their scope is entered, and destroyed when
their scope is left. This means that a variable will not hold its value once
it has gone out of scope.
Variable declared within a block will lose its value when the block is
left. Thus, the lifetime of a variable is confined to its scope.
You can’t declare a variable in an inner block to have the same name as
the one up in an outer block. But it is possible to declare a variable down
outside the inner block using the same name.
25
Blocks
group of zero or more statements between balanced braces
if (Character.isUpperCase(aChar)) {
System.out.println(“Character " + aChar + " is upper case.");

Object Oriented Programming


}
else{
System.out.println(“Character " + aChar + " is lower case.");
}
Here are some examples of when you would want to use floating point
types:
double g = 7.7e100 ;
double tinyNumber = 5.82e-203;
float costOfBook = 49.99F;
Note: In the last example we added an F to the end of the value.
Without the F, it would have automatically been considered a double
instead.
26
Operators
Operators are special symbols used for
– mathematical functions
– assignment statements

Object Oriented Programming


– logical comparisons
Examples:
 3+5 // uses + operator
 14 + 5 – 4 * (5 – 3) // uses +, -, * operators
There are 5 different groups of operators:
• Arithmetic operators (+, -, *, /, %,^)
• Assignment operator (=)
• Increment/Decrement operators (++, --)
• Relational operators (>, <, >=, <=, ==, !=)
• Conditional operators (!, &&, ||)
27
Expression
Combine literals, variables, and operators to form expressions
Expression is segments of code that perform computations and
return values

Object Oriented Programming


Expressions can contain: Example:
– number literal, 3.14
– variable, count
– method call, Math.sin(90)
– operator between two expressions (binary operator), phase +
Math.sin(90)
– operator applied to one expression (unary operator), -discount
– expressions in parentheses. (3.14-amplitude)
28
Statements
Roughly equivalent to sentences in natural languages
Forms a complete unit of execution.
terminating the expression with a semicolon (;)

Object Oriented Programming


Three kinds of statements in java
 expression statements
 declaration statements
 control flow statements
expression statements
 Null statements
 Assignment expressions
 Any use of ++ or –
 Method calls
 Object creation expressions
29
Statements
Example
 aValue = 8933.234; //assignment statement

Object Oriented Programming


 aValue++; //increment statement
 System.out.println(aValue); //method call statement
 Integer integerObject = new Integer(4); //object creation
A declaration statement declares a variable
double aValue = 8933.234; // declaration statement
A control flow statement regulates the order in which statements
get executed
E.g - if, for
30
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

Object Oriented Programming


type (hold only one type of data)
Example:
int[] can hold only integers
char[] can hold only characters
A particular values is indicated by writing an index number or
subscript in brackets after the array name.
Example:
slaray[10] represents salary of the 10 th employee.
31
Arrays
Each item in an array is called an element, and each element is accessed
by its numerical index.
Array indexing starts from 0 and ends at n-1, where n is the size of the

Object Oriented Programming


array.
index values

primes[0] primes[1] primes[2] primes[3] primes[4] primes[9]

One-Dimensional Arrays
list of items can be given one variable name using only one subscript
and such a variable is called a single-subscripted variable or one-
dimensional array
32
Arrays
Declaration of Arrays
Arrays in java can be declared in two ways:

Object Oriented Programming


i. type arrayname[ ];
ii. type[ ] arrayname;
Example: int number[];
float[] marks;
Creation of Arrays
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];
int num[ ] = new int[10];
33
Arrays
Initialization of Arrays
Each element of an array needs to be assigned a value; this process
is known as initialization.

Object Oriented Programming


Syntax: arrayname [subscript] = Value;
Trying to access an array beyond its boundaries will generate an
error.
generates an ArrayIndexOutOfBoundsException when there is
underrun or overrun
Arrays can also be initialized automatically in the same way as the ordinary
variables when they are declared, as shown below: type arrayname []
= {list of Values};
Example: int number[]= {35,40,23,67,49};
34
Arrays
Initialization of Arrays
Arrays can also be initialized automatically in the same way as the

Object Oriented Programming


ordinary variables when they are declared, as shown below:
type arrayname [] = {list of Values};
Example: int number[]= {35,40,23,67,49};
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;
35
Arrays
//sorting of a list of Numbers if (num[i] < num [j]){
class Sorting{ //Interchange Values
public static void main(String [ ]args){ int temp = num[i];
num [i] = num [j];

Object Oriented Programming


int num[ ]= {55, 40, 80, 12, 65, 77};
num [j] = temp;
int size = num.length;
}
System.out.print(“Given List: “); }
for (int i=0; i<size; i++) { }
System.out.print(" " + num[ i ] ); System.out.print("SORTED LIST" );
} for (int i=0; i<size; i++){
System.out.print("\n"); System.out.print(" " " + num [i]);
//Sorting Begins }
for (int i=0; i<size; i++) { System.out.println(" ");
for (int j=i+1; j<size; j++) { }
}
36
String
Strings represent a sequence of characters
to represent a sequence of characters use a character:

Object Oriented Programming


char ch[ ]= new char[4];
ch[0] = ‘D’; ch[2] = ‘a’;
ch[1] = ‘a’; ch[3] = ‘7;
This is equivalent to String ch=“Hello”;
In Java, strings are class objects and implemented using two
classes: String and StringBuffer
Once a String object is created it cannot be changed
To get changeable strings use StringBuffer class
37
String
In Java, strings are declared and created as follows:
String stringName;

Object Oriented Programming


stringName = new String(“String”);
Example: String firstName;
firstName = new String(“Jhon”);
The above two statements can be combined as follows:
String firstName= new String(“Jhon”);
length() method returns the length of a string.
Example: firstName.length(); // returns 4
38
String Arrays
It is possible to create and use arrays that contain strings as
follows:

Object Oriented Programming


String arrayname[] = new String[size];
Example:
String item[]= new String[3];
item[0]= “Orange”;
item[1]= “Banana”;
item[2]= “Apple”;
It is also possible to assign a string array object to another string
array object.
39
String Methods
1. length(); returns the length of the string.
Eg: System.out.println(“Hello”.length()); // prints 5
2. charAt(); returns the character at the specified index.

Object Oriented Programming


Syntax : public char charAt(int index)
Ex: ch = “abc”.charAt(1); // ch = “b”
3. equals(); returns ‘true’ if two strings are equal.
Syntax : public boolean equals(Object anObject)
Ex: String str1=“Hello”,str2=“hello”;
(str1.equals(str2))? System.out.println(“Equal”); :
System.out.println(“Not Equal”); // prints Not Equal
40
String Methods
4. toLowerCase(); converts all of the characters in a String to lower
case.
Syntax : public String toLowerCase( );

Object Oriented Programming


Ex: String str1=“HELLO THERE”;
System.out.println(str1.toLowerCase()); // prints hello there
5. trim(); removes white spaces at beginning & end of a string
Syntax : public String trim( );
Ex: System.out.println(“ wel-come ”.trim());
//prints wel-come
6. replace(); replaces all appearances of a given character with another
character.
Syntax : public String replace( ‘ch1’, ’ch2’);
Ex: String str1=“Hello”;
System.out.println(str1.replace(‘l’, ‘m’)); // prints Hemmo
41
String Methods
7. split(); splits the string against given regular expression and
returns a string array.
Ex: String ak=“Kelemua Alemseged Kifle";

Object Oriented Programming


String st[]=ak.split(" ");
8. comparetTo(); Compares two strings lexicographically.
 returns negative integer if the first String is less than second
 positive integer if the first String is greater than second
 Otherwise result is zero
Syntax : public int compareTo(String anotherString);
Ex: (“hello”.compareTo(“Hello”)==0) ?
System.out.println(“Equla”); : System.out.println(“Not Equal”);
//prints Not Equal
11. startsWith(); Tests if the string starts with the specified prefix
Syntax: public boolean startsWith(String prefix);
42
String Methods
9. concat(); concatenates specified string to end of this string.
Syntax : public String concat(String str)
Ex: System.out.println(“wel".concat(“come"); //returns welcome

Object Oriented Programming


 + operator is used to concatenate two or more strings
String str = “My name is” + “Harry” + “.”;
10. substring(); method creates a substring starting from the specified
index (nth character) until the end of the string or until the
specified end index.
Syntax : public String substring(int beginIndex);
public String substring(int beginIndex, int endIndex);
Ex: "smiles".substring(2); //returns "iles"
"smiles".substring(1, 5); //returns "mile"
43
Methods of Scanner Class
Scanner class provides the following methods to read
different primitives types:

Object Oriented Programming


Method Description
int nextInt() used to scan the next token of the input as an integer.

float nextFloat() used to scan the next token of the input as a float.

double nextDouble() used to scan the next token of the input as a double.

byte nextByte() used to scan the next token of the input as a byte.

String nextLine() Advances this scanner past the current line.

boolean nextBoolean() used to scan the next token of input into a boolean value.
44
How to get input from user
Java Scanner Class
allows the user to read the input of primitive types like int, double,
long, short, float, and byte from the console/keyboard
belongs to java.util package

Object Oriented Programming


Syntax: Scanner sc = new Scanner(System.in);
creates a constructor of the Scanner class having System.in as an
argument, is going to read from standard input stream of the program
java.util package should be import while using Scanner class
Method Description
long nextLong() used to scan the next token of the input as a long.
short nextShort() used to scan the next token of the input as a Short.
BigInteger nextBigInteger() used to scan the next token of the input as a BigInteger.
BigDecimal nextBigDecimal() used to scan the next token of the input as a BigDecimal.
45
How to get input from user
import java.util.*;
class UserInputDemo {
public static void main(String[] args) {

Object Oriented Programming


Scanner sc= new Scanner(System.in); //System.in is a
standard input stream
System.out.print("Enter first number- ");
Example
int a= sc.nextInt();
System.out.print("Enter second number- ");
int b= sc.nextInt();
int d=a+b;
System.out.println("Total= " +d);
}
}
46
Type Casting
Used when you assign a value of one primitive data type to another
type.
In Java, there are two types of casting:

Object Oriented Programming


Widening Casting (automatically) - converting a smaller type to a
larger type size
byte -> short -> char -> int -> long -> float -> double
done when passing a smaller size type to a larger size type:
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
47
Type Casting
In Java, there are two types of casting:
Narrowing Casting (manually) - converting a larger type to a
smaller size type

Object Oriented Programming


double -> float -> long -> int -> char -> short -> byte
done manually by placing type in parentheses in front of the value:

public class Main {


public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int System.out.println(myDouble); //
Outputs 9.78 System.out.println(myInt); // Outputs 9
}
}
48
Methods
Methods also known as functions or procedures.
Methods are a way of capturing a sequence of

Object Oriented Programming


computational steps into a reusable unit.
Methods can accept inputs in the form of arguments,
perform some operations with the arguments, and then
can return a value the is the output, or result of their
computations
inputs outputs
method
49
Methods
Declaring Methods
Method has 4 parts: return type, name, arguments, and body:
type

Object Oriented Programming


name arguments

double sqrt (double num) {


body // a set of operations that compute
}
type, name and arguments together is referred to as the signature of the
method
return type of a method may be any data type.
Methods can also return nothing in which case they are declared
void.
50
Methods
Return Statements
used to output the result of the methods computation
has the form: return expression_value;

Object Oriented Programming


type of the expression_value must be the same as the type of the method:
double sqrt(double num){
double answer;
// Compute and store the value into the variable answer
return answer;
}
method exits immediately after it executes return statement
Therefore, return statement is usually the last statement in a method
A method may have multiple return statements
51
Methods
Method Arguments
Methods can take input in the form of arguments.
Arguments are used as variables inside the method body.

Object Oriented Programming


Like variables, it must have their type specified.
are specified inside the parentheses that follow the name of the method
double divide(double a, double b) {
double answer;
answer = a / b;
return answer;
}
Multiple method arguments are separated by commas
Arguments may be of different types
int indexOf(String str, int fromIndex)
52
Methods
Method Body
a block specified by curly brackets
defines the actions of the method.

Object Oriented Programming


All methods must have curly brackets to specify the body even if
the body contains only one or no statement.
Invoking Methods
To call a method, specify the name of the method followed by a list
of comma separated arguments in parentheses:
pow(2, 10); //Computes 210
If the method has no arguments, you still need to follow the
method name with empty parentheses:
size();
53
Decision Making Statements
 allows the code to execute a statement or block of
statements conditionally

Object Oriented Programming


 Control the execution flow of a program causing a jump
to any point from its current location.
 Java supports types of decision making statements:
• if Statements
• switch Statements
54
Decision Making Statements
if Statement
 if statement is a powerful decision making statement

Object Oriented Programming


 It is basically a two-way decision making statement and is used in
conjunction with an expression.

Test
False
expression ?

True
 if statement may be implemented in different forms depending on
the complexity of conditions to be tested:
55
Decision Making Statements
if Statement - Simple
 An if statement consists of a Boolean expression followed by one

Object Oriented Programming


or more statements.
 syntax: 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
56
Decision Making Statements
if Statement - Simple
 Example

Object Oriented Programming


//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
Output: Age is greater than 18
57
Decision Making Statements
if … else Statement
 Syntax: if{ (expression)

Object Oriented Programming


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 excuted followed
by rest_of_program block.
58
Decision Making Statements
if … else Statement
 Example int number=13;

Object Oriented Programming


//Check if the number is divisible by 2 or not
if(number%2 == 0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
Output: odd number
59
Decision Making Statements
if … else if (else if) Statement
 used when multiple decisions are involved

Object Oriented Programming


 A multiple decision is a chain of ifs in which the statement
associated with each else is an if
 conditions are evaluated from the top, downwards
 As soon as the true condition is found, the statement 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
containing the default statement will be executed
60
Decision Making Statements
if … else if (else if) Statement
 Syntax: if (expression 1) {
Example

Object Oriented Programming


statement(s)-1;
}
if (grade == 'A')
else if (expression 2){
statement(s)-2; System.out.println("You got A");
} else if (grade == 'B')
...
else if (expression n){
System.out.println("You got B");
statement(s)-n; else if (grade == 'C')
} System.out.println("You got C");
else
default-statement;
else
rest_of_program; System.out.println("You got F");
61
Decision Making Statements
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

Object Oriented Programming


each case
 The syntax of switch statement is:
switch (expression)
{
case value-1:
statement-block 1;
break;
case value-2:
statement-block 2;
break;
......
default:
default_statement;
break;
}
rest_of_program
62
Decision Making Statements
switch Statement
 expression must evaluate to a char, short or int, but not long, float or double
 values value-1, value-2, value-3, … are constants or constant expressions and

Object Oriented Programming


are known as case labels
 Each of them should be unique within the switch statement
 statement-block1, statement-block2,…. are statement lists and may contain
zero or more statements.
 no need to put braces around statement blocks of switch but it is important to
note that case labels end with a colon (:)
 When the switch is executed, value of the expression is successfully
compared against values value-2, 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.
 break causes an exit from the switch statement
63
Decision Making Statements
switch Statement switch (grade) {
case 'A':
System.out.println(“Excellent");
break;

Object Oriented Programming


case 'B':
System.out.println(“Well done");
Example break;
case 'C':
System.out.println("You
passed");
break;
default:
System.out.println(“Invalid
 if-else chains can be grade");
sometimes be rewritten as a “switch”
}
statement
 switches are usually simpler and faster
64
Decision Making Statements
?: (Conditional) Operator
 useful for making a two-way decisions

Object Oriented Programming


 combination of ? and : and takes three operands

General formula:
conditional expression ? Expression1:expression2;
 conditional expression is evaluated first. If the result is true,
expression1 is evaluated and is returned as the value of the
conditional expression. Otherwise, expression2 is evaluated and its
value is returned.
65
Looping Statements
 The process of repeatedly executing a block of statements is
known as looping.

Object Oriented Programming


 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.
 sequence of statements are executed until some conditions from
the termination of the loop are satisfied
 A program loop consists of two statements:
 Body of the loop.
 Control statements
66
Looping Statements
 control statement tests certain conditions and then directs the
repeated execution of the statements contained in the body of
the loop.

Object Oriented Programming


 looping process, would include the ff 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
 Depending on the position of the control statement in the loop,
a control structure can be either as the entry-controlled loop or
as exit-controlled loop.
67
Looping Statements
 In entry-controlled loop, the control conditions are tested before
the start of the loop execution.
 In exit-controlled loop, the test is performed at the end of the body

Object Oriented Programming


of the loop and therefore the body is executed unconditionally for
the first time.
 Three types of loops in java:
1.while loops
2.do …while loops
3.for loops
68
Looping Statements
while loop
 simplest of all the looping structures in Java
 an entry-controlled loop statement

Object Oriented Programming


 executes as long as the given logical expression between
parentheses is true
 When expression is false, execution continues with the
statement immediately after the body of the loop block
 expression is tested at the beginning of the loop, so if it is
initially false, the loop will not be executed at all
69
Looping Statements
while loop
 basic format of the while statement is: Example:
int sum=0,n=1;

Object Oriented Programming


initialization;
while(n<=100)
while (expression) {
{ sum+=n;
Body of the n++;
loop; }
} System.out.println(“Sum=”+sum;
 body of the loop may have one or more statements.
 braces are needed only if the body contains two or more
statements
 However, it is a good practice to use braces even if the body has
only one statement
70
Looping Statements
do…while loop
 Unlike while statement, do… while loop executes the body of the
loop before the test is performed

Object Oriented Programming


initialization;
do
{
Syntax for do…while loop Body of the loop;
}
while (expression);
 On reaching the do statement, the program proceeds to evaluate
the body of loop first
71
Looping Statements
do…while loop
 At the end of the loop, test condition in the while statement is
evaluated

Object Oriented Programming


 If it is true, the program continues to evaluate the body of the loop
once again
 When the condition becomes false, the loop will be terminated and
the control goes to the statement that appears immediately after
the while statement int sum=0,n=1;
do
{
sum+=n;
n++;
} while(n<=100);
System.out.println(“Sum=”+sum;
72
Looping Statements
for loop for(initialization; test condition; increment)
 Syntax: {

Object Oriented Programming


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
 execution of the for loop statement is as follows:
1. Initialization of the control variable(s) is done first, using
assignment statement
2. value of the control variable is tested using test condition
 Test condition is a determines when the loop will exit
73
Looping Statements
for loop
2. value of the control variable is tested using test condition
 If the condition is true, the body of the loop is executed; otherwise the

Object Oriented Programming


loop is terminated and the execution continues with the statement that
immediately follows the loop
3. When body of loop is executed, control is transferred back to for
statement after evaluating 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);
74
Looping Statements
for loop: additional features
A. More than one variable, separated by comma, can be

Object Oriented Programming


initialized at a time in the for statement
for(sum=0, i=1; i<=100; i++){
sum=sum+i; Example:
}
B. Increment section may also have more than one part
for(i=0, j=0; i*j < 100; i++, j+=2){
System.out.println(i * j); Example:
}
75
Looping Statements
for loop: additional features
C. test condition may have any compound relation and testing need
not be limited only to loop control variable

Object Oriented Programming


for(sum=0, i=1; i<20 && sum<100; ++i){
sum=sum+i;
} Example:
D. You do not have to fill all 3 control sections, one or more sections
can be omitted but you must have 2 semicolons
int n = 0;
for(; n != 100;) {
Example:
System.out.println(++n);
}
76
Looping Statements
Nesting of for loops
 nest loops of any kind one inside another to any depth
for(int i = 10; i > 0; i--)

Object Oriented Programming


{
while (i > 3)
{
if(i == 5){ Inner Outer
break; Loop Loop
Example: }
System.out.println(i);
i--;
}
System.out.println(i*2);
}
77
Looping Statements
Jumps in Loops
 Jump statements are used to unconditionally transfer the program
control to another part of the program

Object Oriented Programming


 Java has 3 jump statements: break, continue, & return
1. break statement
 used to abort the execution of a loop
 general form : break;
int i=1;
while ( i < 10) {
if(i%2==0)
break;
System.out.println(“ ” + i);
}
System.out.println(“Out of the while loop”);
78
Looping Statements
2. continue statement
 used to alter the execution of for, do, and while statements
 general form : continue;

Object Oriented Programming


int sum = 0;
for(int i = 1; i <= 10; i++){
if(i % 3 == 0) {
continue;
}
sum += i;
} What is the value of sum?
1 + 2 + 4 + 5 + 7 + 8 + 10 = 37
79
Looping Statements
3. return statement
 used to transfer the program control to the caller of a

Object Oriented Programming


method
 general form: return expression;
 If the method is declared to return a value, the
expression used after the return statement must evaluate
to the return type of that method.
 Otherwise, the expression is omitted.
80
Looping Statements
class ContinueBreak {
public static void main(String [ ]args)
{ *
Loop1: for(int i=1; i<100; i++)

Object Oriented Programming


{ **
System.out.println(" "); ***
if (i>=8)
break; ****
for (int j=1; j<100; j++) *****
{ ******
System.out.print("*");
if (j==i) *******
continue Loop1; Termination by BREAK
}
}
System.out.print("Termination by BREAK");
}
}
81
Looping Statements
Example
for(a=0;a<5;a++)

Object Oriented Programming


{
for(b=4;b>a;b--) 5
{ 454
System.out.print(" ");
} 34543
for(c=5-a;c<=5;c++) 2345432
System.out.print(c); 123454321
for(d=4;d>=5-a;d--)
System.out.print(d);
System.out.println();
}
82
Looping Statements
Example
for(a=0;a<5;a++){

Object Oriented Programming


for(b=0;b<a;b++){
System.out.print(" ");
} $$$$$
for(c=4;c>=a;c--){
$$$$
$$$
System.out.print("$");
}
$$
System.out.println(); $
}
83
What is an Exception?
 When a problem encounters and unexpected termination or
fault, it is called an exception
 An error event that disrupts the program flow and may cause a

Object Oriented Programming


program to fail
 Some examples:
 Performing illegal arithmetic
 A user has entered invalid data
 Illegal arguments to methods
 Accessing an out-of-bounds array element
 Hardware failures
 Writing to a read-only file
 divide by 0
84
What is an Exception?
What is Exception?
 Exception is an event that disrupts the normal flow of the program
What is Exception handling?

Object Oriented Programming


 Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that normal flow of the application can
be maintained such as ClassNotFoundException, IOException,
SQLException, RemoteException etc
 When an exception happens we say it was thrown or raised
 When an exception is dealt with, we say the exception is was handled
or caught
85
Exception Handling
 What is the output of this program? Example
public class ExceptionExample {

Object Oriented Programming


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

• Exception in thread "main"


Output: • java.lang.ArrayIndexOutOfBoundsException: 2 at
ExceptionExample.main(ExceptionExample.java:4)
86
Hierarchy of Java Exception classes

 java.lang.Throwable class is

Object Oriented Programming


the root class of Java Exception
hierarchy inherited by two
subclasses:
 Exception and
 Error
87
Hierarchy of Java Exception classes

Object Oriented Programming


88
Types of Java Exceptions
 There are mainly two types of exceptions:
 checked and
 unchecked

Object Oriented Programming


 An error is considered as the unchecked exception.
 However, according to Oracle, there are three types of
exceptions namely:
 Checked Exception
 Unchecked Exception
 Error
89
Difference between
Checked Exception
• classes that directly inherit Throwable class except RuntimeException & Error
• are less frequent and cannot be ignored by the programmer . . .

Object Oriented Programming


• errors that programmer cannot directly prevent from occurring
• E.g., IOException, FileNotFoundException, SocketException etc.
• checked at compile-time

Unchecked Exception
• classes that inherit RuntimeException
• errors that programmer can directly prevent from occurring
• Usually occur because of programming errors, when code is not robust enough to prevent them
• E.g., ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
IllegalArgumentException, etc
• not checked at compile-time, but they are checked at runtime

Error
• irrecoverable
• E.g., OutOfMemoryError, VirtualMachineError, AssertionError etc.
90
Exceptions Methods
 list of methods available in the Throwable class
Function Description
Returns a detailed message about the exception that has

Object Oriented Programming


public String getMessage() occurred. This message is initialized in the Throwable
constructor.
Returns the cause of the exception as represented by a
public Throwable getCause() Throwable object.
Returns the name of the class concatenated with the result of
public String toString() getMessage().
Prints the result of toString() along with the stack trace to
public void printStackTrace() System.err, the error output stream.
Returns an array containing each element on the stack trace.
public StackTraceElement [] The element at index 0 represents the top of the call stack, and
getStackTrace() the last element in the array represents the method at the
bottom of the call stack.
91
How Programmer Handles an Exception?
Customized Exception Handling:
 Java exception handling is managed via five keywords:
 try, catch, throw, throws, and finally

Object Oriented Programming


 Program statements that you think can raise exceptions are
contained within a try block
 If an exception occurs within the try block, it is thrown
 Your code can catch this exception (using catch block) and handle it
in some rational manner
 System-generated exceptions are automatically thrown by Java run-
time system
 To manually throw an exception, use the keyword throw
 Any exception that is thrown out of a method must be specified as
such by a throws clause
 Any code that absolutely must be executed after a try block
completes is put in a finally block
92
How Programmer Handles an Exception?
 Java provides 5 keywords – used to handle exception
Keyword Description
 used to specify a block where we should place an exception code

Object Oriented Programming


try  It means we can't use try block alone
 must be followed by either catch or finally
 used to handle the exception
catch  must be preceded by try block - means we can't use catch block alone
 can be followed by finally block later
 used to execute the necessary code of the program
finally  It is executed whether an exception is handled or not.
throw  used to throw an exception
 used to declare exceptions
 specifies that there may occur an exception in the method
throws  It doesn't throw an exception
 It is always used with method signature
93
How Programmer Handles an Exception?
 Use try-catch block to handle exceptions that are thrown
 “try” keyword – used specify the a block where we should
place exception code

Object Oriented Programming


 try block must be followed by either catch or finally.
 It means, we can’t use try block alone
try {
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}
94
How Programmer Handles an Exception?
 “catch” block – used to handle the exception
 It must be preceded by try block which means we can’t use
catch block alone.

Object Oriented Programming


 It can be followed by finally block later.

 “finally” block – used to execute important code of the


program
 It is executed whether an exception is handled or not.
95
How Programmer Handles an Exception?
class GFG {
public static void main(String[] args)
{ Example

Object Oriented Programming


int[] arr = new int[4];
int i = arr[4];
System.out.println("Hi, I want to execute");
}
}

Output:
96
Common Scenarios of Java Exceptions
1) ArithmeticException
 If we divide any number by zero, there occurs an ArithmeticException
2) NullPointerException int a = 50/0;//ArithmeticException+
 If we have a null value in any variable, performing any operation on the

Object Oriented Programming


variable throws a NullPointerException
String s=null;
3) NumberFormatException
System.out.println(s.length());//NullPointerException
 If the formatting of any variable or number is mismatched, it may result into
NumberFormatException

String s="abc";
4) ArrayIndexOutOfBoundsException
int i=Integer.parseInt(s);//NumberFormatException
 array exceeds to it's size, ArrayIndexOutOfBoundsException occurs
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
97
throw vs throws
 throws - used to declare an exception, which means it
works similar to the try-catch block. On the other hand,

Object Oriented Programming


throw - used to throw an exception explicitly
 throw is followed by an instance of Exception class
and throws is followed by exception class names.
 throw - used in the method body to throw an exception,
while throws - used in method signature to declare the
exceptions that can occur in the statements present in the
method
98
throw vs throws
Basis of
Differences throw throws
used to explicitly throw an used to declare exceptions
Definition exception (checked or

Object Oriented Programming


unchecked) from a method
we can only propagate we can declare both checked and
Type of unchecked exception i.e., unchecked exceptions. However, the
exception checked exception cannot be throws keyword can be used to propagate
propagated using throw only checked exceptions only
Syntax followed by an instance of followed by class names of Exceptions to
Exception to be thrown be thrown
used within the method used with the method signature to indicate
Declaration that this method might throw one of the
listed type exceptions
Internal We are allowed to throw only We can declare multiple exceptions using
implementati one exception at a time i.e. we throws keyword that can be thrown by the
cannot throw multiple method. For example, main() throws
on exceptions IOException, SQLException
99
Java throw - Example
public class TestThrow {
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("\

Object Oriented Programming


nNumber is negative, cannot calculate square");
}
else {
System.out.println("Square of " + num + " is " + (num*num));
}
}
public static void main(String[] args) {
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
}
} Exception in thread "main"
Output: java.lang.ArthmeticException:
Number is negative, cannot calculate square
at
TestThrow.checkNum(TestThrow.java:6)
at
10
0 Java throws - Example
public class TestThrows {
public static int divideNum(int m, int n) throws ArithmeticExceptio
n{
int div = m / n;

Object Oriented Programming


return div;
}
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e){
System.out.println("\nNumber cannot be divided by 0");
}
System.out.println("Rest of the code..");
}
Output: Exception cannot be divided by
} 0
Rest of the code….
10
1 throw & throws - Example
public class TestThrowAndThrows {
static void method() throws ArithmeticException {
System.out.println("Inside the method()");

Object Oriented Programming


throw new ArithmeticException("throwing ArithmeticException"
);
}
public static void main(String args[]) {
try {
method();
}
catch(ArithmeticException e) {
System.out.println("caught in main() method");
}
} Output: Inside the method()
caught in main() method
}
102

THANKS!
Questions, Ambiguities,
Doubts, … ???

You might also like