Vous êtes sur la page 1sur 44

Core Java by www.ExamFear.

com

Introduction
Introduction to Java world
Setting up JAVA in computer
Popular Java Editors
Platform Independence
Java Virtual Machine
Object Oriented Programming
javadoc
JAR Files
PATH and CLASSPATH
Common errors
Comments
My First JAVA program
Compiling and Running an Application

Variables
Why variables?
Why so many variables
Using variables in JAVA
Identifiers
Global Variables AND Local Variables

Datatypes
Fundamental data types
Int
Char
Float etc
Compound data types
Struct
Array
Character sequence
Other data types
Typredef
Enum
Union
Constants
Instance Members
Static Members

Operators
Assignment
Arithmetic
Increment, decrement
Compound assignment
1

Relational
Page

&&, ||, ?, ,

Visit ExamFear.com for Free Question Papers for almost all Exams.
Sizeof
Precedence operator

Control
If else
While
Do while
For
Jump
Continue
Goto
Exit
Switch
Try catch finally

Java Access Modifiers


Introduction to Java Access Modifiers
public access modifier
private access modifier
protected access modifier
default access modifier

Function
Declaring function
Calling function
Parameters with function
Static method
Overloaded function
Inline function
Recursion

Classes & interface


Constructor and destructor
Overloading constructor
Default constructor
Interface
AbstractClass
Java package
Import statement

Inheritance
Single Inheritacne
Multi-Level inheritance
this and super keywords

Object Serialization
Introduction to Object Serialization
Transient Fields and Serialization
2

Input and Output Object Streams


Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
Java String Comparison
Compare String objects to determine Equality

Java StringBuffer
StringBuffer Class
Creation of StringBuffer's
StringBuffer Functions

Java Exception Handling


Exceptions in Java
Exception Classes
Exception Statement Syntax
Rules for try, catch and finally Blocks
try, catch and finally
Defining new Exceptions
throw, throws statement
Handling Multiple Exceptions

Others
Polymorphism
Type casting

Introduction to Core Java world


Java is a robust programming language developed by Sun Microsystems (Now Oracle) in 1991.Java has become
a popular platform since then and hence java has provided lots of standard such as J2EE, JSR etc. On 13
November 2006, Sun released much of Java as free and open source software under the terms of the GNU
General Public License (GPL).

Some of the features of Java are:


Object Oriented : Everything is an object in Java world.
Platform independent: java is platform independent. Java code complied in one machine can run in any
other machine if JRE or JDK is installed in that machine.This is done by JVM (Java virtual Machine )
Simple : Java is designed to be easy to learn. If you understand the basic concept of OOP java would be
easy to master.
Open Source : Java is an open source product and thus we need not pay for using it. Also since it is open
source, lots of support is available from open source community.
Secure : Java is secure and allows us to create secured application.
Robust :Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time
error checking and runtime checking.
Multi-threaded : Muti threading can easily be implemented in Java.
Distributed :Java is designed for the distributed environment of the internet.
3

Object - Objects have states and behaviors. Example: A dog has states-color, name, breed as well as
Page

behaviors -wagging, barking, eating. An object is an instance of a class.

Visit ExamFear.com for Free Question Papers for almost all Exams.
Class - A class can be defined as a template/ blue print that describe the behaviors/states that object of
its type support.

Setting up JAVA in computer


Setting up the path for windows 2000/XP/Win7:

Assuming you have installed Java in c:\Program Files\java\jdk directory:

Right-click on 'My Computer' and select 'Properties'.


Click on the 'Environment variables' button under the 'Advanced' tab.
Now alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path
is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read
'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.

Setting up the path for windows 95/98/ME:

Assuming you have installed Java in c:\Program Files\java\jdk directory:

Edit the 'C:\autoexec.bat' file and add the following line at the end:
'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'

Setting up the path for Linux, UNIX, Solaris, FreeBSD:

Environment variable PATH should be set to point to where the java binaries have been installed. Example, if
you use bash as your shell, then you would add the following line to the end of your '.bashrc: export
PATH=/path/to/java:$PATH'

Popular Java Editors:


To write your java programs you will need a text editor. There are even more sophisticated IDE available in the
market. But for now, you can consider one of the following:

Notepad : On Windows machine you can use any simple text editor like Notepad (Recommended for
this tutorial), TextPad.
Netbeans : it is a Java IDE that is open source and free which can be downloaded from
http://www.netbeans.org/index.html.
Eclipse : it is also a java IDE developed by the eclipse open source community and can be downloaded
from http://www.eclipse.org/

Platform independent :
Java is platform independent. Java code complied in one machine can run in any other machine if JRE or JDK
is installed in that machine. Java was conceived with the concept of WORA: "write once, run anywhere". This
4

is done by JVM (Java virtual Machine )


Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
Java virtual Machine:
Java Virtual Machine, or JVM as its name suggest is a ―virtual‖ computer that resides in the ―real‖ computer as
a software process. JVM gives Java the flexibility of platform independence. JVM is java interpreter as it
converts the byte code into machine code for the computer one wants to run.

The programs written in Java or the source code translated by Java compiler into byte code and after that the
JVM converts the byte code into machine code for the computer one wants to run. JVM is a part of Java Run
Time Environment that is required by every operating system requires a different JRE .

The architecture of the JVM is given below . This architecture tell us how the JVM works . Firstly we write the
simple java program(source code) the java compiler converts the source code into the bytecode , after that JVM
reads this bytecode and converts this into the machine code.

Object Oriented P rogramming :


Object oriented programming or OOP is a way of writing programs using objects. An object is a data structure
5

in memory that has attributes and methods. The attributes of an object are the same as variables and the methods
Page

of an object are the same as functions or procedures. . Object-oriented programming is a method of

Visit ExamFear.com for Free Question Papers for almost all Exams.
programming based on a hierarchy of classes, and well-defined and cooperating objects. In java we create
objects and classes. Also JAVA follows concepts of OOPS such as polymorphism, Inheritance, encapsulation.

Javadoc
Javadoc is a documentation generator from Sun Microsystems for generating API documentation in HTML
format from Java source code . The Javadoc provides information about various methods such as

1. Purpose of function
2. Parameters of function
3. Return type of function

JAR Files:
JAR file is the compressed file format. You can store many files in a JAR file. JAR stands for the Java Archive.
This file format is used to distribute a set of java classes. This file helps you to reduce the file size and collect
many file in one by compressing files. Downloading the files are become completed in very short duration of
time because of reducing the file size. You can make the jar file executable by collecting many class file of your
java application in it. The jar file can execute from the javaw (Java Web Start).

The JAR file format is based on the popular ZIP file format. Usually these file format is not only used for
archiving and distribution the files, these are also used for implementing various libraries, components and
plug- ins in java applications. Compiler and JVMs (Java Virtual Machine) can understand and implement these
formats for java application.

PATH and CLASSPATH


Path is for OS : Executable
Class path is for JVM : Class, jar files

The classpath tells Java where to look on the filesystem for files defining these classes.

The virtual machine searches for and loads classes in this order:

1. bootstrap classes: the classes that are fundamental to the Java Platform (comprising the public classes of
the Java Class Library, and the private classes that are necessary for this library to be functional).
2. extension classes: packages that are in the extension directory of the JRE or JDK, jre/lib/ext/
3. user-defined packages and libraries

Commenting in Java:
6

/* Multiple line comment */ :This is used for multiple line comment


Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
// Single line comment: this is used for single line comment.

Common Errors with Java:


About Java programs, it is very important to keep in mind the following points.

Case Sensitivity - Java is case sensitive which means identifier Hello and hello would have different
meaning in Java.
Class Names - For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class each inner words first letter should be in Upper
Case.Example class MyFirstJavaClass
Method Names - All method names should start with a Lower Case letter. If several words are used to
form the name of the method, then each inner word's first letter should be in Upper Case. Example
public void myMethodName()
Program File Name - Name of the program file should exactly match the class name. When saving the
file you should save it using the class name (Remember java is case sensitive) and append '.java' to the
end of the name. (if the file name and the class name do not match your program will not compile).
Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as
'MyFirstJavaProgram.java'
public static void main(String args[]) - java program processing starts from the main() method which
is a mandatory part of every java program..

My First Java Program:


Let us look at a simple code that would print the words Hello World.

public class ExamFear{

/* This is the first Java program by Examfear.com


This program will print ‗Hello ExamFear Users' */

public static void main(String []args){


System.out.println("Hello ExamFear Users"); // prints Hello World
}
}

How to run a java program:

1. Open notepad and add the code as above.


2. Save the file as: ExamFear.java. Please note that file name should be same as class name.
3. Open a command prompt window and go to the directory where you saved the class. Assume its C:\.
7

4. Type ' javac ExamFear.java ' and press enter to compile your code. If there are no errors in your code the
Page

command prompt will take you to the next line.( Assumption : The path variable is set).

Visit ExamFear.com for Free Question Papers for almost all Exams.
5. Now type ' java ExamFear ' to run your program.
6. You will be able to see ' Hello ExamFear USers ' printed on the window.

C : > javac ExamFear.java


C : > java ExamFear
Hello ExamFear Users

Lets understand what we have done:


We have created a java file named ExamFear.java. In this file we have a class called ExamFear. This class has a
main method. When we execute the program, main method‖ static void main (String []args)‖ is called. Here we
have printed ―Hello ExamFear Users‖. Also note that we have used both single line and multi line comment.

Compiling and running Java Program:


When JDK is installed on your machine, it provides two commands for you to compile and run Java programs.

"javac class_name.java" - Compiles a Java program stored a file named with the program class name.
We compile Java file with extension *.java to create bytes code with extension *.class
"java -cp . class_name" - Runs a compiled Java program. "-cp ." specifies the current directory as the
class path.

Why variables?
Variables are used to store values that can be used by program. Also it is used to pass value from user to
computer. A variable of type char stores a single character, variables of type int store integers (numbers without
decimal places), and variables of type float store numbers with decimal places. Each of these variable types -
char, int, and float - is each a keyword that you use when you declare a variable.

Why so many variable types?


We use so many variable types to make your code efficient and readable. Using the right variable type can be
important for making your code readable and for efficiency--some variables require more memory than others.
E.g.: Char should not be used to store number. Float should be used only if you want to store decimal.

Using Variables in Java


To declare a variable you use the syntax "type <name>;". Here are some variable declaration examples:

int x;
char student_name;
float cost_price;

It is permissible to declare multiple variables of the same type on the same line; each one should be separa ted
by a comma.

int a, b, c, d;

If you were watching closely, you might have seen that declaration of a variable is always followed by a
8
Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
semicolon (note that this is the same procedure used when you call a function).

Ok, so you now know how to tell the compiler about variables, but what about using them? One application of
variable is an addition program. Suppose you want to add two numbers, in that case you have to put number1
and number2 in memory and then add it. In such case you will need variable.

int a = 6;
int b = 3;
int result = a + b;

Java Identifiers:
All java components require names. Names used for classes, variables and methods are called identifiers. Java
identifiers should follow the rules below:

All identifiers should begin with a letter (A to Z or a to z ), currency character ($) or an underscore (-).
After the first character identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly identifiers are case sensitive.
Examples of legal identifiers: cost, $price, _value, __1_value
Examples of illegal identifiers : 567pqr, - india

Java Modifiers:
Like other languages it is possible to modify classes, methods etc by using modifiers. There are two categories
of modifiers.

Access Modifiers : defualt, public , protected, private. These are keywords that help set the visibility
and accessibility of a class, its member variables, and methods

Non-access Modifiers : There are five non access Modifiers in Java.


1. static
2. final
3. transient
4. abstract
5. synchronized

Java Variables:
We would see following type of variables in Java:
9

Local Variables
Page

Class Variables (Static Variables)

Visit ExamFear.com for Free Question Papers for almost all Exams.
Instance Variables (Non static variables)

Fundamental data types


When we wish to store data in a Java program, such as a whole number or a character, we have to tell the
compiler which type of data we want to store. The data type will have characteristics such as the range of values
that can be stored and the operations that can be performed on variables of that type.

Fundamental types
Java provides the following fundamental built- in data types: Boolean, character, integer and floating-point.

Boolean Type
The Boolean type can have the value true or false. For example: bool flag = false;
If a Boolean value is converted to an integer value true becomes 1 and false becomes 0 and vice versa.

Character Type
The character type is used to store characters - typically ASCII characters but not always. For example: char

alphabet = 'a';
char number = '52';

We can declare signed and unsigned characters, where signed characters can have positive and negative values,
and unsigned characters can only contain positive values. A char is guaranteed to be at least 8 bits in size.

Integer Types
The integer type is used for storing whole numbers. We can use signed, unsigned or plain integer values as
follows:

signed int marks = -187;


unsigned int vote = 12;
int population = 998100;

Like characters, signed integers can hold positive or negative values, and unsigned integers can hold only
positive values. However, plain integer can always hold positive or negative values, they're always signed.

Integer values come in three sizes, plain int, short int and long int. The range of values for these types will be
defined by your compiler. A short integer is guaranteed to be at least 16 bits and a long integer at least 32 bits.
10

Floating-Point Types
Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
Floating point types can contain decimal numbers, for example 1.23, -.087. There are three sizes, float (single-
precision), double (double-precision) and long double (extended-precision). Some examples:

float celsius = 37.623;


double fahrenheit = 98.415;
long double accountBalance = 1897.23;

The range of values that can be stored in each of these is de fined by your compiler.

Name Description Size* Range*

signed: -128 to 127


char Character or small integer. 1byte
unsigned: 0 to 255

short int signed: -32768 to 32767


Short Integer. 2bytes
(short) unsigned: 0 to 65535

signed: -2147483648 to
int Integer. 4bytes 2147483647
unsigned: 0 to 4294967295

signed: -2147483648 to
long int
Long integer. 4bytes 2147483647
(long)
unsigned: 0 to 4294967295

Boolean value. It can take one of two


bool 1byte true or false
values: true or false.

float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)

double Double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits)

Long double precision floating point


long double 8bytes +/- 1.7e +/- 308 (~15 digits)
number.

2 or 4
wchar_t Wide character. 1 wide character
bytes

* The values of the columns Size and Range depend on the system the program is compiled for.
11
Page

Composite data type :

Visit ExamFear.com for Free Question Papers for almost all Exams.
A composite data type is any data type which can be constructed in a program using primitive data types and
other composite types. Examples of composite data types are enum, struct, class, string etc

Structs or Structures
There are many instances in programming where we need more than one variable in order to represent
something. For example, to represent student, you might want to store name, age, address, phone number etc, or
any other number of characteristics about student. You could do so like this:

char strName[20]; int age;Char address[50]; int phoneNumber;

However, you now have 4 independent variables that are not grouped in any way. If you wanted to pass
information about yourself to a function, you‘d have to pass each variable individually. Furthermore, if you
wanted to store information about more people, you‘d have to declare 4 more variables for each additional
student.

Fortunately, Java allows us to create our own user-defined aggregate data types. An aggregate data type is a
data type that groups multiple individual variables together. One of the simplest aggregate data type is the
struct. A struct (short for structure) allows us to group variables of mixed data types together into a single unit.
Because structs are user-defined, we first have to tell the compiler what our struct looks like before we can
begin using it. To do this, we declare our struct using the struct keyword. Here is an example of a struct
declaration:

struct Student
{
char strName[20];
int age;
char address;
int phoneNumber;
}

This tells the compiler that we are defining a struct named Student. The Employee struct contains 4 variables
inside of it: two ints and two char. These variables are called members (or fields). Keep in mind that the above
is just a declaration — even though we are telling the compiler that the struct will have variables, no memory is
allocated at this time.

In order to use the Employee struct, we simply declare a variable of type Employee:
Student s1, s2;
Using this command we create objects of student , S1 and S1 and hence memory is allocated.

Arrays
An array is a series of elements of the same type placed in contiguous memory locations that can be
12

individually referenced by adding an index to a unique identifier.


Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
That means that, for example, we can store 10 values of type int in an array without having to declare 10
different variables, each one with a different identifier. Instead of that, using an array we can store 5 different
values of the same type, int for example, with a unique identifier.
unt arrayStudentId[10]; // This can store 10 student ids..
arrayStudentId[0]= 123; arrayStudentId[1]= 124; etc..

int employeeId[5] = { 1,2,3,4,5}; // this is array of length 5, and it is similar to


int employeeId[0] = 1;
int employeeId[1] = 2;
int employeeId[2] = 3;
int employeeId[3] = 4;
int employeeId[4] = 5;

Multi Dimensional array:

int ExamFear[3][4];

It is represented internally as:

0 1 2 3

How to access the elements in the Multidimensional Array

0 1 2 3

Highlighted cell represent ExamFear[1][2]

Java Keywords:
13
Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
The following list shows the reserved words in Java. These reserved words may not be used as constant or
variable or any other identifier names.

abstract assert boolean break

byte case catch char

class const continue default

do double else enum

extends final finally float

for goto if implements

import instanceof int interface

long native new package

private protected public return

short static strictfp super

switch synchronized this throw

throws transient try void

volatile while extends

Enumerated types

An enumerated type is a data type where every possible value is defined as a symbolic constant (called an
enumerator). Enumerated types are declared via the enum keyword. Let‘s look at an example:
14
Page

enum Color_list {COLOR_BLACK, COLOR_RED, COLOR_BLUE};

Visit ExamFear.com for Free Question Papers for almost all Exams.
Defining an enumerated type does not allocate any memory. When a variable of the enumerated type is declared
memory is allocated for that variable at that time.

Enum variables are the same size as an int variable. This is because each enumerator is automatically assigned
an integer value based on it‘s position in the enumeration list. By default, the first enumerator is assigned the
integer value 0, and each subsequent enumerator has a value one greater than the previous enumerator:

Operators
Operator is used to operate variables and constants. Lets discuss various kinds of operators in Java.

Assignment (=)
This operator assigns a value to a variable.

E.g : int i = 10;

This statement assigns the integer value 10 to the variable i. The part at the left of the assignment operator (=) is
variable whereas the one on right is constant. The assignment operation always takes place from right to left
only.

Arithmetic operators ( +, -, *, /, % )
The five arithmetical operations supported by the JAVA language are:

+ addition
- subtraction
* multiplication
/ division
% modulo

Operations of addition, subtraction, multiplication and division literally correspond with their respective
mathematical operators.
Modulo is the operation that gives the remainder of a division of two values. For example, if we write:

int b = 10 % 4;

the variable a will contain the value 2, since 2 is the remainder from dividing 10 by 4.

Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)
15

Compound assignment operators are used when we want to modify the value of a variable by performing an
Page

operation on the value that is stored in the variable currently.

Visit ExamFear.com for Free Question Papers for almost all Exams.
Usage Example:

p -= 6; p = p - 6;

p /=q; p = p / q;

a *= b - 5; a = a * (b -5);

Increase and decrease (++, --)

Increase operator (++) and the decrease operator (--) increase or decrease by one the value stored in a variable.

a++ ;a+=1; a=a+1; //are all same. All increase value of a by 1.

b--;b-=1;b=b-1; //are all same. All decrease value of b by 1

Difference between a++ and ++a:


In case of (++a) the value is increased before the result of the expression is evaluated while in case of (a++) the
value stored in a is increased after being evaluated.

Let‘s see the example to clarify any doubts if any.

P=5;
Q= ++P; //Here both P and Q stores 6.
P=5;
R = P++; //Here R stores 5 and P stores 6.

Relation and equality operator:


Relational and equality operators are used to compare between two expressions. The result of a relational
operation is a Boolean value that can only be true or false.

== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to

Let‘s see some examples to clarify doubts if any.


16

(5== 2) // this returns false. (5==5) // this returns true


Page

(5!= 5) // this returns false. (5!=2 ) // this returns true

Visit ExamFear.com for Free Question Papers for almost all Exams.
(5<2) // this returns false. (2<5) // this returns true
(2>5) // this returns false. (5>2) // this returns true

&& Operator
This is AND operator. For A && B, if both A and B are true, result is true else it is false. Even if one is false,
result is false.

|| Operator:
This is logical OR operator. For A && B, even if either of A or B is true, result is true. It is false only when
both A and B are false.

Conditional operator ( ? )
The conditional operator evaluates an expression returning a value if that expression is true and a different one
if the expression is evaluated as false. Its format is:
variable = condition ? result1 : result2
If condition is true the expression will return result1, if it is not it will return result2.
A = 9<5 ? 5 : 6 // returns 6, since 9 is not greater than 5.

Comma operator ( , )
The comma operator (,) is used to separate two or more expressions that are included where only one expression
is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is

considered. For example, the following code:

p = (q=4, q+3);

Here q is assigned 4 in first place, then q+3, that is (4+3 =7) is assigned to P.

Explicit type casting operator


Type casting operators are used to convert a variable from on type to another type. This is done by writing by
the new type enclosed between parentheses (()):

float float_vlaue = 5.234;


int integer_value =0;
integer_value = (int) float_vlaue;
17

The above code converts float float_vlaue to int. here integer_value stores values 5 as decimal place is lost in
type conversion.Type casting can also be done in the syntax mentioned below.
Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
integer_value = int (float_value );

sizeof()
This operator accepts one parameter, which can be either a type or a variable itself and returns the size in bytes
of that type or object:

a = sizeof (char);

This will assign the value 1 to a because char is a one-byte long type.

The value returned by sizeof is a constant, so it is always determined before program execution.

Control Structures
In real world, we need scenarios where program need to take decision, jump to code in some other place, repeat
code etc. This can‘t be achieved by linear sequence of instructions. So we have concept of control structures.

Before we proceed further, let me introduce you to a concept called block. Block is a group of sentence that are
enclosed in {};

Eg: { int a; char b; float c;}

if and else
The if keyword is used to execute a piece of statement or block only when a given condition is true.
Else statement is used to execute a piece of statement or block only when a given statement is false.

Syntax:
if ( condition)
{ Execute this block if condition is true}
else
{ Execute this block if condition is false}

Code:
if (a == b)
{System.out.println( ― both a and b are equal‖)}
else
{ System.out.println( ― both a and b are not equal‖)}
18
Page

Iteration structures (loops)

Visit ExamFear.com for Free Question Papers for almost all Exams.
Loop is used when we want a block to be executed certain number of times.
Format:
while (Condition is true)
{ statements to be executed }

In this case, the statements will be executed till the condition is true.

while(true)
{ System.out.println(―this is a tutorial by examfear.com‖); }

This will execute infinite number of times.

int i=10;
while(i>0)
System.out.println(―this is a tutorial by examfear.com‖);;
i--;
}
This statement will be executed 10 times.

Do-while loop
Do while loop and while loop are almost similar with a difference that do while loop is executed at least once
even if the condition is false. This is because condition in the do-while loop is evaluated after the execution of
statement instead of before.

Syntax:
do
{statements to be executed}
while
(condition);

CODE:
int i=10;
do
{ System.out.println((―this is a tutorial by examfear.com‖);
}
while (i ==5)

This statement will be executed once even when the condition is false
19

int i=10;
while (i ==5
Page

{ System.out.println((―this is a tutorial by examfear.com‖);

Visit ExamFear.com for Free Question Papers for almost all Exams.
}

This statement will not be executed even once.

The break statement


Break statement is used to come out of a loop evein if condition is not fulfilled.

while(true)
{ System.out.println(― this document is brought to you by examfear.com‖);
break;
}

Without break statement, this loop will print infinite times, but sine we have placed a break statement, the cout
statement will be executed only once.

The continue statement

The continue statement is used to skip rest of the loop and goes back to the start of the current iteration as if end
of the block is reached.
Suppose we want to print odd numbers from 1 to 10. then we can use continue statement to skip printing of
even number.

int i = 0;
while ( i <10)
{i++;
if(i%2 == 0) continue; // if the number is even, it will return true and hence we will skip the next statement.
System.out.println( i);
}

The goto statement


goto statement is used when we want to jump to another point in the program.
The destination point is identified by a label, which is then used as an argument for the goto statement. A label
is made of a valid identifier followed by a colon (:).
Suppose we want to print odd numbers from 1 to 10. then we can use continue statement to skip printing of
even number.

int i = 0;
while ( i <10)
{i++;s
if(i%2 == 0) Label1234; // if the number is even, it will return true and hence we will to label1234.
20

System.out.println( i);
Label1234:
Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
The exit function
The purpose of exit is to terminate the current program with a specific exit code. exit is a function defined in the
cstdlib library .
Syntax:
void exit (int exitcode);
The exitcode is used by some operating systems and may be used by calling programs. By convention, an exit
code of 0 means that the program finished normally and any other value means that some error or unexpected
results happened.

Switch statement.
Switch statement is used to check several possible values for an expression and then decide to execute a
statement or block based on that value.

switch (expression)
{
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;
break;
.
.
.
default:
default group of statements
}

Working of switch statement:


1. It evaluates expression. It should be some constant.
2. Based on the value it goes to case <<value of expresion>> statement
3. It executes the statement till it encounters a break statement. That is why block is not needed in switch.
4. If the expression value is not equal to any of the constant value then it executes statements after default:

switch (a) {
case 1: System.out.println("a is 1‖); break;
case 2: System.out.println("a is 2‖); break;
case 3: System.out.println(("a is 3‖); break;
21

default:
System.out.println("a is unknown");
Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
}

This code will print ―a is 1‖ is a ==1; ―a is 2‖ if a==2; ―a is 3‖ if a==3 and ―a is unknown‖ if a is any other
number.

Please note the break statement.

Try catch Finally


try {
statements;
} catch (exceptionType1 identifier1) { // one or multiple
statements;
} catch (exceptionType2 identifier2) {
statements;
}
...
} finally { // one or none
statements;
}

Properties for try catch statements:


must include either one catch clause
can be multiple catch clauses but only one finally clause
the try statements are executed until an exception is thrown or it completes successfully
a compile-error occurs if the code included in the try statement will never throw one of the caught
checked exceptions (runtime exceptions never need to be caught)
if an exception is thrown, each catch clause is inspected in turn for a type to which the exception can be
assigned; be sure to order them from most specific to least specific
when a match is found, the exception object is assigned to the identifier and the catch statements are
executed
if no matching catch clause is found, the exception percolates up to any outer try block that may handle
it
a catch clause may throw another exception
if a finally clause is included, it's statements are executed after a ll other try-catch processing is complete
the finally clause executes wether or not an exception is thrown or a break or continue are encountered
More specific cache should be written first and more generalized one at last in the catch block.

Example:

public class TestFinally {

/**
* @param args
*/
22

public static void main(String[] args) {


Page

System.out.println("Inside main method!");

Visit ExamFear.com for Free Question Papers for almost all Exams.
int iReturned = new TestFinally().testMethod();
System.out.println("Returned value of i = " + iReturned);

public int testMethod(){

int i = 0;
try{
System.out.println("Inside try block of testMethod!");
i = 100/0;
return i;
}catch(Exception e){
System.out.println("Inside catch block of testMethod!");
i = 200;
return i;
}
finally{
System.out.println("Inside finally block of testMethod!");
i = 300;
return i;
}
}
}

Functions
In real world programming, code is huge. It is difficult to manage code if it is not structured. Also in most of the
case we use same logic at multiple places, so it doesn‘t make any sense to write same block of code multiple
times. Hence comes the concept of function.

Advantage of functions:

1. Make code more structures


2. Make code more human readable
3. Re-use of same block of code at multiple places.

A function is a group of statements that is executed when it is called from some point of the program. The
following is its format:

type name ( parameter1, parameter2, ...) { statements }

where:
23

1. type is the data type returned by the function. E.g.: if it is Int, it means that function return integer.
Page

2. name is the identifier by which it will be possible to call the function.

Visit ExamFear.com for Free Question Papers for almost all Exams.
3. parameters: Each parameter consists of a data type specifier followed by an identifier, like any regular
variable declaration (for example: int a) and which acts within the functio n as regular local variable.
4. statements is the function's body. It is a block of statements surrounded by braces { }.It is the bunch og
code that needs to be executed on function call.

Here you have the first function example:


// function example with constant as parameter to the function
int additionFx (int p, int q)
{
int r;
r=p+q;
return (r);
}

Public static void main ()


{
int a;
a = additionFx (6,2);
System.out.println ("The sum of 6 and 2 is " + a);
}

Output:
The sum of 6 and 2 is 8

Explanation:
The code starts from void main() function. The first statement creates an integer a variable. In the next
statement function additionFx () is called with two parameters viz 6, 2. Thus the control will now go to the
function. As we notice that return type of function is integer it will return integer and the output will be stored in
integer variable named a. If we go inside the function than we notice that the function use two local variables p
and q , that are also parameters to the function. We define a variable called r, this variable stores the sum of p
and q and returns back which is now captured by a. And finally the number ―a‖ is printed.

// function example with variable as parameter to the function


int additionFx (int p, int q)
{
int r;
r=p+q;
return (r);
}
24

void main ()
Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
int a,b,c;
b=6;
c=2;
a = additionFx (b,c);
System.out.println( "The sum of 6 and 2 is " + a);
}

Output:
The sum of 6 and 2 is 8

Explanation:
This program is similar to what mentioned above with only one difference. Instead of passing constant values 2
and 6 to function, now we are passing variables to the function. This works perfectly fine.

Functions with no return type:


If you want to create a function that doesn‘t return any data type then you will have to use void as return type.

Eg: void printvalue(int i);

//Example of function with no return type


void printvalue (int i)
{
System.out.println ("The value of number passed is‖+ i);
}
Public static void main ()
{
int a=5;
printvalue (a);
}

Default Function: Where default valus is passed to the function.

// example of default value function


int additionFx (int a, int b=4)
{
int r;
r=a+b;
return (r);
25

}
void main ()
Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
{
System.out.println (additionFx (3));
System.out.println (‖ , ‖);
System.out.println( additionFx (3,5));
}

Output:
7 , 8

Explanation:
When additionFx (3)is called, b takes its default value that is 4 and thus output is 3+ 4 =7;
When additionFx (3,5) is called the output is 3+5 =8;

Overloaded functions.
To make code more readable, we need functions that perform different action if they have either differen
number of parameter or different type of parameter.

// Example of overloaded function


float area (int length, int breadth)
{ return (length * breadth); }

float area (int radius)


{ return (22/7 * radius * radius); }

void main ()
{int l=2,b=3,r=7;
System.out.println (―Area of rectangle is ‖ + area (l,b));
System.out.println (―Area of circle is ‖ +area(r));
}

Area of rectangle is 6
Area of circle is 154

Explanation:
Here we have two methods with same name called area. First one calculates area of rectangle while second one
calculates area of circle. This is done by overloaded function. The argument to both function are different.
When we call area (l,b), then first function is called that calculates area of rectangle. When we call area ®, then
second function is called , calculating area of circle.

Declaring functions.
26

Till now, we have defined function and then we have used it. If we try to do other way round it will throw error
as compiler will not be aware of the function. In order to avoid this we can just declare the function before
Page

invoking it. Function definition can be provided later in this case.

Visit ExamFear.com for Free Question Papers for almost all Exams.
Syntax:

type name ( argument_type1, argument_type2, ...);

It is identical to a function definition, except that it does not include the body of the function and also it doesn‘t
have braces {}. Also note the semicolon at the end of declaration.

The parameter enumeration does not need to include the identifiers, but only the type specif ier. Both statement
below will work fine.

int FunctionExamfear (int marks);


int FunctionExamfear (int);

//Example of function declaration


void main ()
{ int additionFx (int, int);
int a;
a = additionFx (6,2);
System.out.println ("The sum of 6 and 2 is ")+ a;
}
int additionFx (int p, int q)
{
int r;
r=p+q;
return (r);
}

Output:
The sum of 6 and 2 is 8

Here addition function is just defined after function invocation, but still it ran successfully because of function
declaration before function calling.

Let‘s revise what all we can do with function. Things we can do with function:

1. Function declaration: Eg int additionFx(int,int);


2. Function invocation/call: Eg: int p =additionFx(3,2);
3. Function definition : Eg: int additionFx(int a, int b){ return (a+b);}

Classes
27

A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and
functions. An object is an instantiation of a class. In terms of variables, a class would be the type, and an object
Page

would be the variable.

Visit ExamFear.com for Free Question Papers for almost all Exams.
Classes are generally declared using the keyword class, with the following format:
class class_nm {
access_specifier_a:
member1;
access_specifier_b:
member2;
...
function(parameters);

} object_nm;

Here Class_nm is unique name of class. object_nm is name of object. Access_specifier are keywords private,
public or protected. These specifiers modify the access rights that the members following them acquire:
Private member of a class are accessible only from members of the same class. We will talk about
friendslater.
Public members are accessible from anywhere where object is visible.
If no access specifier is defined then it is considered private.

//Example of class
class ExamFear {
int x, y;
public:
void print_message(char);
int user_id (char);
} user1234;

The above code defines a class called Examfear which has two variables x and y defined . Also it has two
function. ―user1234‖ is the object of the class. If we want to access variable or function of the class then we
have to prefix it with ―objectname. ― . Eg: in this case we have to say user1234.print_message(―a‖);

Also we need to note that we can‘t access x and y outside the body of class as they are private variables. Only
functions of the class can use it.

Constructors
In real world problems, we need to initialize variables during the process of creation based on business logic to
avoid null values during exception. In order to achieve that we need special function called constructor.
Constructor is automatically called when a new object is created. Then name of constructor should be same as
class name and should not have any return type, not even void.

// example of class constructor


28

class ExamFear {
Page

int userId;

Visit ExamFear.com for Free Question Papers for almost all Exams.
public:
ExamFear (int id) {
userId = id;
}
int showUserId()
{return userId;
}

public static void main () {


ExamFear ef1(1234);
Cout<<‖ User id is :‖<< ef1.showUserId();
}
}

The output is:


User id is 1234

Here we see that while creating object (ef1) of class ExamFear, we passed the value of userId. The value 1234,
is assigned to UserId. When we invoke showUserId, it displays the value 1234.

Please note that constructors cannot be called explicitly as a regular member functions. They are only executed
when a new object of that class is created. Also neither constructor declaration nor constructor definition has a
return type.

Overloading Constructors
Like any other function, a constructor can also be overloaded with more than one function that have the same
name but different types or number of parameters. Remember that for overloaded functions the compiler will
call the one whose parameters match the arguments used in the function call. In the case of constructors, which
are automatically called when an object is created, the one executed is the one that matches the arguments
passed on the object declaration:

Default constructor
If you do not declare any constructors in a class definition, the compiler assumes the class to have a default
constructor with no arguments. But as soon as you declare your own constructor for a class, the compiler no
longer provides an implicit default constructor. So you have to declare all objects of that class according to the
constructor prototypes you defined for the class:

Java Package:
In simple it is a way of categorizing the classes and interfaces. When developing applications in Java, hundreds
29

of classes and interfaces will be written, therefore categorizing these classes is a must as well as makes life
Page

much easier.

Visit ExamFear.com for Free Question Papers for almost all Exams.
Import statements:

In java if a fully qualified name, which includes the package and the class name, is given then the compiler can
easily locate the source code or classes. Import statement is a way of giving the proper location for the compiler
to find that particular class.For example following line would ask compiler to load all the classes available in
directory java_installation/java/io :

import java.io.*;

Interfaces:
In Java language an interface can be defined as a contract between objects on how to communicate with each
other. It provides only name of method not the definitio n. Interfaces are used to provide a template or design for
concrete subclasses down the inheritance tree. Eg: In case of car, it is defined that it should have methods such
as tyresSize() , enginePower(),and howToStartCar().

Here if we just declare that tyresSize() , enginePower(),and howToStartCar() are mandatory features of car
without commenting anything on this, and allowing different manufactures to decide on tyres size, Engine
power and steps to start car. The above scenario can be represented in Java by using interface and inheritance.

Rules for interface:

1. One interface can extend another interface


2. One class can implement many interface and thus we can implement multiple inheritance with this.
3. Interface can only declare signature of methods. It can‘t define methods
4. Interface can‘t define objects. It can only have signature of functions.
5. Classes implementing interfaces must define all methods of interface.
6. An interface cannot be instantiated.
7. An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed
as public

interface CarInterface

int tyreSize;

int enginePower ;

int tyresSize();

int enginePower();

void howToStartCar (); // public static by default


30

}
Page

class MarutiWagonR implements CarInterface {

Visit ExamFear.com for Free Question Papers for almost all Exams.
public int tyresSize() { return tyreSize;}

public int enginePower(){ return enginePower; }

public void howToStartCar ()

{ System.out.println(― Steps to start car‖);

System.out.println(― Insert Key into KeyHole‖);

System.out.println(― Rotate the key in Clockwise direction‖);

System.out.println(― Car will start‖);

Java Abstract classes


Java Abstract classes are used to declare common characteristics of subclasses. An abstract class cannot be
instantiated. It can only be used as a superclass for other classes that extend the abstract class. Abstract classes
are declared with the abstract keyword. Abstract classes are used to provide a template or design for concrete
subclasses down the inheritance tree.

Like any other class, an abstract class can contain fields that describe the characteristics and methods that
describe the actions that a class can perform. An abstract class can include methods that co ntain no
implementation. These are called abstract methods. The abstract method declaration must then end with a
semicolon rather than a block. If a class has any abstract methods, whether declared or inherited, the entire class
must be declared abstract. Abstract methods are used to provide a template for the classes that inherit the
abstract methods.

Abstract classes cannot be instantiated; they must be subclassed, and actual implementations must be provided
for the abstract methods. Any implementation specified can, of course, be overridden by additional subclasses.
An object must have an implementation for all of its methods. You need to create a subclass that provides an
implementation for the abstract method.

Rules for abstract class:

1. An abstract class cannot be instantiated.


2. It can only be used as a superclass for other classes that extend the abstract class.
3. Abstract classes are declared with the abstract keyword.
4. Like any other class, an abstract class can contain fields that describe the characteristics and methods
that describe the actions that a class can perform.
5. An abstract class can include methods that contain no implementation. These are called abstract
31

methods. The abstract method declaration must then end with a semicolon rather than a b lock.
6. If a class has any abstract methods, whether declared or inherited, the entire class must be declared
Page

abstract.

Visit ExamFear.com for Free Question Papers for almost all Exams.
7. An abstract class can contain access modifiers for the subs, functions, properties

Inheritance:
In java classes can be derived from classes. Basically if you need to create a new class and there is already a
class that has some of the code you require, then it is possible to derive your new class from the already existing
code. This concept allows you to reuse the fields and methods of the existing class with out having to rewrite
the code in a new class. In this scenario the existing class is called the super class and the derived class is called
the subclass.

Let us consider the chain of inheritance.

Engine  Vehicle  Normal Car  Luxury Car

Now lets see the attribute of all these

1. Engine : Consume petrol, and creates motion


2. Vehicle: Has engine and tyres, It moves
3. Normal Car: Has Engine, Has tyres, it moves, has seat belts, steering, brake etc
4. Luxury car: It has all the features of normal car. Also it has Air conditioner, music system, leather seats
etc.

Here we see that Vehicle inherits some property of Engine, Normal car inherits some property of Vehicle, and
luxury car inherits property of normal car.

In java world, we will write the statement in this format

Class engine {String petrol; String motion; }

Class Vehicle extends engine { int tyres; String movement; }

Class normalCar extends Vehicle { String SeatBelt; String Steering; String brake; }

Class luxuryCar extends normalCar { String AirConditioner; String Stereo; String LeatherSeats; }

Java Supports two kind of inheritance:


Simple Inheritance : If Class A extends only Class B, it is called single level inheritance.
Multilevel Inhe ritance : If Class A extends Class B and Class B in turn Extends Class C, then it is
called multi- level inheritance. The above ―engine  vehicle  normal car  Luxury Car‖ example is
of Multi- level inheritance. Java does not support multiple Inheritance

Multiple Inheritance
32

The mechanism of inheriting the features of more than one base class into a single class is known as multiple
Page

inheritance. Java does not support multiple inheritance but the multiple inheritance can be achieved by using the

Visit ExamFear.com for Free Question Papers for almost all Exams.
interface. In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more than
one interfaces in a class. We will see this in Interface section.

This keyword:
It is used to get values of current class. The keyword this is useful when you need to refer to instance of the
class from its method. The keyword helps us to avoid name conflicts. As we can see in the program that we
have declare the name of instance variable and local variables same. Now to avoid the confliction between them
we use this keyword. Here, this section provides you an example with the complete code of the program for the
illustration of how to what is this keyword and how to use it.

super keyword
The super is java keyword. As the name suggest super is used to access the members of the super class.It is used
for two purposes in java.

super.member;

Here member can either be an instance variable or a method. This form of super most useful to handle situations
where the local members of a subclass hides the members of a super class having the same name. The following
example clarify all the confusions.

class ABC{

int b;

void display(){ System.out.println("Value of b in class ABC is : " + a); }

class PQR extends ABC{ int b; }

void display()

System.out.println("Value of super b in class PQR is : " + super.b);

System.out.println("Value of b in class PQR is : " + b);

public static void main(String[] args){

ABC a1 = new ABC(5);


33

PQR p1 = new PQR(8);


Page

a1.display();

Visit ExamFear.com for Free Question Papers for almost all Exams.
p1.display();

Output:
Value of b in class ABC is 5
Value of super b in class PQR is : 5
Value of b in class PQR is 8

Object Serialization

Java object serialization is used to persist Java objects to a file, database, network, process or any other system.
Serialization flattens objects into an ordered, or serialized stream of bytes. The ordered stream of bytes can then
be read at a later time, or in another environment, to recreate the original objects.

Java serialization does not cannot occur for transient or static fields. Marking the field transient prevents the
state from being written to the stream and from being restored during deserialization. Java provides classes to
support writing objects to streams and restoring objects from streams. Only objects that support the
java.io.Serializable interface or the java.io.Externalizable interface can be written to streams.public interface
Serializable

The Serializable interface has no methods or fields. (Marker Interface)


Only objects of classes that implement java.io.Serializable interface can be serialized or deserialized

Transient Fields and Java Serialization


The transient keyword is a modifier applied to instance variables in a class. It specifies that the variable is not
part of the persistent state of the object and thus never saved during serialization.You can use the transient
keyword to describe temporary variables, or variables that contain local information,such as a process ID or a
time lapse.

Input and Output Object Streams


ObjectOutputStream is the primary output stream class that implements the ObjectOutput interface for
serializing objects. ObjectInputStream is the primary input stream class that implements the ObjectInput
interface for deserializing objects.

These high- level streams are each chained to a low- level stream, such as FileInputStream or FileOutputStream.
The low- level streams handle the bytes of data. The writeObject method saves the state of the class by writing
the individual fields to the ObjectOutputStream. The readObject method is used to deserialize the object from
34

the object input stream.


Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
String:
String comparison
We should use ".equals" rather than "==" to avoid unexpected outcome. It simply because ".equals" will
compare 2 strings character by character to determine equality while "==" checks whether 2 string objects are
identical. Try to do this experiment and you will understand:

String a = new String ("a");


String b = new String ("a");
System.out.println (a == b);

It returns false.

String a = new String ("a");


String b = new String ("a");
System.out.println (a.equals(b));

It returns true.

String a = new String ("abc");


String b = new String ("ABC");
System.out.println (a.equalsIgnoreCase(b));

It returns true.

String buffer
StringBuffer Class : StringBuffer class is a mutable class unlike the String class which is immutable. Both the
capacity and character string of a StringBuffer Class. StringBuffer can be changed dynamically. String buffers
are preferred when heavy modification of character strings is involved (appending, inserting, deleting,
modifying etc).

Strings can be obtained from string buffers. Since the StringBuffer class does not override the equals() method
from the Object class, contents of string buffers should be converted to String objects for string comparison.
A StringIndexOutOfBoundsException is thrown if an index is not valid when using wrong index in String
Buffer manipulations

public class StringBufferDemo {

public static void main(String[] args) {


// Examples of Creation of Strings
StringBuffer strBuf1 = new StringBuffer("Bob");
StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100
StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16
System.out.println("strBuf1 : " + strBuf1);
System.out.println("strBuf2 capacity : " + strBuf2.capacity());
System.out.println("strBuf3 capacity : " + strBuf3.capacity());
35

}
Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
Output
strBuf1 : Bob
strBuf2 capacity : 100
strBuf3 capacity : 16
StringBuffer Functions

Some StringBuffer methods :

1. capacity() : Returns the current capacity of the String buffer.

2. length() : Returns the length (character count) of this string buffer.

3. charAt(int index) :The specified character of the sequence currently represented by the string buffer, as
indicated by the index argument, is returned.

4. setCharAt(int index, char ch) : The character at the specified index of this string buffer is set to ch

5. toString() : Converts to a string representing the data in this string buffer

6. insert(int offset, char c) : Inserts the string representation of the char argument into this string buffer.
Note that the StringBuffer class has got many overloaded ‗insert‘ methods which can be used based on the
application need.

7. delete(int start, int end) : Removes the characters in a substring of this StringBuffer

8. replace(int start, int end, String str) : Replaces the characters in a substring of this StringBuffer with
characters in the specified String.

9. reverse() : The character sequence contained in this string buffer is replaced by the reverse of the sequence.

10. append(String str) : Appends the string to this string buffer. Note that the StringBuffer class has got many
overloaded ‗append‘ methods which can be used based on the application need.

11. setLength(int newLength) : Sets the length of this String buffer.

Exception handling
An exception can be defined as an unexpected event that occurs during the execution of a program and disrupts
the normal of instructions.

The exception- handling facility of Java allows programs to handle abnormal and unexpected situations in a
structured and orderly manner.
36

The exception handling mechanism is made up of the following elements:


Page

try blocks

Visit ExamFear.com for Free Question Papers for almost all Exams.
catch blocks
throw expressions
Exception specific

Catching Exceptions:

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed
around the code that might generate an exception. Code within a try/catch block is referred to as protected code,
and the syntax for using try/catch looks like the following:

try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in
protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred
is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a
method parameter.
Example:

The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array
which throws an exception.

// File Name : ExcepTest.java


import java.io.*;
public class ExcepTest{

public static void main(String args[]){


try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
37

}
Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
This would produce following result:

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3


Out of the block

Multiple catch Blocks:

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the
following:

try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}

The previous statements demonstrate three catch blocks, but you can have any number of them after a single try.
If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the
data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes
down to the second catch statement. This continues until the exception either is caught or falls through all
catches, in which case the current method stops execution and the excep tion is thrown down to the previous
method on the call stack.

Example: Here is code segment showing how to use multiple try/catch statements.

try
{
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i)
{
i.printStackTrace();
return -1;
38

}catch(FileNotFoundException f) //Not valid!


Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
f.printStackTrace();
return -1;
}

The throws/throw Keywords:


If a method does not handle a checked exception, the method must declare it using the throws keyword. The
throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the
throw keyword. Try to understand the different in throws and throw keywords.

The following method declares that it throws a RemoteException:

import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}

A method can declare that it throws more than one exception, in which case the exceptions are declared in a list
separated by commas. For example, the following method declares that it throws a RemoteException and an
InsufficientFundsException:

import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}

The finally Keyword


39

The finally keyword is used to create a block of code that follows a try block. A finally block of code always
executes, whether or not an exception has occurred.
Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what
happens in the protected code.

A finally block appears at the end of the catch blocks and has the following syntax:

try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}

Example:

public class ExcepTest{

public static void main(String args[]){


int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}
}
}
40

This would produce following result:


Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

Note the followings:


A catch clause cannot exist without a try statement.
It is not compulsory to have finally clauses when ever a try/catch block is present.
The try block cannot be present without either catch clause or finally clause.
Any code cannot be present in between the try, catch, finally blocks.

Declaring you own Exception:

You can create your own exceptions in Java. Keep the following points in mind when writing your own
exception classes:

All exceptions must be a child of Throwable.


If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule,
you need to extend the Exception class.
If you want to write a runtime exception, you need to extend the RuntimeException class.

We can define our own Exception class as below:

class MyException extends Exception{


}

You just need to extend the Exception class to create your own Exception class. These are considered to be
checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends
the Exception class, making it a checked exception. An exception class is like any other class, containing useful
fields and methods.

Polymorphism
Polymorphism enables one common interface for many implementations, and for objects to act differently
under different circumstances.Java supports several kinds of static (compile-time) and dynamic (run-time)
polymorphisms. Compile-time polymorphism does not allow for certain run-time decisions, while run-time
polymorphism typically incurs a performance penalty.

Let us summarize:

If an object A wishes object B to achieve some objective , it conveys this to object b by sending a message .The
set of action taken by object B to achieve the end objective is called the method ;in other words , an object
responds to a message using a method .Different objects may use different methods in response to the same
41

message.
Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
The term polymorphism has been derived from greek words ‗poly‘ and ‗morphos‘ which means ‗many and
‗forms‘ respectively .

Polymorphism broadly divided in two types:


• Static polymorphism – exhibited by overloaded functions.
• Dynamic polymorphism – exhibited by using late binding.

Static Polymorphism
Static polymorphism refers to an entity existing in different physical forms simultaneously. Static
polymorphism involves binding of functions based on the number, type, and sequence of arguments. The
various types of parameters are specified in the function declaration, and therefore the function can be bound to
calls at compile time. This form of association is called early binding. The term early binding stems from the
fact that when the program is executed, the calls are already bound to the appropriate functions.

The resolution of a function call is based on number, type, and sequence of arguments declared for each form of
the function. Consider the following function declaration:

void add(int , int);

void add(float, float);

When the add() function is invoked, the parameters passed to it will determine which version of the function
will be executed. This resolution is done at compile time.

Dynamic Polymorphism
Dynamic polymorphism refers to an entity changing its form depending on the circumstances. A function is said
to exhibit dynamic polymorphism when it exists in more than one form, and calls to its various forms are
resolved dynamically when the program is executed. The term late binding refers to the resolution of the
functions at run-time instead of compile time. This feature increases the flexibility of the program by allowing
the appropriate method to be invoked, depending on the context.

Static Vs Dynamic Polymorphism


Static polymorphism is considered more efficient, and dynamic polymorphism more flexible. Statically bound
methods are those methods that are bound to their calls at compile time. Dynamic function calls are bound to
the functions during run-time. This involves the additional step of searching the functions during run-time. On
the other hand, no run-time search is required for statically bound functions.

As applications are becoming larger and more complicated, the need for flexibility is increasing rapidly. Most
users have to periodically upgrade their software, and this could become a very tedious task if static
42

polymorphism is applied. This is because any change in requirements requires a major modification in the code.
Page

Visit ExamFear.com for Free Question Papers for almost all Exams.
In the case of dynamic binding, the function calls are resolved at run-time, thereby giving the user the flexibility
to alter the call without having to modify the code.

To the programmer, efficiency and performance would probably be a primary concern, but to the user,
flexibility or maintainability may be much more important. The decision is thus a trade-off between efficiency
and flexibility.

Type Casting
Converting an expression of a given type into another type is known as type-casting. We have already seen
some ways to type cast:

Implicit conversion
Implicit conversions do not require any operator. They are automatically performed when a value is copied to a
compatible type. For example:
short a=2000;

int b;

b=a;

Here, the value of a has been promoted from short to int and we have not had to specify any type-casting
operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and
allow conversions such as the conversions between numerical types (short to int, int to float, double to int...), to
or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which
the compiler can signal with a warning. This can be avoided with an explicit conversion.

Implicit conversions also include constructor or operator conversions, which affect classes that include specific
constructors or operator functions to perform conversions. For example:

class A {};

class B { public: B (A a) {} };

A a;

B b=a;

Here, a implicit conversion happened between objects of class A and class B, because B has a constructor that
takes an object of class A as parameter. Therefore implicit conversions from A to B are allowed.

Explicit conversion
43

Java is a strong-typed language. Many conversions, especially those that imply a different interpretation of the
value, require an explicit conversion. We have already seen two notations for explicit type conversion:
Page

functional and c- like casting:

Visit ExamFear.com for Free Question Papers for almost all Exams.
short a=2000;int b;

b = (int) a; // c- like cast notation

b = int (a); // functional notation

44
Page

Visit ExamFear.com for Free Question Papers for almost all Exams.