Вы находитесь на странице: 1из 46

Core Java

INDEX
1. Introduction to JAVA
History
Features
Java Components
JDK
JVM
Byte code
Java and Internet
Object Oriented programming principles
Types of java programs
2. Java Programming Features
Variable and Variable declaration rules.
Keywords
Identifier
Token
Literals
Character set
Data types
Array
Command Line Parameters
Operators and types
Conditional statements
Looping statements
Break and continue statements
Octal and Hexadecimal no’s in java
3. Classes and Objects
Class basics and structure of class
Object and object initialization
Access specifiers or modifiers
‘this’ keyword
Garbage Collection
Method Overloading
Constructor
Need of constructor
Parameterized constructor and constructor overloading
Nested and inner classes
Passing objects as a parameters to the constructor and methods
Static member and methods
4. Inheritance
Inheritance basics
Types of inheritance
‘Super’ keyword
finalize method
Dynamic method dispatch
‘final’ keyword
Multilevel inheritance
Abstract method and class
Interface
5. Wrapper Classes
Number class
Byte class
Short class
Integer class
Long class
Float class
Double class
Boolean class
Character class
Arrays class
Vector class
String class
6. Exception Handling
Exception Basics
Exception class Hierarchy
Common Exception classes
‘try----catch----finally’ construct
throw and throws keywords
user defined Exceptions
7. Multithreading
Thread basics
Advantages of multithreading
Thread priorities
Main thread
Thread class
Thread life cycle
Thread class methods
Creating our own threads
Runnable interface
Thread Synchronization
Thread Interprocess Communication
8. Applet Basics
Applet and Internet
Application Vs Applet
Applet class and methods
Applet life cycle
HTML <Applet> tag
Passing parameters to the Applet
getDocumentBase() and getCodeBase() methods
9. Awt and Event Handling
Awt Basics
Awt Containers
Panel and Frame
Awt Componenets
Label, TextField, TextArea, Button, List, Choice,
Scrollbar, Checkbox and Radio Buttons
Awt Graphics classes
Font, Graphics and Color classes
Layout Managers
FlowLayout, BorderLayout, GridLayout, CardLayout
Menu bar and Menu
Event Handling
Event classes
ActionEvent, ItemEvent, AdjustmentEvent,
WindowEvent, FocusEvent, MouseEvent,
MouseWheelEvent, ContainerEvent, ComponentEvent
Listeners
ActionListener, ItemListener, AdjustmentListener,
WindowListener, FocusListener, MouseListener,
MouseWheelListener, ContainerListener, Component
Listener
Anonymous inner classes
Adapter classes
10. File Input Output in Java
File Class
RandomAccessFile Class
FileNameFilter Interface
Stream
Types Of streams
Byte streams
InputStream FileInputStream, ByteArrayInputStream,
BufferedInputStream, DataInputStream
OutputStream
FileOutputStream
ByteArrayOutputStream
BufferedOutputStream
DataOutputStream
PrintStream
CharacterStreams
Reader
FileReader
InputStreamReader
BufferedReader
CharArrayReader
PushBackReader
Writer
FileWriter
CharArrayWriter
BufferedWriter
Serialization and Deserialization
ObjectInputStream and ObjectOutputStream classes
1. Introduction to Java
A Brief History of Java: -
Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and
Mike Sheridan at Sun Microsystems, Inc.in 1991.It took 18 months to develop the first
working version. This language was initially called ‘Oak’ but was renamed “Java ” in
1995.Between the initial implementation of Oak in the fall of 1992 and the public
announcement of Java in the spring of 1995,many more people contributed to the
design and evolution of the language.
Initial purpose of this language development is not Internet. Actually this
language is designed for embedded software, which is used in Control system and
Electronic devices. At the same time the concept of WWW is emerging in the market,
which requires a platform independent and portable language. Because of platform
independency and portability java is used for Internet. Now java is used in embedded
software, Internet Applications and Business applications development.

Features of Java
1.Simple and Powerful
The syntaxes of Java are almost similar to C and C++ so java is easy to
learn C and C++ programmer.
To run a Java program it requires a less hardware specification than any other
language.
2.Compiled and Interpreted
Actually programming languages are compiled or interpreted but java is
compiled as well as interpreted language. Java enables the creation of cross-platform
programs by compiling into an intermediate representation called Java bytecode. This
code can be interpreted on any system that provides a Java Virtual Machine.
3.Secure
While downloading applications from Internet there is no chance to attach a
virus with Java Applications and Applets. Java Runtime System provides Bytecode
verifier, which will, checks complete code before execution of program.

4.Portable
We can design java programs on any type of machine also we can run java
programs on any Machine.

When an applet is encountered on a Web page (if the user's browser can handle Java),
the browser downloads the applet along with the text and images on the page. The
applet then runs on the user's computer. This act should raise a red flag-danger!
Danger! -Because a lot of harmful things can occur when programs are executed:
viruses, Trojan horses, the Microsoft Network, and so on.
5.Platform Independent

When java program is compiled it will not generate directly an


executable code like C and C++. Rather when java program is compiled it compiler
generates a byte code which can run on any platform (Operating System). Bytecode is
executed by JVM (Java Virtual Machine). JVM may differ from platform to platform.
But all JVM interprets same bytecode. JVM generates Native code, which can
understood by Processors.
6. Multithreading
Java was designed to meet the real-world requirement of creating interactive,
networked programs. To accomplish this, Java supports multithreaded programming,
which allows you to write programs that do many things simultaneously.

7. Garbage Collection
In other languages when object is allocated memory space at runtime that
object will not free automatically. These objects are manually freed from the memory.
Java Runtime provides a utility called Garbage Collector (gc method). When
JVM reaches a free time it will run gc method, which will checks the scope of all
objects, stored in the memory. Garbage Collector frees all memory allocated by
unused objects and make chance for allocation of new objects.

8.Distributed Environment
Internet is used in Distributed Environment. In network environment
communication is going on through protocols. Internet uses TCP/IP protocol for
communication. Java can understand TCP/IP protocols.

9. Database Support
Database Managements Systems are used in Business Application for
permanent storage of data. Java provides inbuilt tools for database communication.

Java Components
ByteCode and JVM
The key that allows Java to solve both the security and the portability problems just
described is that the output of a Java compiler is not executable code. Rather, it is
bytecode. Bytecode is a highly optimized set of instructions designed to be executed
by the Java run-time system, which is called the Java Virtual Machine (JVM).
Bytecode is stored in class file. That is, in its standard form, the JVM is an interpreter
for bytecode. This may come as a bit of a surprise. As you know, C++ is compiled to
executable code. In fact, most modern languages are designed to be compiled, not
interpreted —mostly because of performance concerns. However, the fact that a Java
program is executed by the JVM helps solve the major problems associated with
downloading programs over the Internet.
Translating a Java program into byte code helps makes it much easier to run a
Program in a wide variety of environments. The reason is straightforward: only the
JVM needs to be implemented for each platform. Once the run-time package exists for
a given system, any Java program can run on it. Remember, although the details of the
JVM will differ from platform to platform, all interpret the same Java byte code. If a
Java program were compiled to native code, then different versions of the same
program would have to exist for each type of CPU connected to the Internet. This is,
of course, not a feasible solution. Thus, the interpretation of bytecode is the easiest
way to create truly portable programs.

JDK and JDK tools.


JDK
Of course, in order to write Java applications or applets, you need more than a
language-you need the tools that let you write, test, and debug your programs. This
section gives a very high-level overview of the various Java tools that come with the
Java Developer's Kit

JDK tools
Compiler
There is, of course, a Java compiler, named javac. The Java compiler takes input
source code files (these files typically have the extension .java) and converts them into
compiled byte code files
Interpreter
The Java interpreter can be used to execute Java applications. The interpreter
translates byte codes directly into native code. (program actions)
Debugger
The Java debugger, jdb, enables you to debug your Java classes. Unfortunately, the
Java debugger is a throwback to the pre-GUI debugger dark ages of programming.
The Java debugger is a command-line debugger that is enough to make you wish for
even the 1988 version of CodeView. However, you can use the jdb to set breakpoints,
inspect objects and variables, and monitor threads
Header File Generator
Because Java is a new language and must fit in a world dominated by C and C++,
included in Java is the capability to use native C code within a Java class. One of the
steps in doing this is using the Java header file generator, javah.
Applet Viewer
If you will be writing Java applets, you will definitely want to become familiar with
the Applet Viewer. This small program provides a real Java environment for testing
applets. It loads the HTML file in which the applet has been embedded and displays
the application in a browser-like window

Java and Internet


Current Web development technologies excel at displaying this type of page. Much of
human communication is passive, static, or both. A highway billboard is a perfect
example of a conventional means of communication that is both passive and static.
Just as not all billboards will go the way of Burma Shave, not all passive, static
WWW content needs to become active and dynamic (the opposites of passive and
static).

However, Java is an enabling technology that allows for the creation of more powerful
pages. Continuing with the example of a page that shows the price of a stock at a
given point in time, you could use Java to create a page that shows a graph of a stock's
price over time and have that graph continue to update in real time while you browse
the page. This is where Java comes in-because Java is a full-featured programming
language, Web pages like this become much more feasible. Sun Microsystems has
created a page that does exactly this.

First Java Program


class First
{
public static void main(String args[])
{
System.out.pritln (“Welcome to java programming world”);
}
}
How to run above program
1) Type this file in any text editor and save this file as First.java.
2) Compile this file as
C:\jdk1.2\bin>javac First. java
3) Run this file as
C:\jdk1.2\bin> java First

Explanation of above program:-


class First
Here class is the keyword used to define the classes in java
First is the class name (Identifier) By convention class names first letter
is the upper case Letter in Java.

public static void main(String args[])

public is the access specifier allows us to call the main method out of this class.
static is the keyword allows us to call this method without creating an instance
of this class.
void indicates main method does not return any value.
main is the name of method which indicated main method does not return
any value.

String args[]
Is the array of string which values are passed at commandline
While interpretation of this program.
System.out.println(“Welcome to java programming world”);
println is the method defined in PrintStream class, allows us to print any string
or values of variables on standard output device (Monitor).
out is the static object of PrintStream class defined in System class.
System.out.println
Above method prints the specified string or results of calculations on output
stream. Here “Welcome to java programming world” is printed on output stream.

OOP principles
1. Encapsulation
2. Polymorphism
3. Inheritance
Encapsulation
Encapsulations is the mechanism that binds code and data together,and keep
safe from outside interference and missue. Everything that the software object knows
and can do is expressed by the variable and methods within that object.
Inheritance
Inheritance is the process of creating a new class(object) from existing
class(object) where newly created class is known as child or derived or sub class and
already existing class is known as parent or base or super class. Child class has the
ability to access all member functions and attributes of base class. Also it can include
its own data member and member functions. Code reusability is the key advantage of
inheritance.
Polymorphism
Poly means many and morphism means forms.We can use the same name for
multiple tasks. For example we can specify the same name for different functions.

Types of Java Program


There are 2 types of java programs
1.Application
An Application is a program that runs on a computer under the operating system of
that computer. That is, an application created by java is like one created using C or C+
+. Application program provides CLI (Command line Interface) and GUI (Graphical
User Interface).
2.Applet
Applet is a special program designed to be transmitted over the internet and executed
on java compatible web browsers. Actually it is a java program, dynamically
downloaded across Internet just like image, sound file or video clip.
Question Bank
1. Why java is popular for Internet?
2. Why java is platform independent?
3. Explain features of java.
4. Explain JVM and Bytecode
5. Explain Different Components of JDK
6. Why java is not fully object oriented programming language?
7. Why java programs class name and file name should be same?
8. Explain Object Oriented Principles.
9. Explain “public static void main(String args[])”
10. Explain types of Java Programs.
2.Java Programming Features
Character set
Java Program is created using set of characters. These characters
are called as Character set of Java. Java’s character set includes

A-------Z 26 Characters
a---------z 26 characters
0---------9 10 digits
Special characters 32 characters
------------------
94 characters

Tokens
Java Program is formed by the combination of above characters. The word formed
from the character set is called token.
Following are the different types of tokens in java program.
 Keywords
 Identifiers
 Constants
 Operators
 Punctuation Symbols

Identifier
An identifier is a word used by a programmer to name a variable, method and class.
Keywords are reserved words may not be used as identifier.
Following are some valid identifiers
average, net_pay, withdrawamount etc
Some invalid identifiers
3-mod2, $amount, #time etc

Variable
Variable is a given name to the memory location where the values are stored.
The value of the variable can be changed during the programs execution.
Rules for variable declaration
 Variable name should be start with alphabet.
 No special characters are used in variable name except under score( _
 Keywords of java cannot be used as a variable name.
 White spaces are not allowed in variable name.
 Java is case sensitive language. Hence uppercase and lowercase alphabets
are treated as different.
By convention variable names are declared in small case letters.
Keywords
Keywords are special reserved words provided by language developers whose
meaning is already known to the compiler and interpreter. Keywords cannot be used
as a variable name, method name and class name because we are assigning a new
meaning to that words, which is not allowed by java.
Actually java contains 60 keywords out of them 49 are used to
date. Keywords are also called reserved words.
abstract continue goto package synchronized

assert private this interface class


default protected throw Static float
if public throws long native
boolean else instanceof char super
do byte return finally while

implements transient case strictfp const

break extends int volatile for


double short catch switch new
import final try void

Literals
Using a literal representation of it creates a constant value in Java.
Here are different types of literals
1) Integer Literals
2) Floating Literals
3) Character and String Literals
4) Boolean Literals

100 98.6 ‘X ’ “This is a test ” true


Left to right, the first literal specifies an integer, the next is a floating-point value, the
third is a character constant fourth is a string a and last is boolean literal. A literal can
be used anywhere a value of its type is allowed.

Data Types
When we are declaring variables we should specify its type of the variable, it
means what type of data the variable contains and how much memory space is
required to store that value.
The data types are categorized in following categories.
1) Integer
2) Floating point
3) Character
4) Boolean
Integer data type
Basically integer data types are the data type, which
always contains whole no’s
INTEGER TYPE SIZE CAPACITY
byte 8 bits -128 to 127
short 16 bits -32768 to 32767
int 32 bits -231 to 231-1
long 64 bits -2 63 to 263-1

Floating Data Types


Floating data types are the data types, which always contain numbers with
decimal point.
Float data types further divided in following categories.
FLOAT TYPE SIZE CAPACITY
float 32 bits 3.40282347E+38 F to
-3.40282347E+38 F
double 64 bits 1.79769313486231570E308to
-1.79769313486231570E308

Character Data Type


In java char data type is used to store character value. Java uses Unicode character set
to represent characters. The size of char data type is 2 bytes ranging from 0 to 65535.

Example
char c=’a’;
Declaring constant Variables in java
The value of constant variable cannot change throughout the program. Constants are
declared in java by using ‘final’ keyword. By convention keywords are declared in
uppercase only.
Example
final float PI=3.14F;
Using Command-Line Arguments
Sometimes you will want to pass information into a program when you run it.This
is accomplished by passing command-line arguments to main().A command-line
argument is the information that directly follows the program ’s name on the
command line when it is executed. To access the command-line arguments inside a
Java program is quite easy —they are stored as strings in the String array passed to
main()
Operators
Operators are special symbols used for mathematical, logical and bitwise
operations
Following are the categories of operators
1) Unary operators
A Unary operator operates on only one operand.
2) Binary Operators
A binary operator operates on 2 operands.
3) Ternary operators
A ternary operator operates on 3 operands.

Following are the different types of operators


1) Arithmetic Operators
2) Relational Operators
3) Logical Operators
4) Bitwise Operators
5) Shift Operators

Arithmetic operators
Arithmetic operators are used to perform arithmetic operations.
Following table shows the arithmetic operators
Here consider int a=20, b=10;

OPERATOR MEANNING EXAMPLE RESULT


++ Increment a++ a=21
-- Decrement a-- a=19
+ Addition a+b 30
- Subtraction a-b 10
* Multiplication a*b 200
/ Division a/b 2
% Modulus a%3 2
+= Addition Assignment a+=10 a=30
-= Subtraction Assignment a-=10 a=10
*= Multiplication Assignment A*=2 a=40
/= Division Assignment a/=2 a=10
%= Modulus Assignment a%=2 a=2

Relational Operators
These operators are used to compare two values. These operators always return
one Boolean value after execution of relational expression. Following is the list of
relational operators used in java. Relational operators are used with conditional
statements.
Consider
int i=20,j=10;
OPERATOR MEANING EXAMPLE RESULT
< Less than a<b False
> Greater than a>b True
== Equal to a= =b False
!= Not equal to a!=b True
<= Less than equal to a<=b False
>= Greater than equal to a>=b True

Logical operators
The Logical operators are used to compare more than conditions simultaneously
i.e. we can combine more than one condition and form one unique condition.

Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

&& Operator returns True if all specified conditions are true.


| | Operator returns True if one of the conditions is true among specified
conditions.
! Operator negates the specified expression.

The Bitwise Logical Operators


Java defines several bitwise operators which can be applied to the integer types,long
,int ,short ,char ,and byte .These operators act upon the individual bits of their
operands.
They are summarized in the following table:
Operator Meaning
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
The bitwise logical operators are &, |, ^, and ~. The following table shows the
outcome of each operation. In the discussion that follows, keep in mind that the
bitwise operators are applied to each individual bit within each operand.
A B A |B A &B A^B ~A
0 0 0 0 0 1
1 0 1 0 1 0
0 1 1 0 1 1
1 1 1 1 0 0
The Bitwise NOT
Also called the bitwise complement,the unary NOT operator,~,inverts all of the
bits of
its operand.For example,the number 42,which has the following bit pattern:
00101010
becomes
11010101
after the NOT operator is applied.
The Bitwise AND
The AND operator,&,produces a 1 bit if both operands are also 1.A zero is
produced in all other cases.
Here is an example:
00101010 42
& 00001111 15
--------------
00001010 10
The Bitwise OR
The OR operator,|,combines bits such that if either of the bits in the operands is
a 1,
then the resultant bit is a 1,as shown here:
00101010 42
| 00001111 15
--------------
00101111 47
UAGE

The Bitwise XOR


The XOR operator,^,combines bits such that if exactly one operand is 1,then the result
is 1.Otherwise,the result is zero.The following example shows the effect of the ^.This
example also demonstrates a useful attribute of the XOR operation.Notice how the bit
pattern of 42 is inverted wherever the second operand has a 1 bit.Wherever the second
operand has a 0 bit,the first operand is unchanged.You will find this property useful
when performing some types of bit manipulations.
00101010 42
^ 00001111 15
-------------
00100101 37
Bitwise Shift Operators
Java provides << , >> shift operators for shifting of bits. Shifting of bits is used
in control system. Shift operators are always used with integer data types.

The Left Shift


The left shift operator ’<<’ shifts all of the bits in a value to the left a specified
number of times. It has this general form:
value <<num
Here, num specifies the number of positions to left-shift the value in value. That is, the
<<moves all of the bits in the specified value to the left by the number of bit positions
specified by num.

For example
int x=12;
x=x << 2
12= 00001100
Result = 48= 00110000
After execution of above shift operation x contains 48
The Right Shift
The right shift operator,>>,shifts all of the bits in a value to the right a specified
number of times.
Its general form is shown here:
value >>num
Here,num specifies the number of positions to right-shift the value in value.That is,the
>>moves all of the bits in the specified value to the right the number of bit positions
specified by num.
The following code fragment shifts the value 32 to the right by two positions,
resulting in a being set to 8:
int a = 32;
a= a >> 2; // a now contains 8

Control Statements
A programming language uses control statements to cause the flow of execution to
advance and branch based on changes to the state of a program. Java ’s program
control statements can be put into the following categories: selection, iteration, and
jump. Selection statements allow your program to choose different paths of execution
based upon the outcome of an expression or the state of a variable. Iteration
statements enable program execution to repeat one or more statements
Selection Statements or conditional statements
Java supports two selection statements :if and switch .These statements allow you to
control the flow of your program ’s execution based upon conditions known only
during run time. You will be pleasantly surprised by the power and flexibility
contained in these two statements.
if statement
The if statement is Java ’s conditional branch statement. It can be used to route
program execution through two different paths.
Here is the general form of the if statement:
if (condition )
{
//Block of java code
}
else
{
// block of code
}
Here, each statement may be a single statement or a compound statement enclosed in
curly braces (that is, a block ). The condition is any expression that returns a boolean
value. The else clause is optional. The if works like this: If the condition is true, then
block1 is executed. Otherwise, Block2 (if it exists) is executed. In no case will both
statements be executed.
For example, consider the following:
int a, b;
if(a < b)
a = 0;
else
b = 0;

Here, if a is less than b ,then a is set to zero. Otherwise, b is set to zero. In no case are
they both set to zero.
Most often, the expression used to control the if will involve the relational operators.
TH The if-else-if Ladder
A common programming construct that is based upon a sequence of nested if s is the
if-else-if ladder .
It looks like this:
if(condition )
{
Block of code;
}
else if (condition)
{
Block of code;
}
else if(condition )
{
Block of code;
}
--------
else
{
Block of code
}

THEE The if statements are executed from the top down. As soon as one of the
conditions controlling the if is true ,the statement associated with that if is executed,
and the rest of the ladder is bypassed. If none of the conditions is true, then the final
else statement will be executed. The final else acts as a default condition; that is, if all
other conditional tests fail, then the last else statement is performed. If there is no final
else and all other conditions are false ,then no action will take place.

switch statement
The switch statement is Java ’s multiway branch statement. It provides an easy way
to dispatch execution to different parts of your code based on the value of an
expression. As such, it often provides a better alternative than a large series of if-else-
if statements. Here is the general form of a switch statement:
switch (expression )
{
case value1 :
//statement sequence
break;
case value2 :
//statement sequence
break;
.
.
.
case valueN :
//statement sequence
break;
default:
//default statement sequence
}
The expression must be of type byte ,short ,int ,or char ;each of the values specified
in the case statements must be of a type compatible with the expression. Each case
value must be a unique literal (that is,it must be a constant,not a variable). Duplicate
case values are not allowed. The switch statement works like this:The value of the
expression is compared with each of the literal values in the case statements.If a
match is found,the code sequence following that case statement is executed.If none of
the constants matches the value of the expression,then the default statement is
executed.However,the default statement
is optional.If no case matches and no default is present,then no further action is taken.
The break statement is used inside the switch to terminate a statement sequence.
When a break statement is encountered,execution branches to the first line of code
that follows the entire switch statement. This has the effect of “jumping out ” of the
switch .

Looping Statements or Iteration statements


Iteration Statements
Java ’s iteration statements are for ,while ,and do-while .These statements create what
we commonly call loops.As you probably know,a loop repeatedly executes the same
set of instructions until a termination condition is met.As you will see,Java has a loop
to fit any programming need.
while Loop
The while loop is Java ’s most fundamental looping statement.It repeats a statement or
block while its controlling expression is true.Here is its general form:
while(condition )
{
//body of loop
}

The condition can be any Boolean expression. The body of the loop will be executed
as long as the conditional expression is true. When condition becomes false, control
passes to the next line of code immediately following the loop. The curly braces are
unnecessary if only a single statement is being repeated.
do-while loop
As you just saw, if the conditional expression controlling a while loop is initially
false, then the body of the loop will not be executed at all. However, sometimes it is
desirable to execute the body of a while loop at least once, even if the conditional
expression is false to begin with. In other words, there are times when you would like
to test the termination expression at the end of the loop rather than at the beginning.
Fortunately, Java supplies a loop that does just that: the do-while .The do-while loop
always executes its body at least once, because its conditional expression is at the
bottom of the loop. Its general form is

do {

//body of loop
}while (condition );

Each iteration of the do-while loop first executes the body of the loop and then
evaluates the conditional expression. If this expression is true, the loop will repeat.
Otherwise, the loop terminates. As with all of Java ’s loops, condition must be a
Boolean expression.
LANGUAGE

for loop
You were introduced to a simple form of the for loop in Chapter 2.As you will see, it
is a powerful and versatile construct. Here is the general form of the for statement:
for(initialization ;condition ;iteration )
{
//body
}
If only one statement is being repeated, there is no need for the curly braces. The for
loop operates as follows. When the loop first starts, the initialization portion of the
loop is executed. Generally, this is an expression that sets the value of the loop control
variable, which acts as a counter that controls the loop. It is important to understand
that the initialization expression is only executed once. Next, condition is evaluated.
This must be a Boolean expression. It usually tests the loop control variable against a
target value. If this expression is true, then the body of the loop is executed. If it is
false ,the loop terminates. Next, the iteration portion of the loop is executed. This is
usually an expression that increments or decrements the loop control variable. The
loop then iterates, first evaluating the conditional expression, then executing the body
of the loop, and then executing the iteration expression with each pass .This process
repeats until the controlling expression is false.
break and continue statements
Using break to Exit a Loop
By using break ,you can force immediate termination of a loop, bypassing the
conditional expression and any remaining code in the body of the loop. When a break
statement is encountered inside a loop, the loop is terminated and program control
resumes at the next statement following the loop .

Using continue
Sometimes it is useful to force an early iteration of a loop.That is,you might want to
continue running the loop,but stop processing the remainder of the code in its body for
this particular iteration.This is,in effect,a goto just past the body of the loop,to the loop
’s end.The continue statement performs such an action.In while and do-while loops,a
continue statement causes control to be transferred directly to the conditional
expression that controls the loop.In a for loop,control goes first to the iteration portion
of the for statement and then to the conditional expression.For all three loops,any
intermediate code is bypassed.
Question Bank
1. Explain different data types of Data types with their memory size.
2. Explain Following operators.
i. Arithmetic Operators
ii. Bitwise Operators
iii. Relational Operators
iv. Logical Operators
v. Shift Operators
3. Explain Conditional statements with syntaxes
4. What do you mean by looping statements? Explain Looping statements used in
java programming
5. Why java avoids the use of goto statement?
6. Explain break and continue statement
7. Explain the process of data type conversion in java.
8. Explain the advantages of switch case statement over ladder if else if statement
9. Explain the following terms
Keywords
Identifiers
Token
Literal
Character set
10. How we can store hexadecimal and octal no’s in integer variables
11. Explain the use of bitwise operators.
3.Classes and Objects

Class and general structure of class


The class forms the basis for object-oriented programming in Java. Any concept you
wish to implement in a Java program must be encapsulated within a class. The class is
at the core of Java.
The most important thing to understand about a class is that it defines a new
data type. Once defined, this new type can be used to create objects of that type. Thus,
a class is a template for an object, and an object is an instance of a class. In simple
words “class is a user defined data type which binds code and data together”
A class is declared by use of the class keyword. The general form of a class
definition is shown here:
class classname
{

type instance-variable1 ;
type instance-variable2 ;
-------
type instance-variableN ;
constructor(paramlist)
{
//initialization code
}
type methodname1 (parameter-list )
{
//body of method
}
type methodname2 (parameter-list )
{
//body of method
THE }
type methodnameN (parameter-list )
{
//body of method
}
}

Declaring Objects and Object Initialization


As just explained, when you create a class, you are creating a new data type. You can
use this type to declare objects of that type. However,obtaining objects of a class is a
two-step process.First,you must declare a variable of the class type.This variable does
not define an object.Instead,it is simply a variable that can refer to an object.Second,
you must acquire an actual,physical copy of the object and assign it to that
variable.You can do this using the new operator.The new operator dynamically
allocates (that is,allocates at run time)memory for an object and returns a reference to
it.This reference is,more or less,the address in memory of the object allocated by new
. This reference is then stored in the variable.Thus,in Java,all class objects must be
dynamically allocated.Following is the syntax of object declaration in java.

Classname object; //Object declaration

e.g.
Student s;
object=new Classname([param list]); //object initialization

e. g
s=new Student();

Access Specifiers/Modifiers/Controls
Encapsulation links data with the code that manipulates it.However, encapsulation
provides another important attribute:access control. Through encapsulation,you can
control what parts of a program can access the members of a class. By controlling
access,you can prevent misuse. For example, allowing access to data only through a
well-defined set of methods, you can prevent the misuse of that data.
Follwing is the list of access specifiers used in java
1) private
Private members can be accessed only within the class in which it is
defined. Private members are declared using private keyword.
2) public
Public members can be accessed within the class in which it is declared as well as
anywhere outside the class through an instance of class. Here classes can be same
package or different package. Public members are declared by using public
keyword.
3) protected
Protected members can be accessed within the class in which it is declared as well as
in its child class but here base class and child class should be within the same
package. Protected members are declared by using protected keyword.
4) friendly
When a member is declared in a class without any access specifier that is by default
considered is a friendly. Friendly access specifier behaves somewhat like public.
Friendly members are accessed within a class in which it is declared as well as
another classes within the same package. Friendly members cannot be accessed
outside the package in which it is declared.
5)public protected
When a member is declared with public protected access specifier that member can
be accessed within the class as well as in child class. Here child class may be in
different package.
Adding methods to the class
As mentioned at the beginning of this chapter,classes usually consist of two things
instance variables and methods.The topic of methods is a large one because Java gives
them so much power and flexibility.In fact,much of the next chapter is devoted to
methods.However,there are some fundamentals that you need to learn now so that you
can begin to add methods to your classes.

This is the general form of a method:


type name (parameter -list )
{
//body of method
}
Here, type specifies the type of data returned by the method.This can be any valid
type, including class types that you create.If the method does not return a value,its
return type must be void .The name of the method is specified by name.This can be
any legal identifier other than those already used by other items within the current
scope. The parameter-list is a sequence of type and identifier pairs separated by
commas. Parameters are essentially variables that receive the value of the arguments
passed to the method when it is called.If the method has no parameters,then the
parameter list will be empty. Methods that have a return type other than void return a
value to the calling routine using the following form of the return statement:
return value ;
Here,value is the value returned.

Constructor
Constructor is a special type of function which have same name as class in which it is
declared. Once a constructor is defined it is automatically called immediately after the
object is created. Following are the rules for constructor declaration
 Constructor should have same name as that of its class name.
 Constructor should not return any value.
 Constructor may take parameters
 Constructor should not be abstract or static.
Need of Constructor
A class contains one of the process which requires some data and code. Data is stored
in the form of instance variables of class. Means it will not execute a process defined
in the class without initializing the variables of class. It is difficult to initialize all the
class variables by using like getdata() method as used in all programs. So we can
define a constructor which will call automatically when the object is created of that
class and initializes the variables of class.

Parameterized constructor
If you want to assign different values to the instance variables when different
objects are created. So we make constructor which takes some argument whose value
will be assigned to variable. In short “Constructor which have arguments are known as
parameterized constructor.”
Following is the general form of constructor
NameOfClass(data type arg1,data type arg2,data type arg3----------data
type argn)
The general structure explains that the NameOfClass will be the
same name of class in which we are declaring constructor. Here arg1,
arg2--------argn represent the list of arguments used in constructor like we
declare arguments in method and the type represents the data type of arguments.
It is not mandatory that constructor must have the arguments, the constructor
may be without parameters. For example, if class Student name is Student then
the constructor can be declared as
Student( int roll ,String name)
{
//Initialization
}//Parameterized Constructor
Or
Student()
{
// Initialization
}//Without parameter constructor

‘this’ Keyword
Sometimes a method will need to refer to the object that invoked it.To allow this, Java
defines the this keyword. this can be used inside any method to refer to the current
object. That is, this is always a reference to the object on which the method was
invoked. You can use this anywhere a reference to an object of the current class ’ type
is permitted.
Instance variable hiding
you can have local variables, including formal parameters to methods,which overlap
with the names of the class instance variables.However,when a local variable has the
same name as an instance variable,the local variable hides the instance variable.

Overloading Methods
In Java it is possible to define two or more methods within the same class that share
the same name, as long as their parameter declarations are different. When this is the
case, the methods are said to be overloaded, and the process is referred to as method
overloading. Method overloading is one of the ways that Java implements compile
time polymorphism.
When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method to
actually call. Thus, overloaded methods must differ in the type and/or number of their
parameters. While overloaded methods may have different return types, the return
type alone is insufficient to distinguish two versions of a method. When Java
encounters a call to an overloaded method, it simply executes the version of the
method whose parameters match the arguments used in the call.

Static members of class


There will be times when you will want to define a class member that will be used
Independently of any object of that class. Normally a class member must be accessed
only in conjunction with an object of its class. However, it is possible to create a
member that can be used by itself, without reference to a specific instance. To create
such a member, precede its declaration with the keyword static. When a member is
declared static, it can be accessed before any objects of its class are created, and
without reference to any object. You can declare both methods and variables to be
static .The most common example of a static member is main (). main()is declared as
static because it must be called before any objects exist. Instance variables declared as
static are, essentially, global variables. When objects of its class are declared, no copy
of a static variable is made. Instead, all instances of the class share the same static
variable.

Methods declared as static have several restrictions:


 They can only call other static methods.
 They must only access static data.
 They cannot refer to this or super in any way.
If you need to do computation in order to initialize your static variables, you can
declare a static block, which gets executed exactly once, when the class is first
loaded.
Introducing Nested and Inner Classes
It is possible to define a class within another class; such classes are known as nested
classes. The scope of a nested class is bounded by the scope of its enclosing class.
When you define nested classes, inner class can access members of outer class but
outer class cannot access members of inner class.
Following are the type of inner class
1) Static inner class
2) Non static inner class

A static nested class is one which has the static modifier applied. It has access to
members of inner class and only static members of outer class.
The most important type of nested class is the inner class. An inner class is a non-
static nested class. It has access to all of the variables and methods of its outer class
and may refer to them directly in the same way that other non-static members of the
outer class do. Thus, an inner class is fully within the scope of its enclosing class.
Question Bank
1. Explain class and its general syntax.
2. Explain Object Oriented Programming principles.
3. Explain Access modifiers.
4. Explain scope of variable.
5. Explain the process of method overloading.
6. Explain Constructor and its need.
7. Explain packages with its types.
8. In what situation parameterized constructors are used?
9. Explain static members of class
10. Explain Nested and inner classes with their types.
11. Explain this keyword.
12. Explain method’s syntax? How we can add methods in the class?
13. How object is created in java? Why it is required?
4.Inheritance
Inheritance
Inheritance is one of the measure principles of object-oriented programming because
it allows the creation of hierarchical classifications. Using inheritance, you can create
general class that defines traits common to a set of related items. Other, more specific
classes can then inherit this class, each adding those things that are unique to it. In the
terminology of Java, a class that is inherited is called a superclass. The class that does
the inheriting is called a subclass. Therefore,a subclass is a specialized version of a
superclass.It inherits all of the instance variables and methods defined by the
superclass and adds its own, unique elements.
Inheritance Basics
To inherit a class, you simply incorporate the definition of one class into another by
using the extends keyword. To see how, let ’s begin with a short example. The
following program creates a superclass called StudentInfo and a subclass called
Student. . Notice how the keyword extends is used to create a subclass of Student.
class StudentInfo
{
protected String name;
protected int roll,mark1,mark2;
StudentInfo()
{
name="Raj";
roll=101;
mark1=78;
mark2=56;
}
int total()
{
return mark1+mark2;
}
void display()
{
System.out.println("Name="+name);
System.out.println("Roll="+roll);
System.out.println("Total Marks="+total ());
}
}
class StudentAvg extends StudentInfo
{
float avg;
String address;
StudentAvg(String n,int r,int m1,int m2,String a)
{
name=n;
roll=r;
mark1=m1;
mark2=m2;
address=a;
}
float calAvg()
{
avg=total()/2;
return avg;
}
void show()
{
display();
System.out.println("Average="+calAvg());
System.out.println("Address="+address);
}
}
class studentdemo
{
public static void main(String sp[])
{
StudentAvg obj=new StudentAvg("Yash",101,78,49,"Solapur");
obj.show();
}
}
A Superclass Variable Can Reference a Subclass Object
A reference variable of a superclass can be assigned a reference to any subclass
derived from that superclass.You will find this aspect of inheritance quite useful in a
variety of situations.For example,consider the following:
class Base
{
void show()
{
System.out.println(“I am Base”);
}
}
class Child extends Base
{
void display()
{
System.out.println(“I am child”);
}
}
class BaseChild
{
public static void main(String args[])
{
Base b=new Base();
b.show();
b=new Child();
b.display();
}
}
Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type
signature as a method in its superclass, then the method in the subclass is said to
override the method in the superclass. When an overridden method is called from
within a subclass, it will always refer to the version of that method defined by the
subclass. The version of the method defined by the superclass will be hidden.
Consider the following:
Super Keyword
In java there is a keyword named ‘super’ which is used in inheritance. super keyword
is used for the following purposes.
1. To access the private members of base class in child class by calling the
constructor of base class in child class. But the constructor calling statement
should be the first statement in the child constructor definition.
2. To access the members of base class in the child class having same name.
3. To call the method of base class in the child class having same name.
Following program demonstrates the use of super keyword.

// Method overriding and super keyword


class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
// display i and j
void show()
{
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show()
{
System.out.println("k: " + k);
}

}
class Override
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}

final keyword
final is one of the keyword used in java program for following purposes
1. To declare the constant variables in java.
e.g. final float PI=3.14F;
2. To prevent a method from overriding, e .g if one of the method is defined in the
base class as a final then that method can’t be override in the child class.
3. To prevent the class from inheritance. If one of the class is declared as final
then any other classes can’t inherit to the final classes.
Following program demonstrates the use of final keyword.
final class Area
{
final float PI=3.14F;
final float calArea(float r)
{
return PI*r*r;
}
void display()
{
System.out.println(“Area of circle=”+calArea(5.6F));
{
}
class FinalDemo
{
public static void main(String str[])
{
Area obj=new Area();
Obj.display();
}
}
In the above program PI variable declared as a final(constant) e.g the value of
the PI variable cannot be changed. Area class is also declared as a final so no any
other classes can inherit the Area class. CalArea() method is declared as a final means
the calArea cannot be overridden in the child class.

Dynamic method dispatch


Dynamic method dispatch is the mechanism by which a call to an overridden method
is resolved at run time, rather than compile time. Dynamic method dispatch is
important because this is how Java implements run-time polymorphism. Let ’s begin
by restating an important principle:a superclass reference variable can refer to a
subclass object. Java uses this fact to resolve calls to overridden methods at run time.
Here is how. When an overridden method is called through a superclass reference,
Java determines which version of that method to execute based upon the type of the
object being referred to at the time the call occurs. Thus, this determination is made at
run time. When different types of objects are referred to, different versions of an
overridden method will be called. In other words, it is the type of the object being
referred to (not the type of the reference variable) that determines which version of an
overridden method will be executed. Therefore, if a superclass contains a method that
is overridden by a subclass, then when different types of objects are referred to
through a superclass reference variable, different versions of the method are executed.

Following program demonstrates the use of Dynamic method dispatch.


class Base
{
void display()
{
System.out.println(“Hello from base class”);
}
}
class Child extends Base
{
void display()
{
System.out.println(“Hello from child class”);
}
}
class DynamicDemo
{
public static void main(String args[])
{
Base b=new Base();
b.display();
b=new Child();
b.display();
}
}
Here in above program base class object b pints to the base class first time it will calls
the display method of base class. When base class object points to the child class then
it will calls the method of child class.

Abstract class
There are situations in which you will want to define a superclass that declares the
structure of a given abstraction without providing a complete implementation of every
method. That is, sometimes you will want to create a superclass that only defines a
generalized form that will be shared by all of its subclasses, leaving it to each subclass
to fill in the details. Such a class determines the nature of the methods that the
subclasses must implement. One way this situation can occur is when a superclass is
unable to create a meaningful implementation for a method. These methods are
sometimes referred to as subclasser responsibility because they have no
implementation specified in the superclass. Thus, a subclass must override them —it
cannot simply use the version defined in the superclass. To declare an abstract
method, use this general form:
abstract type name(parameter-list);
Any class that contains one or more abstract methods must also be declared abstract.
To declare a class abstract, you simply use the abstract keyword in front of the class
keyword at the beginning of the class declaration. There can be no objects of an
abstract class. That is, an abstract class cannot be directly instantiated with the new
operator. Such objects would be useless, because an abstract class is not fully defined.
Also, you cannot declare abstract constructors, or abstract static methods. Any
subclass of an abstract class must either implement all of the abstract methods in the
superclass, or be itself declared abstract.
Following program demonstrates the use of abstract classes
abstract class Animal
{
abstract void travel();
void show()
{
System.out.println(“I am abstract”);
}
}
class Bird extends Animal
{
void travel()
{
System.out.println(“I am bird”);
}
}
class Fish extends Animal
{
void travel()
{
System.out.println(“I am Fish”);
}
}
class AbstractDemo
{
public static void main(String args[])
{
Bird b=new Bird();
b.travel();
b.show();
Animal obj=new Fish();
obj.travel();
obj.show();
}
}
In the above program Animal class is declared as abstract. In Animal class
travel method is declared as a abstract. Fish class and Bird class inheriting the Animal
class so Fish and Bird class overrides the travel method of Animal class.

Interface
Java does not support Multiple Inheritance but java achieves the technique of multiple
Inheritance by using a new notation called interface. By using interface we can define
fully abstract class. That is, using interface, you can specify what a class must do, but
not how it does it. Interfaces are syntactically similar to classes, but they lack instance
variables, and their methods are declared without any body. In practice, this means
that you can define interfaces, which don’t make assumptions about how they are
implemented. Once it is defined, any number of classes can implement an interface
.Also, one class can implement any number of interfaces. To implement an interface, a
class must create the complete set of methods defined by the interface. However, each
class is free to determine the details of its own implementation. By providing the
interface keyword and a class can implement the interface by using implements
keyword.
In short “interface is a class like structure which contains only final
variables and abstract methods though which java achieves the concept of multiple
inheritance”. Java allows you to fully utilize the “one interface, multiple methods ”
aspect of polymorphism.
Following is the general form of interface.
access interface identifier
{
return-type method-name1 (parameter-list );
return-type method-name2 (parameter-list );
type final-varname1 =value;
type final-varname2 =value;
.
return-type method-nameN (parameter-list );
type final-varnameN =value;
}
Following program demonstrates the use of interface in java.

interface Area
{
float PI=3.14F;
float calArea(float x, float y);
}

class Circle implements Area


{

public float calArea(float x,float y)


{
return PI*x*x;
}
}
class Rectangle implements Area
{
public float calArea(float x, float y)
{
return x*y;
}
}
class InterfaceDemo
{
public static void main(String args[])
{
Circle c=new Circle();
Rectangle r=new Rectangle ();
float a1,a2;
a1=c.calArea(3.4F,0);
a2=r.calArea(4.5F,6.7F);
System.out.println(“Area of circle=”+a1);
System.out.println(“Area of Rectangle=”+a2);
}
}
Question Bank
1. Explain super keyword with its different uses in java.
2. Explain final keyword.
3. Explain method overriding.
4. Differentiate method overloading and overriding
5. Explain dynamic Method Dispatch.
6. How multilevel inheritance is implemented in java.
7. Explain abstract class. When they are used?
8. Explain interface and its general structure.
9. Explain finalize () method. Why it is always protected?
10. Explain multilevel inheritance.
5.Exception Handling
Exception
An exception is a condition that is caused by run time error in the program when the
java interpreter encounters an error such as dividing by zero; it creates an exception
object and throws it. In short “Exceptions are java’s predefined objects which are
instantiated by java runtime System whenever error occurs at runtime.”
Need of Exception Handling
Before you learn how to handle exceptions in your program, it is useful to see what
happens when you don ’t handle them. This small program includes an expression that
intentionally causes a divide-by-zero error.
class MyException
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
When the Java run-time system detects the attempt to divide by zero, it constructs a
new exception object and then throws this exception. This causes the execution of
MyException to stop, because once an exception has been thrown, it must be caught
by an exception handler and dealt with immediately. In this example, we haven ’t
supplied any exception handlers of our own , so the exception is caught by the default
handler provided by the Java run-time system. Any exception that is not caught by
your program will ultimately be processed by the default handler. The default handler
displays a string describing the exception, prints a stack trace from the point at which
the exception occurred, and terminates the program.
Here is the output generated when this example is executed.
Java.lang.ArithmeticException: / by zero at Exc0.main (Exc0.java:4)
Notice how the class name,Exc0; the method name, main ;the filename,Exc0.java ;
and the line number,4 ,are all included in the simple stack trace.Also,notice that the
type of the exception thrown is a subclass of Exception called ArithmeticException ,
which more specifically describes what type of error happened.
If the exception object is not caught and handled properly, the interpreter will display
an error message and will terminate the program. If we want to continue the program
with the execution of the remaining code then we should try to catch the exception
object thrown by the error condition and display an appropriate message for taking
corrective actions. This task is known as “Exception Handling”
The purpose of exception handling mechanism is to provide means to detect
and report an ‘exceptional circumstance’ so that appropriate action can be taken.
To handle the exceptions in java program perform the following task.
1. Find the problem (Hit the exception).
2. Inform that an error information (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exceptions)
Common java Exception classes
1. ArithmeticException
Throws when user or programmer is trying to divide the no by zero in java
program.
2. ArrayIndexOutOfBoundsException
Throws when we are exceeding the array indexes.
3. FileNotFoundException
Throws when a program tries to attempt to access a non-existent file.
4. IOException
Caused by general I/O failures, such as inability to read from file or writ e to
file.
5. NullPointerException
Caused when we are accessing methods or members through a null object.
(Non-initialized)
6.OutOfMemoryException
Causes when there is no enough memory to allocate a new object.
6. StringIndexOutOfBoundsException
Throws when we are accessing a non-existent character from a string.
7. IllegalArgumentExfeption
Throws when we will pass the illegal arguments to the methods.
8. IllegalThreadStateException
Throws when threads are switching to illegal state.
9. NumberFormatException
Throws when we are trying to convert an invalid string to the no in java
program.
10. SQLException
Throws while communicating with database management systems.

try ---catch---finally construct


The try –catch—finally construct is a technique of handling exceptions in
java program.
Following is the general structure of try-catch-finally construct
try
{
//block of java code which causes the exception
}
catch(ExceptionType1 obj)
{
//block of java code which is executed when the exception is generated in
try block
}
catch(ExceptionType2 obj2)
{
//block of java code which is executed when the exception is generated in
try block
}
--------------------------
--------------------------
--------------------------
catch(ExceptionTypen objn)
{

//block of java code which is executed when the exception is generated in


try block
}
finally
{
//block of java code which assures for guarantee execution
}
While executing the try block if exception is generated which matches with
argument of catch, the statement in the curly braces that follow the catch keyword will
be executed. After executing these statements, the program will continue with the next
statement.If the exception created does not match with the argument of catch, java
runtime system throws the exceptions and will terminates the programs execution.
Finally, the block of code which included in the curly braces followed by the finally
keyword will execute compulsory, no matter the exception is generated or not.

Following program demonstrates how to handle the exceptions in java


program.
class Arithmetic {
public static void main(String arg[]){
int a,b,c=0;
a=Integer.parseInt(arg[0]);
b=Integer.parseInt(arg[1]);
try{
c=a/b;
}
catch(ArithmeticException ae){
System.out.println("Second value should not be zero");
}
finally {
System.out.println("Result="+c);
}
System.out.println("Exception Demo");
}
}
If in the above userr will enter second value zero at commandline during the
programs execution then java runtime system throws an Exception named
ArithmeticException.
Following program demonstrates the use of multiple catch statements in the
java program.
class MultipleCatchDemo
{
public static void main(String arg[])
{
int i,j,k=0;

try
{
i=Integer.parseInt(arg[0]);
j=Integer.parseInt(arg[1]);
k=i/j;
}
catch(NumberFormatException ae)
{
System.out.println("You should enter valid numeric value");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("You shoul pass 2 values at commandline");

}
catch(ArithmeticException ae)
{
System.out.println("Second value should not be zero");
}
finally
{
System.out.println("Result="+k);
}

}
}
Above program demonstrates the use of multiple catch blocks in a java
program. While executing the program if user will not enters the values at
command line then Java Interpreter throws ArrayIndexOutOfBoundsException, if
user will enters a character value at commandline then it throws
NumberFormatException, if user will enter a second value zero then it throws
ArithmeticException. But at a time java can throw only one exception from a try
block.
‘throw’ keyword
In all above programs exceptions are thrown automatically by java
runtime system when a runtime error occurs. Java also allows programmer to
throw exceptions manually on user defined situations. This task is done by the
throw keyword.
Following is the syntax of throw diagram.
throw obj;
Here obj is object of any subclass of java.lang.Throwable class.
e.g.
throw new Exception(“Sal out of Range”);

Following program demonstrates the use of throw keyword in java program.


class ThrowDemo
{
public static void main(String args[])
{
int sal=0;
Exception e=new Exception("Salary out of range");

try
{
sal=Integer.parseInt(args[0]);
if(sal<0||sal>15000)
throw e;
}
catch(Exception se)
{
System.out.println(se.getMessage());
}

finally
{
System.out.println("Salary="+sal);
}
}
}

throws keyword
If a method is capable of causing an exception that it does not handle,it must
specifythis behavior so that callers of the method can guard themselves against that
exception. You do this by including a throws clause in the method ’s declaration.A
throws clause lists the types of exceptions that a method might throw.This is
necessary for all exceptions,except those of type Error or RuntimeException ,or any
of their subclasses. All other exceptions that a method can throw must be declared in
the throws clause.If they are not,a compile-time error will result. This is the general
form of a method declaration that includes a throws clause:
type method-name(parameter-list)throws exception-list
{
//body of method
}
Here,exception -list is a comma-separated list of the exceptions that a method can
throw.
Following program demonstrates the use of throws keyword in java programs.
class ThrowsDemo
{
static void validate(int sal)throws Exception
{
Exception e=new Exception("Salary out of Range");
if(sal<0 ||sal>15000)
throw e;

}
public static void main(String arg[])
{
int sal=Integer.parseInt(arg[0]);
try
{
validate(sal);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
System.out.println("Salary="+sal);
}
}
}

User Defined Exceptions


Although Java ’s built-in exceptions handle most common errors,you will probably
want to create your own exception types to handle situations specific to your
applications. This is quite easy to do:just define a subclass of Exception (which is,of
course,a subclass of Throwable ).Your subclasses don ’t need to actually implement
anything —it is their existence in the type system that allows you to use them as
exceptions.
Following program demonstrates how to create user-defined exceptions in java
class StringNotMatchException extends Exception
{
StringNotMatchException(String str)
{
super(str);
}
}
class UserDefined
{
public static void main(String args[])
{
String s1,s2;
s1=args[0];
s2=args[1];
StringNotMatchException se=new StringNotMatchException("Strings
are not equal");

try
{
if(!s1.equals(s2))
throw se;
}
catch(StringNotMatchException ste)
{
System.out.println(ste.getMessage());
}
finally
{
System.out.println("First string is="+s1);
System.out.println("Second string is="+s2);
}
}
}
Question Bank
1. What is the exception? Explain the need of ExceptionHandling in java.
2. Explain Common Exceptions classes defined by java.
3. Explain try—catch –finally construct.
4. Explain throw and throws keyword.
5. Differntaite throw and throws keyword.
6. Explain the need of user defined exceptionsin java? How they are created.
Students Name:
-_________________________________________________________
College: -
_________________________________________________________

CORE JAVA AND PRGRAMMING

Вам также может понравиться