4.CoreJavaProgramming Day4
4.CoreJavaProgramming Day4
Presented By
Dr. Eman Hesham, DBA.
Agenda
A. The History and Evolution of Java
B. An Overview of Java
C. Data Types, Variables and Arrays
D. Operators, Control Statements and String Handling
E. Modifiers, Access Specifiers, Packages and Interfaces
F. Wrapper Classes, Autoboxing and Inner Classes
G. Exception Handling
H. Generics and Lambda Expressions and Method Reference
I. Java Stream API
J. Java Collections
K. Multi-Threading in Java
Agenda
A. The History and Evolution of Java
B. An Overview of Java
C. Data Types, Variables and Arrays
D. Operators, Control Statements and String Handling
E. Modifiers, Access Specifiers, Packages and Interfaces
F. Wrapper Classes, Autoboxing and Inner Classes
G. Exception Handling
H. Generics and Lambda Expressions and Method Reference
I. Java Stream API
J. Java Collections
K. Multi-Threading in Java
Lesson 7
Exception Handling
4
What are Exceptions?
Exceptions are events that occur during the execution of programs that disrupt the normal flow of instructions (e.g.
divide by zero, array access out of bound, etc.).
In Java, an exception is an object that wraps an error event that occurred within a method and contains:
Information about the error including its type
System errors:
FileNotFoundException, IOException, SocketTimeoutException
Programming errors:
NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException
Checked vs. Unchecked Exceptions
Errors and RuntimeExceptions are unchecked — that is, the compiler does not enforce (check) that
you handle them explicitly.
Methods do not have to declare that they throw them (in the method signatures).
It is assumed that the application cannot do anything to recover from these exceptions (at
runtime).
All other Exceptions are checked — that is, the compiler enforces that you handle them explicitly.
Methods that generate checked exceptions must declare that they throw them.
Methods that invoke other methods that throw checked exceptions should handle them (they can
be reasonably expected to recover) .
Checked vs. Unchecked Exceptions
https://www.protechtraining.com/content/java_fundamentals_tutorial-
exceptions
Handling Exceptions
Example
Considerations Regarding Exceptions
If several method calls throw different exceptions,
2. Put them all inside the same try block and then
3. Put them all inside the same try block and then
then you must take care not to handle a parent exception before a
child exception
Or:
try { ...... }
catch (FileNotFoundException | IOException e) {
System.err.println(“...................“);
}
Declaring, Throwing, and Catching Exceptions
}
Throwing Exceptions
When the program detects an error, the program can create an instance of an appropriate exception type
and throw it. This is known as throwing an exception. Here is an example,
if (newRadius >= 0)
radius = newRadius;
else
}
Catching Exceptions
try {
obj.setRadius(); // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
}
Catch or Declare Checked Exceptions
...
}
Catch or Declare Checked Exceptions
Java forces you to deal with checked exceptions.
If a method declares a checked exception (i.e., an exception other than Error or
RuntimeException), you must invoke it in a try-catch block or declare to throw the
exception in the calling method.
For example, suppose that method p1 invokes method p2 and p2 may throw a
checked exception (e.g., IOException), you have to write the code as shown in (a)
or (b).
(a) (b)
Exception Propagation
public class Example3
public static void main(String[] args)
{ Example3 ref=new Example3();
try {
Method Call Propagation
ref.myMethod1();
}catch (Exception ex) {
ex.printStackTrace();
Propagation
Exception
}
}
public void myMethod1() throws Exception
{
myMethod(5);
}
public void myMethod(int x) throws Exception
{
if (x>0) throw new Exception("Exception in
method");
} }
Example: Create A new Exception
You CAN’T throw any different exceptions other than the exception(s)
declared in the method that you are attempting to override
Agenda
A. The History and Evolution of Java
B. An Overview of Java
C. Data Types, Variables and Arrays
D. Operators, Control Statements and String Handling
E. Modifiers, Access Specifiers, Packages and Interfaces
F. Wrapper Classes, Autoboxing and Inner Classes
G. Exception Handling
H. Generics and Lambda Expressions and Method Reference
I. Java Stream API
J. Java Collections
K. Multi-Threading in Java
Lesson 8
Generics and Lambda Expressions and Method Reference
28
Generic
Programming
Introduction
Why generic Programming
• Generic programming means writing code that can be reused for objects of many different
types.
• Generic classes are desirable because they let you write code that is safer and easier to read
than code littered with Object variables and casts.
• Generics are particularly useful for collection classes, such as the universal ArrayList.
• Generic classes are—at least on the surface—similar to templates in C++. In C++, as in Java,
templates were first added to the language to support strongly typed collections.
Why generic Programming
• It is important to understand that Java has always given you the ability to
create generalized classes, interfaces, and methods by operating through
references of type Object.
• Because Object is the superclass of all other classes, an Object reference
can refer to any type object.
• In pre-generics code, generalized classes, interfaces, and methods used
Object references to operate on various types of objects.
• The problem was that they could not do so with type safety.
Why generic Programming
In other words, the term generics means parametrized types.
Parameterized types are important because they enable you to create
classes, interfaces, and methods in which the type of data upon which they
operate is specified as a parameter.
Using generics, it is possible to create a single class, for example, that
automatically works with different types of data.
A class, interface, or method that operates on a parameterized type is
called generic, as in generic class or generic method.
The Advantages of Type Parameters
• Before generic classes were added to Java, generic
programming was achieved with inheritance.
• The ArrayList class simply maintained an array of Object
references:
public class ArrayList // before generic classes
{
private Object[] elementData;
. . .
public Object get(int i) { . . . }
public void add(Object o) { . . . }
}
The Advantages of Type Parameters
• This approach has two problems. A cast is necessary whenever
you retrieve a value:
ArrayList files = new ArrayList();
. . .
String filename = (String) files.get(0);
• Moreover, there is no error checking. You can add values of
any class:
files.add(new Text(". . ."));
The Advantages of Type Parameters
The call in the previous slide compiles and runs without error.
Generics offer a better solution: type parameters. The ArrayList class now has a type
parameter that indicates the element type:
This makes your code easier to read. You can tell right away that this particular array list
contains String objects.
The Advantages of Type Parameters
The compiler can make good use of the type information too. No cast is required for calling
get. The compiler knows that the return type is String, not Object:
String filename = files.get(0);
The compiler also knows that the add method of an ArrayList<String> has a parameter of
type String.
That is a lot safer than having an Object parameter. Now the compiler can check that you
don’t insert objects of the wrong type. For example, the statement
will not compile. A compiler error is much better than a class cast exception at runtime.
Lab Exercises
Lab Exercise
• Create your own exception class.
• Write down two other classes:
• the first will contain three methods throwing your newly
created exception class
• the second class will be calling the methods that throws
exception using the try-catch-finally block.
38
Lab Exercise
• Create a base class named Shape that contains one abstract
method draw().
• Create two concrete classes (Rectangle and Circle) that extend
Shape
• Create a test class that defines a method that accepts a list
that contains only child classes of shape
• Test your method by creating two ArrayList of Rectangle and
shapes and pass them to the generic method
Lab Exercise
• Create a generic interface that could be used to represent
complex numbers
• Create some generic methods that represent basic arithmetic
operation on complex.