Intro to the Java Programming Language Topics covered: Basic Programming Concepts: Variables, Data Types, Operators & Expressions, Flow Control, Arrays Classes & Objects

Download 159.9 Kb.
Size159.9 Kb.
Intro to the Java Programming Language
Topics covered:

1. Basic Programming Concepts: Variables, Data Types, Operators & Expressions, Flow Control, Arrays 2. Classes & Objects

2.1. The public and private modifiers

2.2. Packages (the package and import statements)

2.3. Constructors

2.4. The static modifier

2.5. Inheritance (the extends clause and protected modified)

2.6. Nested classes

2.7. Abstract methods and classes (the abstract modifier)

2.8. Interfaces (the implements clause)

2.9. GUIs

2.10. The final modifier

2.11. Exception Handling
Java is a simple and yet powerful Object Oriented Programming (OOP) language and it is in many respects similar to C++.
1. Basic Programming Concepts: Variables, Data Types, Operators & Expressions, Flow Control and Arrays
A program is a set of instructions that manipulate some data. Programs store and access data from memory using variables. So, a variable can be thought of as a memory location that can store data.
Each variable has a name, a type and a value;

  • the name is used to refer to that memory location (instead of an address)

  • the type is used to specify what kind of values can be stored in that memory location (it indirectly specifies the size of that memory location)

  • the value is the actual data stored in that memory location.

As C and C++, Java is a strongly-typed language, meaning that the type of a variable MUST be declared before that variable can be used. Data can be stored in a variable using the assignment operator "=". The Java syntax for variable declaration and assignment is similar to the C and C++ syntax.

Syntax for variable declaration: variable_type variable_name;
Syntax for variable assignment: variable_name = expression;

int noOfCourses; //variable declaration

noOfCourses = 3; //variable assignment

long noOfStars = 4147483648; //variable declaration and initialization

double gpa, height; //two variable declarations

gpa = 2.3; //variable assignment

height = 7.2; //variable assignment

boolean easy = true; //variable declaration and initialization


  1. Every Java statement must end with a semicolon ";"

  2. Java is case sensitive ("gpa" is different than "Gpa" and "GPA")

The name of a variable can be any identifier that is not a keyword.

- identifier = a series of letters, digits and underscores that does not begin with a digit

- keyword = word reserved by Java for specific use (e.g., int, long, for, while, if, …)

The type of a variable can be a primitive type or a class type. Programmers can define there own class types and/or use existing class types from the Java class library. Java supports 8 primitive types, as follows:

Primitive Types

Type Name



Range of Possible Values

Numeric types

Integer types


1 bytes

-128 to 127


2 bytes

-32,768 to 32, 767


4 bytes

-2,147,483,648 to 2,147,483,647


8 bytes

-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Floating point types


4 bytes

approx. 10-38 to 1038


8 bytes

approx. 10-308 to 10308

Non-numeric types


2 byte

any single character on the keyboard


1 bit*

true, false

The fixed values assigned to variables of primitive types are called literals (= any number or text that represents a value). For example:

37 - int literal

37l - long literal (notice the "l" after 37)

35.5 - double literal

35.5f - float literal (notice the "f" after 35.5)

3.5e2 - double literal (scientific notation or floating-point notation) = 3.5*102

'a' - char literal

Basic operators supported by Java:

  • Arithmetic operators: +, -, *, /, %

  • Increment/decrement operators: ++, --

  • Relational operators: ==, !=, <, <=, >, >=

  • Boolean operators: &&, ||, !

  • Assignment operators: =





+, - , ++, --, !


Highest 1


*, /, %





+ -


< <= > >=



== !=










Lowest 8



switch (expression)


case value1:

code to be executed if expression equals value1

case value2:

code to be executed if expression equals value2



default: // optional

code to be executed if expression is different

from value1, value2, ...

ava supports the following flow control structures:

  • Branches: if, switch

  • Loops: while, do-while, for


frame4 frame5 frame6
The break statement can be used with switch statements and with loops. It terminates the enclosing statement (switch, while, do or for loop) and continues executing the code immediately following the enclosing statement.
The continue statement can be used in loops to terminate the current iteration of a loop and jump to the next iteration. This behavior is similar to that of a break statement, but rather than terminating the loop completely, the continue statement causes a jump to evaluating the loop condition and iterating again through the loop if the condition is still true.

int sum = 0;

int n = 5;

while (n>0)


sum = sum + n;

n = n - 1;


int sum = 0,

n = 5;



sum = sum + n;

n = n - 1;

} while (n>0);

  1. If a break or continue statement is not enclosed by a switch, while, do or for loop, a compilation error will occur.

  2. If a break statement is absent from the end of a case clause, execution will continue with the statements of the next case label (if any).

Arrays are collections of items of the same type (aka, the base type of the array). Arrays can be stored in array variables. Array variables are declared as follows:

base_type[] array_name;

The base_type can be any primitive or class type.

Example: declaring an array variable named grades for storing the final grades for all the students in a class

char[] grades;


In Java, array variables and variables that are NOT of primitive types must be explicitly allocated space in memory (after they are declared) using the operator new. This operator is followed by the amount of space to be allocated (expressed in terms of a data type).


grades = new char[10]; //will allocate space for 10 characters for the array variable grades

The elements of an array can be accessed using the indexing operator [].

grades[0] = 'A'; grades[1] = 'D';

grades[2] = 'A'; grades[3] = 'B';

grades[4] = 'B'; grades[5] = 'C';

grades[6] = 'A'; grades[7] = 'F';
Remark: for loops are commonly used to step through all the elements of an array
frame12 frame13

frame14 frame15

2. Classes and Objects
The basic module/unit in Java (and in OOP generally) is the class. A class is similar to a C struct, except that the latter consists only of data fields, while the former has both data fields and functions, called methods. Structures and classes allow you to create your own data types.
C structure Java class

frame16 frame17
Note that String is a pre-defined Java class that can be used to represent strings/arrays of characters.
frame18 frame19



  1. Methods of a class can be accessed/invoked just like the data fields, that is, using the dot "." operator.


  1. Variables of a class type are called objects. Therefore, we will refer to the variable myCar as an object of the class Car (instead of variable of type Car).

2.1. The public and private modifiers
When defining structures, you as a designer of a new type, have no control over the values assigned to the fields of the variables of that type. For example, someone using your Car struct type can assign "invalid" data to the fields of that structure:
struct Car myCar;

myCar.noDoors = 70;

myCar.color = "BYE";

myCar.year = 100;

myCar.mileage = -10000;
Using classes you can restrict access to the data fields of a class and allow them to be modified only through the class methods (that can be implemented to check data validity before assigning it to a field). This can be done using the public and private modifiers to mark each member of a class as private or public.

  • Private class members can only be referenced/accessed within the class (that is, within the definitions of methods of that class)

  • Public members can be referenced/accessed from any other class

Therefore, to restrict access to the data fields of a class we must declare them as private. In addition, we have to make sure to provide public methods that can be used to manipulate/access (in a controlled manner) the private data fields.

To complete the definition of the Car class we need to provide an implementation for the two methods paint() and printToString().

Note that in the implementation of method paint(), before changing the color field of a car object (calling this method) we first check if newColor is a valid color (for simplicity we assume here that only "BLUE", "RED" and "GREEN" are valid colors).
Method printToString() simply concatenates the values of all the data fields of a car object in a String variable and returns it, so that it can be displayed when needed.

Now, let’s modify our “Hello Android!” application such that it uses the above Car class. Specifically, it will create a new Car object, change its color to "BLUE" and then display all the information about that object.


Let’s run this application (consisting of two classes: HelloAndroid and Car) in Eclipse. Modify your HelloAndroid class as indicated above. For now, put the Car class definition in the same file as the HelloAndroid class.


  1. You can only have one public class in a file (and the name of that class must be the same as the name of the file). That is why class Car in file is not declared as public.

  2. In general, it is recommended that each class is defined in its own file. This makes the code cleaner and easier to read and maintain.

Run the application (by going to Run Run) and notice its output. Note that only the color data field of the myCar object has been assigned a value (by the statement myCar.paint("BLUE");). The other data fields were not assigned any values and they were initialized by default with 0 (the numeric fields) and null (the fields of type String).

2.2. Packages
To make classes easier to find and use, to avoid naming conflicts, and to control access, programmers bundle groups of related classes into packages. Java packages are similar to namespaces in C++.
To create a package, you choose a name for the package and put a package statement with that name at the top of every source file that contains the classes that you want to include in the package. The package statement must be the first line in the source file. There can be only one package statement in each source file, and it applies to all classes in the file. If you do not use a package statement, your classes end up in a default unnamed package.
Packages provide access protection in addition to name space management. If a class member or class does not have an access modifier (such as public or private) it will be assigned implicitly the package modifier, meaning that it can be accessed from any class in the same package.


Class Members



Can only be accessed from the class that defines them



Can be accessed from the class that defines them and any other class in that same package

Can only be accessed from any class in the same package


Can be accessed from anywhere

Can be accessed from anywhere

Let’s move our Car class into a different file ( then make it public and put it in a package called myPackage.

Right click on the "src" folder and select New Class.

Fill in the class name Car and the package name myPackage and click 'Finish'.

Then cut-and-paste the implementation of the Car class from the file.

Now, in order to access the Car class (from the myPackage package) you have to do one of the following:

  1. refer to the Car class by its full name, including the package name


  1. or, import the class Car from the myPackage package

  2. or, import the entire myPackage package

Then you can refer to the Car class by its simple name.
To import a package or a specific class form a package into the current file, put an import statement at the beginning of the file before any class definitions but after the package statement, if there is one. To import all the class contained in a particular package, use the import statement with the asterisk '*' wildcard character.

2.3. Constructors
A constructor is special class method whose main purpose is to initialize the data fields of an object when the object is created. Constructors are automatically called when an object of the class is created (using the new operator). A constructor’s name must be the same as the name of the class. A constructor cannot return a value, so no return type (not even void) is used in defining a constructor.
Constructors, like any other methods, can have one or more parameters. A constructor with no parameters is called a default constructor. The default constructor should initialize all data fields to some default values.
For example, the default constructor for the Car class could initialize the make, model and color with the value "Unknown", the year with 2009, mileage with 0 and doors with 4.
When an object of the Car class is created (using new)

the default constructor is automatically invoked:

Car myCar = new Car();

It is a good idea to always include a default constructor even if you do not want to initialize the data fields. If a class does not have a default constructor, one will be generated automatically. This constructor will initialize all data fields to zeros or null (as seen in our last example ran in Eclipse).

Like any other methods, constructors can be overloaded.

Overloading a method’s name means using the same name for multiple method definitions. To be able to distinguish between calls to these methods (that have the same name) they must have:

  • Either different number of parameters

  • Or at least one parameter must differ in type

Overloading example: method name average is overloaded with 3 definitions:

double average(double n1, double n2) {return ((n1 + n2) / 2);}

double average(int n1, int n2) {return ((n1 + n2) / 2);}

double average(int n1, int n2, int n3) {return ((n1 + n2 + n3) / 3);}

When method average is invoked, the number and type of the arguments in the call will determine which of the 3 definitions is invoked.

average (2, 3); //will invoke the second definition

average (4, 1, 7); //will invoke the third definition

average (5.6, 1.3); //will invoke the first definition
Different returned types is not enough to differentiate between two method definitions that have the same name!

This is an example of incorrect function overloading:

double average(double n1, double n2) { return ((n1 + n2) / 2);}

int average(double n1, double n2) { return (int)((n1 + n2) / 2);}
Overloading allows us to have multiple constructors (with different number or types of parameters) in a class. The parameters in constructors are used for passing values to be used for initializing the data fields.
Example: a constructor for that Car class that has 6 parameters, each one for initializing one of the data fields.

Such constructor is invoked as follows:

Car yourCar = new Car("Porsche", "Cayman", 2007, "Blue", 10000, 2);
Other constructors for the Car class can be defined. For example, if you want to allow a user to create Car objects when only the make and model of a car are know, then you should define a constructor with only two parameters (for initializing only those two data fields). The remaining fields should be initialized to some default values.
Such constructor is invoked as follows:

Car myNextCar = new Car("Porsche", "Cayman");
Let’s test the above constructors by modifying the main method in the HelloAndroid class as follows:

Remark: If a constructor for a given class is non-public, then only the class itself can create objects of that class.
2.4. The static modifier
When a number of objects are created from the same class, they each have their own distinct copies of the data fields of the class. In the case of the Car class, the data fields are make, model, year, color, mileage and noDoors. Each Car object has its own values for these fields, stored in different memory locations.
Sometimes, you want to have fields that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every object of the class shares the static field, which is in one fixed location in memory. Any object can change the value of the static field, but static fields can also be manipulated without creating an object of the class. Specifically, static class members can be accessed using the class name (instead of an object’s name).


Remark: It is recommended that you refer to static fields using the class name (Car.noOfCars) instead of an object’s name (myCar.noOfCars). This makes it clear that they are static fields.

For example, suppose you want to create a number of Car objects and assign each a serial number, beginning with 0 for the first object. This id number is unique to each object and is therefore a non-static data field. At the same time, you need a field to keep track of how many Car objects have been created so that you know what id to assign to the next one. Such a field is not related to any individual object, but to the class as a whole. Thus, to keep track of the number of Car objects created, we will use the static field noOfCars and add in every constructor the statement noOfCars++; before this incrementation, the id field is assigned the value of noOfCars. In addition, we should make noOfCars private so that it cannot be changed from outside the class.

If needed we can provide read-only access to the private field noOfCars by defining a public method getNoOfCars() that will simply return the value of this field. To allow us to get the number of cars without knowing what car objects have been created, we will make method getNoOfCars static (so that it can be invoked using the class name instead of an object’s name). We also modify function printToString() so that it displays the id of each car in addition to the other data.


  • A static method CANNOT access non-static data fields. But, non-static methods CAN access static data fields (as illustrated in the above example).

  • Constructors cannot be declared static.

2.5. Inheritance

In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes. A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).

The idea of inheritance is simple but powerful: when you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug!) them yourself.

A subclass inherits all the members (fields, methods, and nested classes) from its superclass, except constructors. Constructors are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

Example: Class RaceCar is defined as a subclass of Car


RaceCar inherits all the fields and methods of Car and adds the fields rollCageType and windowNet and two methods to change these fields, setRollCageType and setWindowNet.

Keyword super allows a subclass method to invoke a method in the superclass. The constructors of the RaceCar class illustrate how to use the super keyword to invoke a superclass's constructor. This will take care of initializing the inherited data fields, so that you only need to assign values to the two new fields of the RaceCar class: rollCageType and windowNet.

Remark: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the default constructor of the superclass. If the super class does not have a default constructor, you will get a compile-time error.

When needed, you can provide a different implementation for an inherited method (and hide the original implementation). This is known as overriding a method. For example, we would like to override method printToString() from the Car class in the RaceCar class, such that it returns a string containing the values of the all the data fields, including the two new fields of this class. Remember that if a method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super.

Private members of the superclass CANNOT be accessed in the subclass. The modifier protected can be used instead of private to allow members of a class to be accessed from subclasses.

Class members



Can only be accessed from the class that defines them



Can be accessed from the class that defines them and from any subclasses of that class



Can be accessed from the class that defines them and all the other classes in the same package

Can only be accessed from the classes in the same package


Can be accessed from anywhere

Can be accessed from anywhere

2.6. Nested classes
The Java programming language allows you to define a class within another class. Such a class is called a nested class and is illustrated here:
class OuterClass {


class NestedClass {



As a member of the OuterClass, a nested class can be declared private, public, protected, or package. (Recall that outer classes can only be declared public or package).
Nested classes can be accessed just like any other class members, using the dot "." operator: OuterClass.NestedClass.

  • Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

  • There are two additional types of inner classes. You can declare an inner class within the body of a method. Such a class is known as a local inner class. You can also declare an inner class within the body of a method without naming it. These classes are known as anonymous inner classes.

There are several compelling reasons for using nested classes:

  • It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.

  • It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

  • Nested classes can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.

2.7. Abstract methods and classes
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
public abstract void sum(double x, double y);
If a class includes abstract methods, the class itself must be declared abstract, as in:

public abstract class Abc {


public abstract void sum(double x, double y);

Remark: Abstract classes cannot be instantiated (you cannot create objects of abstract classes), but they can be subclassed/extended. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.
An Abstract Class Example: In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier curves, and many other graphic objects. These objects all have certain states (for example: position, orientation, line color, fill color) and behaviors (for example: moveTo, rotate, resize, draw) in common. Some of these states and behaviors are the same for all graphic objects—for example: position, fill color, and moveTo. Others require different implementations—for example, resize or draw. All GraphicObjects must know how to draw or resize themselves; they just differ in how they do it. This is a perfect situation for an abstract superclass. You can take advantage of the similarities and declare all the graphic objects to inherit from the same abstract parent object—for example, GraphicObject, as shown in the following figure.

Classes Rectangle, Line, Bezier, and Circle inherit from GraphicObject
First, you declare an abstract class, GraphicObject, to provide fields and methods that are wholly shared by all subclasses, such as the current position and the moveTo method. GraphicObject also declares abstract methods for methods, such as draw or resize, that need to be implemented by all subclasses but must be implemented in different ways. The GraphicObject class can look something like this:
public abstract class GraphicObject {

private int x, y;


public void moveTo(int newX, int newY) {...}

public abstract void draw();

public abstract void resize();

Each non-abstract subclass of GraphicObject, such as Circle and Rectangle, must provide implementations for the draw and resize methods:
public class Circle extends GraphicObject {

public void draw() {...}

public void resize() {...}


public class Rectangle extends GraphicObject {

public void draw() {...}

public void resize() {...}


2.8. Interfaces
Interfaces are classes in which all methods are abstract. Like abstract classes, interfaces cannot be instantiated. They can only be implemented by classes or extended by other interfaces.
Interfaces are defined using the keyword interface instead of class.
public interface OperateCar {

int turn(int direction, double radius, int startSpeed, int endSpeed);

int changeLanes(int dir, int startSpeed, int endSpeed);

int signalTurn(int dir, boolean signalOn);

int getRadarFront(double distanceToCar, int speedOfCar);

int getRadarRear(double distanceToCar, int speedOfCar);


Remark: All of the methods in an interface are implicitly abstract, so the abstract modifier is not used with interface methods (it could be, but it's just not necessary).
Just like classes, interfaces can be extended by other interfaces (interface inheritance).

To use an interface, you write a class that implements the interface. If that class does not implement all the methods of the interface, the class must be declared abstract. To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class. By convention, the implements clause follows the extends clause, if there is one.

public class OperateBMW760i implements OperateCar {
int signalTurn(Direction direction, boolean signalOn) {

//code to turn BMW's LEFT turn indicator lights on/off

//code to turn BMW's RIGHT turn indicator lights on/off


int turn(int direction, double radius, int startSpeed, int endSpeed) {…}

int changeLanes(int dir, int startSpeed, int endSpeed) {…}

int getRadarFront(double distanceToCar, int speedOfCar) {…}

int getRadarRear(double distanceToCar, int speedOfCar) {…}

Rewriting Interfaces

Consider an interface that you have developed called DoIt:

public interface DoIt {

void doSomething(int i, double x);

int doSomethingElse(String s);

Suppose that, at a later time, you want to add a third method to DoIt, so that the interface now becomes:
public interface DoIt {

void doSomething(int i, double x);

int doSomethingElse(String s);

boolean didItWork(int i, double x, String s);

If you make this change, all classes that implement the old DoIt interface will break because they don't implement the interface anymore. Programmers relying on this interface will protest loudly.
Try to anticipate all uses for your interface and to specify it completely from the beginning. Given that this is often impossible, you may need to create more interfaces later. For example, you could create a DoItPlus interface that extends DoIt:
public interface DoItPlus extends DoIt {

boolean didItWork(int i, double x, String s);

Now users of your code can choose to continue to use the old interface or to upgrade to the new interface.

    1. Graphical User Interfaces (GUIs)

Java includes class libraries that provide support for GUIs. A Java GUI consists of components (such as buttons, text fields, labels, etc.) placed in GUI containers (such as, windows, panels, canvases). The size and arrangement of the components in a container is managed by layout managers.

The Java GUI system generates events when the user interacts with it (e.g., clicks on a button, types in a field, chooses from a pop-up menu, etc.). In order to capture user’s interaction with a GUI, a programmer should define for each GUI component one or more objects to "listen" for events from that component and process (respond to) them. These objects are called event listeners.
When an event occurs, the GUI system notifies the registered event listeners by invoking one of their event handling methods depending on the details of the event. For example, in case of a focus event, the source of the event (a GUI component) can be either gaining or loosing focus, and different actions might be required in the two cases. Thus, a focus event listener should have two event handling methods, one to be invoked when focus is gained and the other one to be invoked when focus is lost.
Different GUI components can generate different types of events and can therefore be assigned different types of event listeners to handle those events. For example, any GUI component can gain or loose focus thus generating a focus event, so it can therefore be assigned a focus listener. On the other hand, only a text component (such, as a text field) can generate a caret event (when the caret - the cursor indicating the insertion point - in a text component moves) and therefore can be assigned a caret listener. Assigning a caret listener to a button would not make sense.
Java GUI libraries contain several event listener interfaces, such as, FocusListener, CaretListener, ActionListener, MouseListener, etc., for different types of events. Thus, event listeners can be created as objects of classes (usually anonymous inner classes) implementing one or more of those existing interfaces.
Remark: An object of any class can be designated as an event listener if that class implements an existing event listener interface.
2.10. The final modifier
The final modifier is used to mark classes, methods, fields or formal parameters (of methods) as un-modifiable. Specifically:

  • a field that is declared final cannot be modified and must be initialized at the point of declaration

  • a method that is declared final cannot be overridden or declared to be abstract

  • a class that is declared final cannot be subclassed or declared to be abstract

  • a formal parameter that is declared final prevents the parameter’s value from changing


  1. Constructors cannot be marked with final.

  2. final always appear after the public/private/protected modifiers.

  3. Fields marked with final are sometimes made static to preserve memory (multiple copies of a value that cannot change are wasteful).

Pre-defined Android classes

Some of the pre-defined classes of the Android framework are: Activity, Intent, Dialog, View, Canvas, Paint. In your applications you will either extend these classes or create and use objects of these classes.

For more information on Android classes, see the complete documentation at:

2.11. Exception Handling

The Java programming language uses exceptions to handle errors and other exceptional events. An exception is “an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions” (Sun Microsystems) (e.g., a division by zero).

When an error occurs inside a method, the method creates an exception object, which contains information about the error, and hands it off to the runtime system. Creating an exception object and handing it to the runtime system is called throwing an exception. The runtime system then tries to find an exception handler (= code that can handle that exception) by searching the call stack. The call stack is the ordered list of methods that had been called to get to the method where the error occurred. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. The exception handler chosen is said to catch the exception.
Example: if method A calls method B and then B calls C, where an exception is thrown, then the system will go through the call stack starting with C trying to find a handler for that particular exception. If there is no handler in method C for that particular exception, the system looks in method B and then in A. If for some reason there is no exception handler capable of handling a particular exception then the system automatically terminates the program.
In java there are two types of exceptions: checked and unchecked exceptions.

  • Checked exceptions are exceptional conditions that a well-written application should anticipate and recover from. For example, suppose an application prompts a user for an input file name and then opens the file to read from it. Normally, the user will provide the name of an existing, readable file, so the execution of the application will proceed normally. But sometimes the user might mistakenly supply the name of a nonexistent file, in which case the program execution cannot proceed normally. A well-written program should catch this exception and notify the user of the mistake, possibly prompting for a corrected file name.

  • Unchecked exceptions are exceptional conditions that an application usually cannot anticipate or recover from. They are of two types: errors, which are external to the application (for example, if a file cannot be read because of a hardware or system malfunction) and runtime exceptions, which are internal to the application and usually indicate programming bugs, such as logic errors or improper use of an API.

Checked exceptions must be caught and handled, while unchecked exceptions do not need to be caught.

For example, a division-by-zero is a runtime exception, so it does not need to be caught and handled. However, when running the code below, a division-by-zero runtime exception will be thrown by the division operator and because the exception is not caught and handled the program will be terminated.

2.11.1. Catching and handling an exception: the try-catch-finally block
In order to catch an exception you must implement a try-catch-finally block that has the following syntax:

If any exception is thrown inside the try-block, the runtime system will search for an appropriate catch-block that can handle that exception and it will pass it the exception thrown. The finally-block is always executed regardless of whether an exception was thrown or not. If the try or catch blocks contain a return statement, the code inside the finally-block will get executed before the return statement.


When the above code is executed, the division operator throws an exception of type ArithmeticException which is passed by the runtime system to the catch-block for handling. As a result variable c is assigned the value of variable a and the information about the error is displayed followed by the value of variable c.

2.11.2. Propagating an exception: the throws clause
Instead of catching and handling an exception, a method also has the option to propagate the exception to methods further up the call stack for handling. This can be done using the throws clause in the method declaration. The throws clause comprises of the throws keyword followed by a comma-separated list of all the exceptions thrown by that method. In the example below, method doSomething propagates any exception of type ArithmeticException to the onCreate method (which is the one that invoked method doSomething).

2.11.3. Throwing an Exception: the throw statement
Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform, or the Java runtime environment. Regardless of what throws the exception, it is always thrown with the throw statement.
In the example below, an exception object of type ArithmeticException is created and thrown if the value of variable b is equal to 0. The constructor invoked takes one argument representing the error message associated with the ArithmeticException object created.

The Java platform provides numerous exception classes, such as ArithmeticException. All these classes are descendants of the Throwable class, and they allow programs to differentiate among the various types of exceptions that can occur during the execution of a program.

You can also create your own exception classes to represent problems that can occur within the classes you write. In fact, if you are a package developer, you might have to create your own set of exception classes to allow users to differentiate an error that can occur in your package from errors that occur in the Java platform or other packages.

Download 159.9 Kb.

Share with your friends:

The database is protected by copyright © 2022
send message

    Main page