0% found this document useful (0 votes)
23 views82 pages

Handout 3 Control Statements + Exceptions

This document discusses various Java control statements and error handling concepts including: 1. The final keyword is used to declare variables that do not change. Final variables, methods, and classes cannot be overridden or extended. 2. Local variables declared in methods like main() are only accessible within that method and their values are lost when the method terminates. Class-level variables are accessible by all class methods. 3. Static methods belong to the class and can access only static variables and methods without needing an object. The main() method is declared static so an object does not need to be created to run the program. 4. Control structures like if, for, while, do-while and switch statements

Uploaded by

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

Handout 3 Control Statements + Exceptions

This document discusses various Java control statements and error handling concepts including: 1. The final keyword is used to declare variables that do not change. Final variables, methods, and classes cannot be overridden or extended. 2. Local variables declared in methods like main() are only accessible within that method and their values are lost when the method terminates. Class-level variables are accessible by all class methods. 3. Static methods belong to the class and can access only static variables and methods without needing an object. The main() method is declared static so an object does not need to be created to run the program. 4. Control structures like if, for, while, do-while and switch statements

Uploaded by

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

Java Control

statements and error


handling
Complete exception handling
Local and Final variables
- final keyword is used to store values in variable that
don’t change
- final String Fathername=“Ndiba”;
- Method declare with final keyword cannot be overidden when
user extends class.
- Classes defined with final cannot be extended. You can create
its sub classes
- A variables declared in method such as main are local
variables can only be used within that method. When
method terminates local variables values are lost.
- For variables accessible by all class methods declare it
at class level – for example color and numberOfDoors
declared in Car class next slide. These variables
remain in memory while Car object exists in its
memory and are even visible to external classes.
Static methods

• Static methods belong to the class


• Static methods can only access static
variables and other static methods
• You don’t need to create an object to use
a static method. In writing programs we
didn’t create an object to access main
method. To use scanner constructor we
create a scanner object that we gave
user name input and used input object
method nextInt() to read integers
entered in keyboard.
Why main() is declared static
1. So that interpreter doesn’t have to create
the object before running the program
2. All objects created form class with main
share one main method
3. Its part of specification of language so it
has to be followed in implementing java
4. They is can only be one main method in an
application, if main is not static it can be
overridden in subclasses resulting in two
main methods and ambiguity where program
would start.
Copying programs from other application to NetBeans

If you copy program from another


application like MS PowerPoint or Word
to NetBeans special characters like “ ‘ {
that have same characters (look same)
but different coding scheme values.
You many get errors in the program. If
you copy part with errors and they it
seems correct to you delete the whole
line and retype it, the error will
disappear.
Local and Final variables
package payrollgrosspay;
public class PayrollGrossPay {

static int overtimehrs;

public static void main(String[] args) {


double salary=40000.00;
overtimehrs=16;
//errSalcGSal(salary);
double gp=calcGSal(salary);
System.out.println("Gross Pay = "+gp);
}
/* public static void errCalcGSal(int sal) { // method with error
salary=0.0; // an error salary not visible in errCalcGSal method
overtimehrs=5; // no error class variable/field (global) visible all methods in the class
} */

public static double calcGSal(double sal) {


double grosspay=(overtimehrs*2000)+sal;
return grosspay;
}
}
Secrets of mastering java programming
• Practice while reasoning and learning from
mistakes makes perfect
Secrets of mastering java programming:
- Learn theory
- Then Practice !
- Practice !
- Practice !
- Practice !
• Java is language and if you learn java and don’t
practice writing programs its like learning a
foreign language and not practice speaking the
foreign language. You will never learn a human
language or programming language this way.
Class with multiple methods
package car;
public class Car {
// class level variables declared outside any method
String color;
int numberOfDoors;
int startEngine() {
int nomiles=60000;
// write code here
return nomiles;
}
void stopEngine() {
// write code here
}
public static void main(String[] args) {
// TODO code application logic here
}
}
Scope of declarations
- You cant use a variable before its declared
- There are declarations of various entities: classes,
methods and variables
Scope of declaration is scope of program that is able refer to
declaration.
- Scope of parameter declaration is body of method in which
its declared.
void square(int num) {
scope of parameter num is square function block statements
encloses by {}
}
- Scope of declaration of local variable that appears in
declaration of for, while, do while loops is the body of loop.
loopcontinuationexpression and Loopcontrolincrement
variable
- for(int counter=1;counter<=10;counter++)
for(initializationdeclaration ; loopcontinuationexpression;
Loopcontrolincrement)
Scope of declarations
void is type that indicates method will
not return anything
Method Syntax
return type methodname (lists of types
of variables passed to function) {
method statements
} – end of method
void square(int num) {
statements
}
Scope of declarations …
- Scope of a method or field is entire body of class. This
enables class instance methods to use fields and other
methods of class – e.g. startEngine() and stopEngine() can
be called from any where with class (E.g. class car {}). Color
and numberofdoors can be reference any where in the
class.
- Any block may have variable declarations e.g. : class block,
method block and loop block and selection statement blocks
- If a local parameter or variable has same name as class
field name its hidden until block finishes executing which is
called shadowing. – (class field hidden in method you have
to use this keyword – to be covered in classes {– program to
be made available later}
- If field is an instance of class precede its name with this
- If field is a static class variable precede its name with .
Methods
• Programs normally divided into separate
methods called modules in order to perform
different tasks that can be repeatedly
called in the program. This makes it easy to
debug methods and for modules to be
assigned to different individuals to develop.
• Methods in a program are generally
useful if values can be passed from one part
of program to the other.
• Types a method can accept is given in
method declaration and its type. The
appropriate value should be passed when
argument is called e.g main(String[] args)
accepts an array of strings
Multimethod greeting
package manymethod;
public class ManyMethod {

public static void main(String[] args) {


System.out.println("In main method");
String msg=swah();
System.out.println(msg);
}
public static String swah() {
System.out.println("in swah method");
return "returned from swah";

}
}
Multimethod greeting
package multimethodret;
public class MultiMethodRet {
public static void main(String[] args) {
String cb;
System.out.println("Hello");
cb=swah();
System.out.println(cb);
}
public static String swah() {
System.out.println("Habari");
return "comming back";
}
}
MultiMethods global variable
public class multiMethodScope {
static int nambari=100; //global class variable
public static void main(String[] args)

{
int num=250; // local method variable
System.out.println("greetings from Main method");
System.out.println("Global number is" + nambari);
System.out.println("Main method number is" + num);
Sub("konichwa");
}

public static void Sub(String Jap)


{
int num=500; // local method variable
System.out.println("greetings from Sub method");
System.out.println("Global number is" + nambari);
System.out.println("Sub method number is" + num);
System.out.println("Sub method received your string see it " + Jap);
} }
Branching and looping control statement
• Block statement{} doesn’t affect flow of
program but the other five control
statement do
• Any problem requiring a looping
statement can be implemented in any of
the loops: for, while and do- while.
Problem requiring branching can be
implemented in switch or if.
• Inclusion one type loop or selection is
for convenience and sometimes it my be
easier to implement a solution in on
branching or looping statement than the
other.
Java control structure

• Java programming language is built on six


basic control structures. This control
structures are driven be requirements to
build small to large programs
1. Block {}
2. for
3. while
4. do while
5. switch
6. if
While statement
- While statement is used to repeat
statements as long as condition is true.
However its rare we want to repeat a
loop for ever. A loop that doesn't end is
called a infinite loop
Syntax of a while statement
while(boolean-expression)
(statement/statements)
– Execution of while statement: when program
comes to a while statement it evaluates
boolean-expression if its true it executes
while block statements otherwise the
statements is skipped.
While program to display first 10 numbers [cont]
package whilesquare;
public class WhileSquare {
public static void main(String[] args) {
int square; //square variable
int counter =1; // while loop control variable
while(counter <=10) {
square= counter * counter;
counter = counter +1; // increment counter
}

}
if statements
If (condition)
Statement;
If they are no {} only one statement executed. Puts a
semi colon afer if for, do while, switch and while state
null statement is selected or repeated.
If(condition) {
Statement/s
}
If(condition) {
Statement/s;
} else {
Statements/s
}
If and else block have single statement the {}
delimiters can be removed
if else if
if (condition) {
statement/s
} else if(condition) {
Statement/s;
} else if(condition) {
Statements/s
} else if (condition)
Statement/s;
} else {
Statement/s;
}
Nested if statements
If students grade is greater or equal to 90
Print “a”;
Else If students grade is greater or equal to 87 print “A-”
Else If students grade is greater or equal to 84 print “B+”
Else If students grade is greater or equal to 79 print
“B”
Else If students grade is greater or equal to 96
print “OTHER”
Individual exercise Future exercise
Draw a UML activity diagram for above
pseudocode
Submit blackboard week5 Linkname
elseifPSwk4-1
grades
Marks>=90 A
Marks>=87 A-
Marks>=84 B+
Marks>=80 B
Marks>=76 B-
package gradeifelse;
public class GradeIfElse {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
int marks;
System.out.println("Enter Marks:");
marks=input.nextInt();
if(marks>=90){
System.out.println("A");
} else if(marks>=87){
System.out.println("A-");
} else if(marks>=84){
System.out.println("B+");
} else if(marks>=80){
System.out.println("B");
} else {
System.out.println("OTHER");
}
}
}
PROGRAM THAT ASK USE TO ENTEER 10 STUDENTS MARKS AND GRADES THEM
package gradewhileifelse;
import java.util.Scanner;
public class GradeWhileIfElse {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
int marks;
int control=0;
while(control<10) {
System.out.println("Enter Marks:");
marks=input.nextInt();
if(marks>=90){
System.out.println("A");
} else if(marks>=87){
System.out.println("A-");
} else if(marks>=84){
System.out.println("B+");
} else if(marks>=80){
System.out.println("B");
} else {
System.out.println("OTHER");
}
control=control+1;
} } }
Complete program submit blackboard week4 linkname usiugradingWK4
Do while

- Test the condition at end unlike while


that tests at the beginning.
do {
statements
} while(boolean-expression);

The thing most student forget is


putting as semi colon at of loop
Individual Home exercise
Write a java program that:
- Asks the user to enter an integer n
- Uses a do while loop in main() method to display the first n
integers in descending order. Ascending numbers are
displayed in main(). Ones this part is complete your
program can run

- You will call dowhilereverse() in main() by writing


dowhilereverse(n);
- Uses a do while loop to display first n integers I descending
order in a method called dowhilereverse() – doesn’t return
anything so its return type is void. The numbers in
descending order are displayed in dowhilereverse()

Submit program in blackboard week4 Linkname dowhileWK4


submit 31-1-2024
Do while program to display first 10
integers.
package dowhile1_10;
public class DoWhile1_10 {
public static void main(String[] args) {
int counter=1;
do {
System.out.println(counter);
counter=counter+1;
} while(counter<=10);
}
}
The switch structure
• A switch statement allows a variable
to be tested for equality against a list
of constant values. Each value is called
a case, and the variable being
switched on is checked for each case.
• The constant value that must be
integer or character constant value.

29
Syntax
switch(expression){
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional
// you can have any number of case statements.
default : //Optional
statement(s);}
30
Switch program Exercise (don’t submit)
The following are names of detergents sold in a
shop
Omo, Sunlight, Msafi, Toss, Persil

Write a program that uses switch statement to


count the number of detergents sold. The shop
keep types the first letter of name of detergent.

Submit blackboard week4 detCountWK4 BY 2-10-


2023
Switch program
package switwk3;
import java.util.Scanner;
public class SwitWk3 {
public static void main(String[] args) {
char grade='C';

switch(grade){
case 'A':
System.out.println("Grade is A");
break;
case 'B':
System.out.println("Grade is B");
break;
case 'C':
System.out.println("Grade is C");
Break;
case 'D':
System.out.println("Grade is D");
break;
case 'E':
System.out.println("Grade is E");
break;
default:
System.out.println("Grade invalid");
//break; // optional exits loop any way
} } }
Switch program READ char
package switchchar;
import java.util.Scanner;
public class SwitchChar {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter uppercase Grade A-F");
char grade=“C”
Grade =input.next().charAt(0);

switch(grade){
case 'A':
System.out.println("Grade is A");
break;
case 'B':
System.out.println("Grade is B");
break;
case 'C':
System.out.println("Grade is C");
break;
case 'D':
System.out.println("Grade is D");
break;
case 'E':
System.out.println("Grade is E");
break;
default:
System.out.println("Grade invalid");
//break; // optional exits loop any way
}
}
}
Break and continue statements
break cause control to get out loop or if or
else conditional statements
continue cause execution to go back to
beginning of loop cause statement after
continue to be skipped.

When using break and continue is loops we


often use conditional statement (if or
switch) – because if not use conditional
statement some statement will never
executed so they is no reason to be
written.
Break and continue
//Break allows getting out of any loop
//Statement in loop following continue not executed

package dwconbrk;

public class DwConBreak {

public static void main(String[] args) {


int counter=0;
do {
// System.out.println(counter);
counter=counter+1;
if(counter==5) {
//break; //exits loop
continue;
//System.out.println("bye");
}
System.out.println(counter);

} while(counter<=10);
}

}
}
Scanner reading char

char grade=sc.next().charAt(0);

Used to read characters


Static methods

• Static methods belong to the class


• Static methods can only access static
variables and other static methods
• You don’t need to create an object to use
a static method. In writing programs we
didn’t create an object to access main
method. To use scanner constructor we
create a scanner object that we gave
user name input and used input object
method nextInt() to read integers
entered in keyboard.
Static methods ….

• Static indicates method or


variable is part of the
type(class).
• Its applied to methods and
attributes and nested classes
• Its used for memory
management
• Enables attributes or methods to
be shared among objects
Static methods
• Public class sum {
• Static int number;
• Double s;

Public static void main(String[] args) {

• }
For program to display first 10 integers

package fordisp1_10;
public class ForDisp1_10 {
public static void main(String[] args) {
for(int i=1; i<=10;i++) {
System.out.println(i);
}
i=i+1
}
}
for statement
for statement executing single statement
for(initialization_exp; control_exp; increment-
decremexp)
(statement);

for statement executing block statement


for(initialization_exp; control_exp; incrementexp) {
(statements)
}

Scope of for loop initialization variable is


within the for loop: it cannot be accessed (you
cant use variable before loop executes or after
it terminates
Exercise wk5 {don’t submit

Write a program using for loop that


asks user to enter an integer greater
or equal to one and displays first 10
numbers. Nest another for loop to
make program repeat five times.
• Its similar to while we wrote but used
for statement

Submit blackboard week3 by 27-9-


2022 linkname nest1forNWk5
Nested for program (write program as group and
understand it don’t submit}

package fordisp1_10;
public class ForDisp1_10 {
public static void main(String[] args) {

for(int k=1; k<=3;k++) {


System.out.println(“ Out k=”+k);
//i=0; error I has not been declared
for(int i=1; i<=5;i++) {
System.out.println(“k=”+k+ “ i=”+i);
} //end of inner for loop i
///i=5; i longer exits inner loop has terminated
}//end of outer for loop k

}
}
Output of Nested for program
k=1 i=1
k=1 i=2
k=1 i=3
k=2 i=1
k=2 i=2
k=2 i=3
k=3 i=1
k=3 i=2
k=3 i=3
k=4 i=1
k=4 i=2
k=4 i=3
Nested individual while loop exercise

Write the class program that displays


loop control variable of inner and outer
for loops using two while loops
{Don’t submit}
Submit blackboard week5 by 4-10-
2023 linkname nest2whileNWk5
For loop to display 10 numbers
package nestfloop;
public class NestFLoop {

public static void main(String[] args) {


for(int k=10;k<=100;k=k+10) {
System.out.println("k= "+k);
for(int i=1;i<=10;i++){
//System.out.printf("\t%d",i);
System.out.print("\t"+(i*k));
}
System.out.println();
}
}
}
Output of above program
k= 10
10 20 30 40 50 60 70 80 90 100
k= 20
20 40 60 80 100 120 140 160 180 200
k= 30
30 60 90 120 150 180 210 240 270 300
k= 40
40 80 120 160 200 240 280 320 360 400
k= 50
50 100 150 200 250 300 350 400 450 500
k= 60
60 120 180 240 300 360 420 480 540 600
k= 70
70 140 210 280 350 420 490 560 630 700
k= 80
80 160 240 320 400 480 560 640 720 800
k= 90
90 180 270 360 450 540 630 720 810 900
k= 100
100 200 300 400 500 600 700 800 900 1000
Multiplication table program
package nestedfloop;
public class NestedFLoop {
public static void main(String[] args) {
for(int cl=1;cl<=10;cl++) {
System.out.print("\t"+cl);
}
System.out.println();
for(int k=1;k<=10;k=k+1) {
System.out.print(k);
for(int i=1;i<=10;i++){
//System.out.printf("\t%d",i);
System.out.print("\t"+(i*k));
}
System.out.println();
}
}
Output of above program
12 3 4 5 6 7 8 9 10
1 12 3 4 5 6 7 8 9 10
2 24 6 8 10 12 14 16 18 20
3 36 9 12 15 18 21 24 27 30
4 48 12 16 20 24 28 32 36 40
5 5 10 15 20 25 30 35 40 45 50
6 6 12 18 24 30 36 42 48 54 60
7 7 14 21 28 35 42 49 56 63 70
8 8 16 24 32 40 48 56 64 72 80
9 9 18 27 36 45 54 63 72 81 90
10 10 20 30 40 50 60 70 80 90 100
Group don’t submit BY 00-00-2024
Write program that displays calculates
and displays a 10*10 multiplication table
1 2 3 4 5 6 7 8 9 10
1 1 2 3 4 5 6 7 8 9 10
2 2 4 6 8 10 12 14 16 18 20
3 3 6 9 12 15 18 21 24 27 30
4 4 8 12 16 20 24 28 32 36 40
5 5 10 15 20 25 30 35 40 45 50
6 6 12 18 24 30 36 42 48 54 60
7 7 14 21 28 35 42 49 56 63 70
8 8 16 24 32 40 48 56 64 72 80
9 9 18 27 36 45 54 63 72 81 90
10 10 20 30 40 50 60 70 80 90 100

Inlude group members who participated


only.

Submit blackboard week9 by 6-7-2023


linkname multipTableWK9
Group submit BY 13-02-2024
Write program that calculates and displays a 10 by
10 power table CV^RV (CVRV) power table
power table 10 x 10
take columnvalue raise to power row value
1 2 3 4 5 6 7 8 9 10
1 1 2 3 4 5 6 7 8 9 10
2 1 4 9 16 25 36 49 64 81 100
3 1 8 27 64 125 216 343 512 729 1000
4 1 16 81 256 625 1296 2401 4096 6561 10000
5 1 32 243 1024 3125 7776 16807 32768 59049 100000
6
7 `
8
9
10

• Include only group members who participated.


• Submit blackboard week5 by 13-2-2024 linkname
multipTablePowWK5
Math.pow() function

Used to calculte powers of numbers


96 xy

Math.pow(x,y)

Example 84
double num1=8, pow=4, prod=0;
prod=Math.pow(num1, pow);
System.out.println(prod);
Exception handling
• Java has Exception handlers
• Java exception handling based on that of C++, but
designed to be more in line with object oriented
paradigm. Further more Java has predefined exceptions
while C++ doesn’t
• Java has several classes for exception handling. All
exceptions in java are descendant of Throwable class.
Throwable is great grand parent of all exception classes.
• Throwable has two predefined sub classes : Error and
Exception.
• The Error class and descendants handle errors throw by
Java Virtual machine such as running out of heap
memory.
• These exceptions are never thrown to user program and
should never be handled there.
When to use Exception handling

• Designed to process synchronous


errors which occur when a statement
executes. Synchronous means
happening at same time
• Common examples are out-of-range
array indices, arithmetic overflow,
division by zero, invalid method
parameters and thread exception
try catch statement blocks

try {
Statements that may cause exceptions
} catch(exceptiontype exceptionobj) {
Exception handling statements
} final {
This statement are always executed
}
Exception handling

Code can exit try catch in three ways:


1. Code completes inside try block
successful ends and program
execution continues
2. Code inside try block throws
exception and execution continues in
catch block
3. Code in try block encounter return
statement and returns to calling
program
Finally block in try

Code is executed irrespective of failure


of success of execution of code in try
block
Exception handling
• When there is an execution error normal behavior is to
terminate program and print message but java provides
a way of handling the error by catching it and handling it.
• Try catch block is used for exception handling
• Exception error that ones to handle with try catch.
try {
(statements computing statements which you want handle runtime errors)
Catch(exceptionclass objectname) {
(statements are for error)
}
Java exception handling
try and catch blocks

1. try block contain statements that may


cause exception
2. catch block indicates what would
happen is exception error occurred.
3. Variables in try block are local
4. If you want program to terminate use
System.exit(-1) in catch block, -1
indicates program terminates
abnormally
5. When error occurs java creates an
exception object.
Exception classes
6. All exception classes are subclasses
of Throwable see exception classes
hierarchy.
7. RuntimeException arithmetic
exception ArithmeticException –
divide by zero
8. RuntimeException array exceptions:
IndexOutOfArrayBounds – when
array index exceeds arraysize or
invalid index and
NullPointerException when its null
Exercise

Write a program that ask user to enter


a string and converts it to an integer.
If the string doesn’t contain numbers it
handle the exception.
NumberFormatException program
package numbexcept;
import java.util.Scanner;
public class NumbExcept {
public static void main(String[] args) {
System.out.println("number or text:");
Scanner input=new Scanner(System.in);
String str=input.nextLine();
try {
int a=Integer.parseInt(str);
} catch(NumberFormatException e) {
System.out.println("Not integer -
"+e.getMessage());
} } }
Exception object methods

getMessage() – returns message that


was passed to constructor when object
was created. E.g. System.out.println("Error -
"+e.getMessage());
toString() returns full name exception
concatenated with message returned
by getMessage() e.g. -
System.out.println("Error - "+e.toString());
printStackTrace() – prints a stack of
statements executed that lead to the
exception e.g. - e.printStackTrace();
Integer wrapper class

Its has a method parseInt() that is


used to covert a string into integer.
This is string has numbers.
Type-Wrapper classes
• Wrapper enable you to manipulate primitive types as
objects.
• Each primitive type boolean, byte, char, double,
float,int , long and short has corresponding type-
wrapper class: Boolean, Byte, Character, Double, Float,
Integer , Long and Short. All wrapper classes have
same name as primitive type but starts with capital
letter except int whose wrapper is Integer and char
wrapper class Character.
• All type wrapper classes are final classes so cannot be
extended.
• The type-wrapper classes are part of java.lang
package for example to Integer is imported as import
java.lang.Integer. [this not necessary as java.lang
package is included automatically]
• The wrapper classes have methods for manipulating
their primitive types
Java data types
1. Java has two categories of data types:
1. Primitive (there are 8 primitive data types)
2. Non primitive(complex types
Primitive – these are most basic types types are most
basic types: boolean, byte, char, double, float,int , long
and short
Not Primitive or object type: such as Arrays, String
etc.
• Except the 8 primitive types all other types are
object types (non primitive) – the primitive
types are usually stored using 32 or 64 bits.
• The primitive types have a simple structure and have
hardware support, so computing with primitive types is
usually faster.
• Non primitive types have a complex structure.
ArithmeticException Program
package arithexcept;
import java.util.Scanner;
public class ArithExcept {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("number or text:");
int num1, num2, sum;
num1=5; num2=0;
//while(num1>num)
try {
sum=num1/num2;
} catch(ArithmeticException e) {
System.out.println("Error - "+e.getMessage());
}
}

}
ArithmeticException looping Program
package arithexcept;
import java.util.Scanner;
public class ArithExcept {
public static void main(String[] args) {
int num1, num2, divtot;
num1=15; num2=-4; divtot=0;
while(num1>num2){
try {
divtot=num1/num2;
} catch(ArithmeticException e) {
System.out.println("Error - "+e.getMessage());
System.exit(-1); // in you comment program executin continues
}
System.out.println("result:"+divtot);
num2=num2+1;
}
}

}
ArithmeticException +NumberFormatException
package arnofmtexcept;
import java.util.Scanner;
public class ArnofmtExcept {
public static void main(String[] args) {
int num1=10,num2=0;
double prod=0;
String snum2;
Scanner ingisha=new Scanner(System.in);
System.out.println("Enter String");
snum2=ingisha.next();
try {
num2=Integer.parseInt(snum2);
prod=num1/num2;
} catch(ArithmeticException ea){
System.out.println("artithmetic Exception Message "+ea.getMessage());
} catch(NumberFormatException en){
System.out.println("Format Exception Message "+en.getMessage());
}
}
}
Types of exceptions
The two types of exceptions: checked and
unchecked exception
Checked exceptions must be checked in
programs otherwise program throws an error.
Unchecked errors the programmer can ignore
and no errors.
ArithmeticException and NumberFormatException
are unchecked exceptions. Unchecked
exceptions extend RuntimeException and
Error classes
ArrayIndexOutBoundsException – catches
errors when array index is beyond the range
of index
Types of exceptions
When method occurs in a method we
have two choices:
1 handle exception by catch block
2. Declare program method throws
exception
- Throwing exception means method is
one that throws exception
- If we can deal with exception
effectively in method catch is
better if we cannot throw.
Throws program
package susha;
public class Susha {

static int divide(int num1, int num2) throws


ArithmeticException {
int result=num1/num2;
return result;
}
public static void main(String[] args) {
int num1=6, num2=0;
int product=divide(num1, num2);
System.out.println("Result:" + product);
}
}
Throw program
public class ThrowExcept {
static void checkage(int ag) {
if(ag<18) {
throw new ArithmeticException("dont register");
} else {
System.out.println("register");
}
}
public static void main(String[] args) {
int age=12;
checkage(25);
}
}
Ìndividual class exercise
Write a java programs that ask user to enter salary calculates the tax to be
paid on salary and displays tax amount and salary-tax
Tax ranges
0-12000 - 0%
12001-20000 – 2%
20001-30000 - 5%
30001-50000 -10%
50001-70000 - 15%
70001-100000 - 25%
100001-150000 - 30%
150001 and above - 35%

Submit by end of class blackboard week4 link Taxcalc

Copy above program and Modify program so that it ask user to also enter
number of employees he/she wants to calculate tax and uses a for loop to
calculate and display tax
Submit by beginning of Monday 3-10-2022 next class blackboard week4 link
TaxcalcLoop
{method local and class
global variable
shadowing – program to
be made available later}
Exercise write a program with
two methods main() and swah().
Main calls swah and swah
returns a string when its ending
Both display location messages
in main, ndani swah
Main displays message returned
by swah
Class program
Class name PayrollGrossPay
write a program with two methods main()
and calcGPay() methods. Main calls
calcGPay() and calcGPay() will calculate
grosspay and return gross salary
Main displays message returned by
calcGPay()
Effects to observer:
• static
• Local and global variables
Write a program that uses
switch statement to determine
whether the range of integer
entered is with.
1-9
21-29
31-39

90-99
Not within 0-100 – displays “other”
package switcher;
import java.util.Scanner;
public class Switcher {
public static void main(String[] args) {
int inum=0, idiv=10;
Scanner sc=new Scanner(System.in);
boolean check=true;

while(check){
System.out.println("Enter integer inum1>0 and <100");
inum=sc.nextInt();

if(inum<=0){
System.out.println("Error \n");
check=true;
// System.exit(0); // causes normal program termination
//System.exit(n); n positive integer causes abnormal program
//termination
} else
check=false;
}
..program continued from previous page
switch(inum/idiv) {
case 0:
System.out.println("\n1-9");
break;
case 1:
System.out.println("\n10-19");
break;
case 2:
System.out.println("\n20-29");
break;
case 3:
System.out.println("\n30-39");
break;
default:
System.out.println("\nother");
}
}
}
System.exit()
System.exit(0);- causes
normal program
termination
System.exit(n); n positive
integer causes abnormal
program termination

You might also like