Ch1 Introduction - Advanced Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

Advanced Java

Programming

Chapter 1

Introduction to Java (Review)


by Abdo A. (MSc)

1
About java [to remind you ]
 Let's start learning of java from basic questions like
what is java, where it is used, what type of applications
are created in java and why use java.
 Java is a programming language and a platform.
 Java is a high level, robust, secured and object-oriented
programming language.
 Platform : Any hardware or software environment in which
a program runs, is known as a platform. Since Java has its
own runtime environment (JRE) and API, it is called
platform.
 According to Sun, about 3 billion devices run java

2
Java virtual machine
• The JVM manages system memory and
provides a portable execution environment
for Java-based applications
• JVM is a program whose purpose is to
execute other programs.
• The JVM has two primary functions:
1. to allow Java programs to run on any
device or operating system (known as the
"Write once, run anywhere" principle),
2. to manage and optimize program
memory
 The Java class loader is the part of the JVM that loads
classes into memory and makes them available for execution.
 The execution engine in the JVM executes the loaded class

3
JDK, JRE, JVM
• JRE is an installation package which provides
JDK=JRE + Development Tool environment to only run(not develop) the java
JRE=JVM+ Library Classes program (or application) onto your machine

JDK – Java Development Kit is Kit


which provides the environment to
develop and execute(run) the Java
program. JDK is a kit(or package)
which includes two things
1. Development Tools()
2. JRE
JDK is only used by Java Developers.

Whatever Java program you run using JRE or JDK goes into JVM
and JVM is responsible for executing the java program line by
line hence it is also known as interpreter. 4
What does JRE consists of?
JRE consists of the following components:
 Deployment technologies e.g. Java Plug-in.
 User interface toolkits e.g. AWT, Swing…
 Integration libraries e.g. Java Database Connectivity (JDBC), (RMI) …
 Lang and util base libraries, including lang and util, management, versioning …
 JVM

The Class Loader loads all


necessary classes needed for
the execution of a program.
At runtime the Byte Code is
loaded, checked and run by
the interpreter.
The interpreter has the
following two functions:
• Execute the Byte Code
• Make appropriate calls to
the underlying hardware
5
4 major type of applications
(using java programming)
1) Standalone Application
 Desktop application or window-based application.
 E.g. acrobat reader, media player, antivirus, etc.
2) Web Application
 An application that runs on the server side and creates dynamic page, is called web
application. Currently, servlet, jsp etc.
 E.g. javatpoint.com
3) Enterprise Application
 An application that is distributed in nature, such as banking applications etc.
 It has the advantage of high level security, load balancing and clustering.
4) Mobile Application
 An application that is created for mobile devices.
 Currently Android and Java ME are used for creating mobile applications.
Others
 Smart Card

 Robotics
 Games, etc. 6
Java Platforms / Editions
There are 4 platforms or editions of Java:
1. Java SE (Java Standard Edition)
 It is a Java programming platform. It includes Java programming APIs such as
java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes core
topics like String, Regex, Exception, Multithreading, I/O Stream,
Networking, AWT, Swing, Collection, etc.
2. Java EE (Java Enterprise Edition)
 It is an enterprise platform which is mainly used to develop web and
enterprise applications. It is built on the top of the Java SE platform.
 It includes topics like Servlet, JSP, Web Services, EJB, etc.
3. Java ME (Java Micro Edition)
 It is a micro platform which is mainly used to develop mobile applications.
4.JavaFX
 It is used to develop rich internet applications. 7
Objects
 An object is a software bag of related state and behavior.
 Software objects are often used to model the real-world objects that you find
in everyday life.
 Real-world objects share two characteristics: state and behavior
 An object stores its state in fields (variables in some programming languages)
and its behavior through methods (functions in some programming
languages).
 Methods operate on an object's internal state and serve as the primary
mechanism for object-to-object communication.
 Hiding internal state and requiring all interaction to be performed through
an object's methods is known as data encapsulation — a fundamental
principle of object-oriented programming 8
What Is a Class?
 A class is a blueprint or prototype from which objects
are created.
 This section defines a class that models the state and
behavior of a real-world object.
 It intentionally focuses on the basics, showing how
even a simple class can cleanly model state and
behavior.

class Square {
//field, and method declarations
}
9
Instantiation
 In the real world, you'll often find many individual objects all
of the same kind.
 There may be thousands of other Squares in existence, all of
the same make and model.
 Each Square was built from the same set of blueprints and
therefore contains the same components.
 In object-oriented terms, we say that your Square is an
instance of the class of objects known as Squares.
 A class is the blueprint from which individual objects are
created.

10
Components of Class Declarations
 In general, class declarations can include these components, in
order:
 Modifiers such as public, private, and a number of others that you
will encounter later.
 The class name, with the initial letter capitalized by convention.
 The name of the class's parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
 A comma-separated list of interfaces implemented by the class, if
any, preceded by the keyword implements.
 A class can implement more than one interface.
 The class body, surrounded by braces, {}.

11
Declaring Member Variables
There are several kinds of variables:
 Member variables in a class—these are called fields.

 Variables in a method or block of code—these are called local

variables.
 Variables in method declarations—these are called parameters.

public int side;


public String color;
public void decreasesizebyfive() {
int decrementa = 5;
side -= decrementa;
}
public void changecolor(String newcolor) {
color = newcolor; }
12
Variable Naming Conventions
 Variable names are case-sensitive.
 A variable's name can be any legal identifier — an unlimited-
length sequence of Unicode letters and digits, beginning with a
letter, "$", or "_"
 White space is not permitted.
Types
 All variables must have a type.
You can use primitive types such as int, float, boolean, etc.

13
Access modifiers:
 used to determine the level of access to class members.
 Private: Variables or methods declared with access
modifier private are accessible only to methods of the class
in which they are declared.
 Public: Variables or methods declared public are accessible where
ever the program has a reference to an object of the class members.
 Protected: Offers an intermediate level of access between public and
private. A super class’ protected members can be accessed by
members that super class, by members of any classes derived from
that superclass and by members of other classes in the same package.
Access is within the package and derived classes.
14
Method Declarations
 method declarations have six components, in order:
 Modifiers
public void setCadence(int newValue) {
 Return type
cadence = newValue;
 Method name
}
 Parameter
 Exception list  Modifier public
 Method body  Return type void
 Method Name setCadence
 Parameter int newValue
 Method Body cadence = newValue;

15
Features of java: Encapsulation
 It separates the implementation details from the interface.
 Object orientation uses classes to encapsulate (i.e. Wrap together)
data and methods.
 It is the mechanism by which implementation details are hidden.
 This is done through security and visibility.
 The interface (method) is visible to the entire world, and we can hide
other variables and methods so that they cannot be accessed.
 Methods are provided to allow to variables (State) and to change the
state.
 The only access to the object’s variables is through method calls to
check their state and there is no direct access to object’s variables.

16
Inheritance
 Inheritance in Java is a mechanism in which one
object acquires all the properties and behaviors of a
parent object. It is an important part of OOPs
 Generalization is a relationship between a class and one
or more refined versions of it.

17
Polymorphism
 Polymorphism means many forms.
 A single object can refer the super class or sub-class depending
on the reference type which is called polymorphism.
 Polymorphism is applicable for overriding and not for
overloading.

 What is the difference b/n Overloading &


overriding?

18
Overloading Methods
 If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
 If we have to perform only one operation, having same name of the
methods increases the readability of the program.• Same method name
• Different argument type
 Advantage of method overloading • May have different return types
 Method overloading increases the readability of the program.
2 ways to overload the method in java
 By changing number of arguments class Adder{
static int add(int a,int b){
 By changing the data type
return a+b;}
class Adder{ static int add(int a,int b,int c){
static int add(int a, int b){return a+b;} return a+b+c;}
static double add(double a, double b){ }
return a+b; }} classTestOverloading1{
classTestOverloading2{ public static void main(String[] args) {
public static void main(String[] args){ System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11)); System.out.println(Adder.add(11,11,11));
System.out.println(Adder.add(12.3,12.6)); }} }} 19
Overriding Methods
 Going from the general cases to its specializations, some behaviors might be
implemented differently.
 Whenever there is such a difference in implementation of behavior and the
base class implementation is wrong in the subclass’s context, we use
method overriding. • Method name should be same
• Argument should be same
• Return type also should be same

 The version of the method defined by the superclass will be hidden.


//Creating a parent class.
class Vehicle{ //defining a method
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){
System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();
obj.run(); //calling method } } 20
Abstract Classes and Methods
Abstract Classes is a class that you define represents an
abstract concept.
 In object-oriented programming, you may want to model an
abstract concept without being able to create an instance of it.

 There are 2 ways to model abstract concept(i.e. abstract


class and interface)

21
Abstract Class &Java Interface
 What is an Abstract method and an Abstract class?
 Abstract Methods
 Methods that do not have implementation (body)

 It use the abstract keyword without { }

 For example public abstract void someMethod();

 Abstract Class is a class that contains one or more abstract methods

 An abstract class cannot instantiated

// You will get a compile error on the following code


MyAbstractClass a1 = new MyAbstractClass();
 Another class (Concrete class) has to provide implementation of abstract
methods
– Concrete class has to implement all abstract methods of the abstract
class in order to be used for instantiation
– Concrete class uses extends keyword 22
example :

23
Extending an Abstract Class
 When a concrete class extends the LivingThing abstract
class, it must implement the abstract method walk(), or
else, that subclass will also become an abstract class, and
therefore cannot be instantiated. For example

24
When to use Abstract Methods
& Abstract Class?
 Abstract methods are usually declared where two or more
subclasses are expected to fulfill a similar role in different
ways through different implementations.

 These subclasses extend the same Abstract class and provide


different implementations for the abstract methods

 Use abstract classes to define broad types of behaviors at the


top of an object-oriented programming class hierarchy, and
use its subclasses to provide implementation details of the
abstract class.

25
What is an Interface?
 It defines a standard and public way of specifying the behavior of
classes – Defines a contract
 All methods of an interface are abstract methods
– Defines the signatures of a set of methods, without the body (just
set of method signatures without any implementations.)
 A concrete class must implement the interface (all the abstract
methods of the Interface)
 It allows classes, regardless of their locations in the class hierarchy, to
implement common behaviors Example:
 No need to say abstract modifier for each method since it assumed.

26
Interface example

27
Why do we use Interfaces?
 Reason #1
 To make public an object's programming interface (functionality of the
object) without publicizing its implementation (i.e. concept of encapsulation)
 The implementation can change without affecting the caller of the interface
 The caller does not need the implementation at the compile time
 It needs only the interface at the compile time
 During runtime, actual object instance is associated with the interface type
 Reason #2
 To have unrelated classes implement similar methods (behaviors)
 They are not related through inheritance
 You want both to implement comparison methods

Reason #3
 To model multiple inheritance

– A class can implement multiple interfaces while it can extend only one class28
Interface vs. Abstract Class
 All methods of an Interface are abstract methods while
some methods of an Abstract class are abstract methods
– Abstract methods of abstract class have abstract modifier
 An interface can only define constants while abstract class
can have fields.
 Interfaces have no direct inherited relationship with any
particular class, they are defined independently.
 Interfaces themselves have inheritance relationship among
themselves.

29
Interface vs. Class: Differences
 The methods of an Interface are all abstract methods
– They cannot have bodies
 You cannot create an instance from an interface. For

example:
PersonInterface pi = new PersonInterface(); //ERROR!
 An interface can only be implemented by classes or

extended by other interfaces.

30
When to use an Abstract Class
over Interface?
 For non-abstract methods, you want to use them when you
want to provide common implementation code for all sub-
classes
– Reducing the duplication
 For abstract methods, the motivation is the same with the
ones in the interface – to impose a common behavior for
all sub-classes without dictating how to implement it
 Remember a concrete can extend only one super class whether
that super class is in the form of concrete class or abstract class

31
Question

 When to use an Interface over Abstract Class?

32
Exception Handling
Many things can go wrong when dealing with files.
 requested input file does not exist
 input file has invalid data
 output file unavailable
Exception Handling
 A program must be able to handle error situations
gracefully when they occur at runtime.
 Java provides exception handling for this purpose.
 A program should be able to handle error situations that
might occur at runtime.
 Error situations can be divided into two main categories:
 Programming errors. For example, using an invalid index to access
an array element, attempting to divide by zero, calling a method
with illegal arguments or using a reference with the null value
to access members of an object.
 Runtime environment errors. For example, opening a file that does
not exist, a read or write error when using a file, or a network
connection going down unexpectedly.
34
Exception Handling …
 Programming errors are error situations that occur because of
logical errors in the program, while runtime environment errors
are errors over which the program has little control.
 A program must be able to handle both kinds of errors.
 Ideally, programming errors should not occur, and the program
should handle runtime environment errors gracefully.
 An exception in Java signals that an error or an unexpected
situation has occurred during program execution.
 Exception handling is the mechanism for dealing with such
situations.
 It is based on the “throw and catch” principle. An exception is
thrown when an error situation
35
Advantage of Exception Handling
 The core advantage of exception handling is to maintain
the normal flow of the application.
 Exception normally disrupts the normal flow of the
application that is why we use exception handling.
 There are mainly two types of exceptions: checked and
unchecked where error is considered as unchecked
exception.
 Checked exceptions are checked at compile-time
 Unchecked exception are checked at run-time

36
Checked exceptions …
 Checked exceptions are checked at compile-time. E.g.
 ClassNotFoundException Signals an attempt to load a class during
execution, but the class cannot be found.
 java.io.IOException Signals an error during reading and writing of
data. For example, the read() methods in the interface InputStream and
the write() methods in the interface OutputStream throw this
exception.
 java.io.EOFException Signals unexpected end of input. For example,
the read() methods in the interface InputStream throw this exception.
 java.io.FileNotFoundException Signals an attempt to refer to a file
that does not exist. For example, the constructors in the classes
FileInputStream, FileOutputStream and RandomAccessFile throw this
exception, if the file cannot be assigned
37
Unchecked exceptions
 Unchecked exceptions are exceptions typically concerning
unforeseen errors (e.g. programming errors).
 In contrast to checked exceptions, the compiler does not
check whether unchecked exceptions can be thrown.
 but it must then face the consequences if the program is
terminated due to an unchecked exception.
 The best solution: correct the cause of the errors in the program so
that they do not occur during program execution.
 Since the compiler ignores unchecked exceptions and a
method is not forced to handle them, such exceptions are
usually not specified in the throws clause of a method.
38
Unchecked exceptions…
 In short the classes that extend RuntimeException are known as
unchecked exceptions
 It checked at runtime e.g.
o NullPointerException Signals an attempt to use a reference that
has the value null, i.e. the reference does not refer to an object.
For example, the expression new String(null) throws this
exception, since the parameter has the value null, instead of being
a reference to an object.
o ArithmeticException Signals an illegal arithmetic operation, for
example integer division with 0, e.g. 10/0.
o ClassCastException Signals an attempt to convert an object’s
reference value to a type to which it does not belong.
 For example: Object ref = new Integer(0); String str = (String) ref; //
Integer is not String.
39
Unchecked exceptions…
 IllegalArgumentException Signals an attempt to pass an
illegal actual parameter value in a method call.
 NumberFormatException Indicates a problem converting a
value to a number, for example, an attempt to convert a
string with characters that cannot constitute a legal integer,
e.g. Integer.parseInt("4u2").
ArrayIndexOutOfBoundsException Indicates an index
value is not valid. The index value in an array is either less
than 0 or greater than or equal to the array length, e.g.
array[array.length].
 StringIndexOutOfBoundsException Indicates an index
value is not valid. The index value in a string is either less
than 0 or greater than or equal to the string length, e.g.
str.charAt(-1).
 Error -- Error is irrecoverable e.g. OutOfMemoryError,
VirtualMachineError, AssertionError etc.
40
Java Exception Handling Keywords
 Java Exception Handling Keywords There are 5 keywords
used in java exception handling.
1. Try 2. catch 3. Finally 4. throw 5. throws
o Java try block is used to enclose the code that might throw an
exception. It must be used within the method. Java try block must be
followed by either catch or finally block.
o Java catch block is used to handle the Exception. It must be used after
the try block only. You can use multiple catch block with a single try.
1. try{
2. //code that may throw exception
3. } catch(Exception_class_Name ref){}
Syntax of try-finally block
1. try{
2. //code that may throw exception
3. }finally{} 41
 In internal working of java try-catch block the JVM firstly
checks whether the exception is handled or not.
 If exception is not handled, JVM provides a default exception
handler that performs the following tasks:
 Prints out exception description.
 Prints the stack trace (Hierarchy of methods where the

exception occurred).
 Causes the program to terminate.

 But if exception is handled by the application programmer,


normal flow of the application is maintained i.e. rest of the
code is executed. If you have to perform different tasks at the
occurrence of different Exceptions, use java multi catch
block.

42
 Let's try to understand the problem if we don't use try-catch block.

public class Testtrycatch1{


public static void main(String args[]){
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}}
 Solution by exception handling Let's see the solution of above problem
by java try-catch block.
public class Testtrycatch2{
public static void main(String args[]){
try{ int data=50/0;
}catch(ArithmeticException e) {

System.out.println(e); }
System.out.println("rest of the code..."); } }

43
 At a time only one Exception is occured and at a time only one
catch block is executed. All catch blocks must be ordered from most
specific to most general i.e. catch for ArithmeticException must
come before catch for Exception.
 Java finally block is a block that is used to execute important
code such as closing connection, stream etc. Java finally
block is always executed whether exception is handled or
not. Java finally block follows try or catch block.
 Finally block in java can be used to put "cleanup" code such
as closing a file, closing connection etc. Look at the
following examples their difference is based on data value
and type of exception
44
Java throw and Throws keyword
 Java throw keyword -is used to explicitly throw an
exception. We can throw either checked or uncheked
exception in java by throw keyword. The throw keyword is
mainly used to throw custom exception. We will see custom
exceptions later. The syntax of java throw keyword is given
below.
throw exception;
 Let's see the example of throw IOException.
throw new IOException("sorry device error);
Java throws keyword - is used to declare an exception. It
gives information to the programmer that there may occurs an
exception so it is better for the programmer to provide the
exception handling code so that normal flow can be
maintained.
45
 Exception Handling is mainly used to handle the checked
exceptions. If there occurs any unchecked exception such
as NullPointerException, it is programmers fault that he is
not performing checkup before the code being used.

 Advantage of Java throws keyword - Now Checked


Exception can be propagated (forwarded in call stack). It
provides information to the caller of the method about the
exception.
 If you are calling a method that declares an exception,

you must either caught or declare the exception.


46
There are many differences between throw and throws
keywords.

47
What is the difference between checked and unchecked
exceptions?

48

You might also like