Java Notes 2 - TutorialsDuniya
Java Notes 2 - TutorialsDuniya
Java Notes 2 - TutorialsDuniya
COM
Java Programming
Notes
Contributor: Abhishek Sharma
[Founder at TutorialsDuniya.com]
Unit-1
1. Introduction to Object Oriented Programming
The Object Oriented Programming (OOP) is one of the most interesting innovations in the
m
Software Development. It addresses problems commonly known as "Software Crisis". Many
software failed in the past. The term 'Software Crisis' is described in terms of failure in the
co
software
a.
Software is not meeting the client's requirements.
Bugs in the software.
iy
OOP is a programming paradigm with deals with the concepts of the objects to build programs
and software applications. IT is molded around the real world objects. Every object has well-
un
defined identity, attributes, and behavior. The features of the object oriented programming are
similar to the real world features like Inheritance, abstraction, encapsulation, and
polymorphism.
sD
2. Need of OOP
Whenever a new programming language is designed some trade-offs are made, such as
al
FORTRAN, which is efficient for scientific applications, but is not good for system
code.
BASIC, which is easy to learn, but is not powerful, it is lack of structure.
Assembly Language, which is highly efficient, but is not easy to learn.
These languages are designed to work with GOTO statement. As a result programs
written using these languages tend to produce "spaghetti code", which is impossible to
understand.
https://www.tutorialsduniya.com
Unit 1: Need of OOP
m
During the late 1970s and early 1980s, C became the dominant computer programming
language, and it is still widely used today. The C language is structured, efficient and high level
language. Since C is a successful and useful language, you might ask why a need for something
co
else existed. The answer is complexity. As the program complexity is increasing it demanded the
better way to manage the complexity.
When computers were first programming was done by manually toggling in the binary
a.
machine instructions by use of the front panel. As long as programs were just a few hundred
instructions long, this approach worked. As programs grew, assembly language was invented so
iy
that a programmer could deal with larger, increasingly complex programs by using symbolic
representations of the machine instructions. As programs continued to grow, high-level
languages were introduced that gave the programmer more tools with which to handle
un
complexity.
The 1960s gave birth to structured programming. This is the method of programming
championed by languages such as C. The use of structured languages enabled programmers to
sD
write, for the first time, moderately complex programs fairly easily. However, even with
structured programming methods, once a project reaches a certain size, its complexity exceeds
what a programmer can manage. To solve this problem, a new way to program was invented,
called object-oriented programming (OOP). OOP is a programming methodology that helps
al
organize complex programs through the use of inheritance, encapsulation, and polymorphism.
OOP languages follow certain principles such as, class, object, abstraction, encapsulation,
inheritance and polymorphism.
to
3.1 Classes
A class is defined as the blueprint for an object. It serves as a plan or template. An object
is not created just by defining the class, but it has to be created explicitly. It is also
Tu
3.4 Encapsulation
Encapsulation is the mechanism that binds methods and data together into a single unit.
This hides the data from the outside world and keeps both safe from outside interference
and misuse.
It puts some restriction on outside code from directly accessing data.
om
Encapsulation is also known as "Data Hiding".
The Data can be accessed by the methods of the same class . Access to the code and data
inside the wrapper is tightly controlled through a well-defined interface.
In Java, the basis of encapsulation is the class.
A class defines the structure and behavior (Data and Method) that will be shared by a set
.c
of objects. Each object of a given class contains the structure and behavior defined by the
class.
a
The objects are sometimes referred to as instances of a class. Thus, a class is a logical
construct; an object has physical reality.
iy
When you create a class, you will specify the code and data that constitute that class.
Collectively, these elements are called members of the class.
Specifically, the data defined by the class are referred to as member variables or
un
instance variables.
The code that operates on that data is referred to as member methods or just methods.
The members can be public or private. When a member is made public any code outside
the class can access them. If the members are declared as private, then only the members
sD
3.5 Inheritance
Inheritance is the process by which one class acquires the properties or characteristics
from another class.
Here we have two types of classes: base class and derived class.
The class from which the properties or characteristics are acquired is called "Base Class".
m
The class that acquires the properties is called "Derived Class".
The base class is also called super class or parent class. The derived class is also called
sub class or child class.
co
The main use of Inheritance is code reusability.
The keyword "extends" is used for inheriting the properties.
a.
3.6 Polymorphism
Polymorphism simply means many forms (from Greek, meaning “many forms”).
iy
It can be defined as same thing being used in different forms.
It has two forms: compile-time polymorphism and run-time polymorphism.
We know that binding is the process of linking function call to the function definition. If
un
the linking is done at compile-time, then it is called compile-time binding. If it is done at
the run time it is called run-time binding.
The compile-time binding is also called as "static binding". The run-time binding is also
called as "dynamic binding".
sD
All computer programs consist of two elements: methods and data. Furthermore, a program
can be conceptually organized around its methods or around its data. That is, some programs are
ri
written around “what is happening” and others are written around “who is being affected.”
These are the two paradigms that govern how a program is constructed. The first way is called
to
Not suitable for large programs and suitable for large programs and applications
applications
Analysis and design is not so easy Analysis and design is easy
Faster Slower
Less flexible Highly flexible
Less reusable More reusable
m
Only procedures and data are there Inheritance, Encapsulation and polymorphism
are the key features.
Uses top-Down approach Uses Bottom-Up approach
co
Examples: C, Basic, FORTRAN Example: C++,Java
a.
5. Applications of OOP
iy
There are mainly 4 types of applications that can be created using java programming:
1) Standalone Application
un
It is also known as desktop application or window-based application. An application that we
need to install on every machine such as media player, antivirus etc. AWT and Swing are used in
sD
2) Web Application
al
An application that runs on the server side and creates dynamic page, is called web application.
Currently, servlet, jsp, struts, etc. technologies are used for creating web applications in java.
ri
3) Enterprise Application
to
An application that is distributed in nature, such as banking applications etc. It has the advantage
of high level security, load balancing and clustering. In java, EJB is used for creating enterprise
Tu
applications.
4) Mobile Application
An application created for mobile devices is called Mobile Applications. Currently Android and
Java ME are used for creating mobile applications.
In addition to the above applications, there are other applications that use OOP concepts as
follow:
https://www.tutorialsduniya.com
Unit 1: Need of OOP
5. Neural Networks –The neural system of the human body is simulated into the machine, so
that optimizations are carried out according to it.
6. Real Times –These Systems work bases on the time. Examples airline, rockets, etc;
m
7. Expert System –Expert's knowledge is integrated with system, that system will respond as the
expert in the particular domain.
co
8. Database management systems – Data is constructed into tables and collection of table is
called database. Java is used to process the data that is available in the database, such as
a.
insertion, deletion, display etc;.
6. History of JAVA
iy
1. Brief history of Java
2. Java Version History
Java history is interesting to know. The history of java starts from Green Team. Java Team
un
members (also known as Green Team), initiated a revolutionary task to develop a language for
digital devices such as set-top boxes, televisions etc. For the green team members, it was an
advance concept at that time. But, it was suited for internet programming. Later, Java technology
as incorporated by Netscape. Currently, Java is used in internet programming, mobile devices,
sD
games, e-business solutions etc. There are given the major points that describe the history of
java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
al
June 1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set-top boxes.
ri
3) Firstly, it was called "Greentalk" by James Gosling and file extension was ".gt"
to
4) After that, it was called Oak and was developed as a part of the Green project. This name was
inspired by the Oak Tree that stood outside Golsling's Office.
Tu
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
https://www.tutorialsduniya.com
Unit 1: Need of OOP
7) Why they chosen java name for java language? The team gathered to choose a new name.
The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc. They wanted
something that reflected the essence of the technology: revolutionary, dynamic, lively, cool,
unique, and easy to spell and fun to say. According to James Gosling "Java was one of the top
m
choices along with Silk". Since java was so unique, most of the team members preferred java.
8) Java is an island of Indonesia where first coffee was produced (called java coffee). Java
co
coffee was consumed in large quantities by the GreenTeam.
a.
10) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.
iy
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
un
12) JDK 1.0 released in(January 23, 1996).
There are many java versions that has been released. Current stable release of Java is Java SE 8.
JVM also helps to solve many problems associated with web-based programs.
Translating a Java program into byte code makes it much easier to run a program in a
wide variety of environments (or platforms) because 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
m
on it. Remember, although the details of the JVM will differ from platform to platform, all
understand the same Java Byte Code. Thus, the execution of byte code by the JVM is the easiest
way to create truly portable programs.
co
The fact that a Java program is executed by the JVM also helps to make it secure. Because the
JVM is in control, it can contain the program and prevent it from generating side effects outside
a.
of the system.
In general, when a program is compiled to an intermediate form and then interpreted by a virtual
iy
machine, it runs slower than it would run if compiled to executable code. However, with Java,
the differential between the two is not so great. Because byte code has been highly optimized, the
use of byte code enables the JVM to execute programs much faster than you might expect
un
To give on-the-fly performance, the Sun began to design HotSpot Technology for Compiler,
which is called, Just-In-Time compiler. The JIT, Compiler also produces output immediately
after compilation.
sD
8. Features of Java
There is given many features of java. They are also known as java buzzwords. The Java Features
al
Simple
ri
o
o Secure
o Portable
to
o Object-oriented
o Robust
o Multithreaded
Tu
o Architecture-neutral
o Interpreted
o High performance
o Distributed
o Dynamic
Simple
Java was designed to be easy for the professional programmer to learn and use effectively.
According to Sun, Java language is simple because: syntax is based on C++ (so easier for
programmers to learn it after C++). Removed many confusing and/or rarely-used features e.g.,
explicit pointers, operator overloading etc. No need to remove unreferenced objects because
https://www.tutorialsduniya.com
Unit 1: Need of OOP
Secure
Once the byte code generated, the code can be transmitted to other computer in the world
without knowing the internal details of the source code.
m
Portable
co
The byte code can be easily carried from one machine to other machine.
Object Oriented
a.
Everything in Java is an Object. The object model in Java is simple and easy to extend, while
primitive types, such as integers, are kept as high-performance non-objects.
iy
Robust
un
The multi-plat-formed environment of the Web places extraordinary demands on a program,
because the program must execute reliably in a variety of systems. Thus, the ability to create
robust programs was given a high priority in the design of Java. Java also frees from having
worry about many errors. Java is Robust in terms of memory management and mishandled
sD
exceptions. Java provides automatic memory management and also provides well defined
exception handling mechanism.
Multithreaded
al
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.
ri
Architecture-neutral
to
The Java designers made several hard decisions in the Java language and the Java Virtual
Machine in an attempt to alter this situation. Their goal was “write once; run anywhere, any
Tu
Distributed
Java is designed for the distributed environment of the Internet because it handles TCP/IP
protocols. In fact, accessing a resource using a URL is not much different from accessing a file.
Java also supports Remote Method Invocation (RMI). This feature enables a program to invoke
methods across a network.
m
Dynamic
Java programs carry with them substantial amounts of run-time type information that is used to
co
verify and resolve accesses to objects at run time. This makes it possible to dynamically link
code in a safe and expedient manner.
a.
9. Program Structures
Simple Java Program
iy
Example.java
class Example
un
{
public static void main(String args[])
{
System.out.println("Hello World");
sD
}
}
We can use any text editor such as "notepad' or "dos text editor". The source code is typed and
ri
is saved with ".java" as extension. The source code contains one or more class definitions. The
program name will be same as class name in which main function is written. This in not
compulsory, but by convention this is used. The source file is officially called as compilation
to
unit. We can even uses our choice of interest name for the program. If we use a different name
than the class name, then compilation is done with program name, and running is done with class
file name. To avoid this confusion and organize the programs well, it is suggested to put the
Tu
same name for the program and class name, but not compulsory.
To compile the program, first execute the compiler, "javac", specifying the name of the source
file on the command line, as shown bellow:
c:\>javac Example.java
The javac compiler creates the file called "Example.class", that contains the byte code version of
the source code. This byte code is the intermediate representation of the source code that
https://www.tutorialsduniya.com
Unit 1: Need of OOP
contains the instructions that the Java Virtual Machine (JVM) will execute. Thus the output of
the javac is not the directly executable code.
To actually run the program, we must use Java interpreter, called "java". This is
interpreter the "Example.class" file given as input.
When the program is run with java interpreter, the following output is produced:
m
Hello World
co
a.
Description of the every line of the program
iy
The first line contains the keyword class and class name, which actually the basic unit for
encapsulation, in which data and methods are declared.
un
Second line contains "{" which indicates the beginning of the class.
where public is access specifier, when a member of a class is made public it can be accessed by
the outside code also. The main function is the beginning of from where execution starts. Java is
case-sensitive. "Main" is different from the "main". In main there is one parameter, String args,
al
Fourth line contains the "{", which is the beginning of the main function.
ri
System.out.println("Hello World");
Here "System" is the predefined class, that provides access to the system, and out is the output
Tu
stream that is used to connect to the console. The println(), is used to display string passed to it.
This can even display other information to.
If you do not already have the JDK software installed or if JAVA_HOME is not set, the Java CAPS installation will not
be successful. The following tasks provide the information you need to install JDK software and set JAVA_HOME on
UNIX or Windows systems.
The following list provides the Java CAPS JDK requirements by platform.
https://www.tutorialsduniya.com
Unit 1: Need of OOP
Solaris
IBM AIX
m
JDK5: The latest 1.5 release supported by IBM AIX
co
Linux (Red Hat and SUSE)
a.
JDK6: At least release 1.6.0_03
Macintosh
iy
JDK5: The latest 1.5 release supported by Apple
Microsoft Windows
un
JDK5: At least release 1.5.0_14
om
2. To set JAVA_HOME:
a. Right click My Computer and select Properties.
c
a.
iy
un
sD
al
b. On the Advanced tab, select Environment Variables, and then edit JAVA_HOME to point to where the JDK
software is located, for example, C:\Program Files\Java\jdk1.6.0_02.
ri
to
Tu
TutorialsDuniya.com
Download FREE Computer Science Notes, Programs, Projects,
Books PDF for any university student of BCA, MCA, B.Sc,
B.Tech CSE, M.Sc, M.Tech at https://www.tutorialsduniya.com
m
These instructions use the following file:
jdk-8uversion-linux-i586.tar.gz
co
1. Download the file.
Before the file can be downloaded, you must accept the license agreement. The archive binary can be installed
by anyone (not only root users), in any location that you can write to. However, only the root user can install the
a.
JDK into the system location.
2. Change directory to the location where you would like the JDK to be installed, then move the .tar.gz archive
iy
binary to the current directory. un
3. Unpack the tarball and install the JDK.
UNIT – 2
Topics to be covered:
Java Basics: Data types, variables, identifiers, Keywords, Literals, Operators, Expressions,
Precedence Rules and Associativity, Type Conversion and Casting, Flow of Control: Branching,
m
Conditional, Loops, Classes and objects, creating objects, methods, constructors, constructor-
overloading, Cleaning up unused objects and garbage collection, overloading methods and
constructors, Class variables and methods, Static keyword, this keyword, Arrays and command
co
line arguments
Data Types
Java is strongly typed language. The safety and robustness of the Java language is in fact
a.
provided by its strict type. There are two reasons for this: First, every variable and expression
must be defined using any one of the type. Second, the parameters to the method also should
iy
have some type and also verified for type compatibility. Java language 8 primitive data types:
The primitive data types are: char, byte, short, int, long, float, double, boolean. These are again
un
grouped into 4 groups.
1. Integer Group: The integer group contains byte, short, int, long. These data types will
need different sizes of the memory. These are assigned positive and negative values. The
sD
byte:
to
The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to
127.Variables of type byte are especially useful when you’re working with a stream of data
froma network or file. They are also useful when you’re working with raw binary data that
Tu
maynot be directly compatible with Java’s other built-in types.Byte variables are declared by use
of the byte keyword.
For example, the followingdeclares two byte variables called b and c:
byte b, c;
short:
short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least-used
Java type. Here are some examples of short variable declarations:
short s;
https://www.tutorialsduniya.com
Unit 2: Java Basics
short t;
int:
The most commonly used integer type is int. It is a signed 32-bit type that has a rangefrom –
2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int arecommonly
employed to control loops and to index arrays. We can store byte and short values in an int.
m
Example
int x=12;
co
long:
long is a signed 64-bit type and is useful for those occasions where an int type is not
largeenough to hold the desired value. The range of a long is quite large. This makes it
a.
usefulwhen big, whole numbers are needed.
Example
long x=123456;
iy
2. Floating-Point Group
un
Floating-point numbers, also known as realnumbers, are used when evaluating expressionsthat
require fractional precision. These are used with operations such as square root, cosine, and sine
etc. There are two types of Floating-Point numbers: float and double. The float type represents
single precision and double represents double precision. Their width and ranges are as follows:
sD
al
float:
ri
The type float specifies a single-precisionvalue that uses 32 bits of storage. Single precision is
to
faster on some processors and takes half as much space as double precision. Variables of type
float are usefulwhen you need a fractional component, but don’t require a large degree of
precision.
Tu
Example:
float height, price;
double:
Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double
precision is actually faster than single precision on some modern processors that have been
optimized for high-speed mathematical calculations. All the math functions, such as sin( ), cos( ),
and sqrt( ), return double values.
Example:
double area,pi;
https://www.tutorialsduniya.com
Unit 2: Java Basics
import java.io.*;
class Circle
{
public static void main(String args[])
m
{
double r,area,pi;
r=12.3;
co
pi=3.14;
area=pi*r*r;
System.out.println("The Area of the Circle is:"+area);
a.
}
}
3. Characters Group
iy
In Java, the data type used to store characters is char. However, C/C++ programmers
beware:char in Java is not the same as char in C or C++. In C/C++, char is 8 bits wide. This is
not thecase in Java. Instead, Java uses Unicode to represent characters. Unicode defines a
un
fullyinternational character set that can represent all of the characters found in all
humanlanguages.
Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. The
sD
standard set of characters known as ASCII still ranges from 0 to 127 as always, and theextended
8-bit character set, ISO-Latin-1, ranges from 0 to 255.
{
public static void main(String args[])
{
to
4. Booleans
Java has a primitive type, called boolean, for logical values. It can have only one of twopossible
values, true or false. This is the type returned by all relational operators, as in thecase of a < b.
m
b = false;
System.out.println("b is " + b);
b = true;
co
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b) System.out.println("This is executed.");
a.
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
iy
System.out.println("10 > 9 is " + (10 > 9));
}
}
un
Identifiers
Identifiers are used for class names, method names, and variable names. An identifier may be
sD
any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and
dollar-sign characters. They must not begin with a number, lest they be confused with anumeric
literal. Again, Java is case-sensitive, so VALUE is a different identifier than Value.Some
examples of valid identifiers are:
al
Class or Interface- These begin with a capital letter. The first alphabet of every internal
word is capitalized. Ex: class Myclass;
Variable or Method –These start with lower case letters. The first alphabet of every
internal word is capitalized. Ex:- int totalPay;
https://www.tutorialsduniya.com
Unit 2: Java Basics
Constants- These are in upper case. Underscore is used to separate the internal word.
Ex:-final double PI=3.14;
Package – These consist of all lower-case letters. Ex:- import java.io.*;
Variables
m
The variable is the basic unit of storage in a Java program. A variable is defined by
thecombination of an identifier, a type, and an optional initializer. In addition, all variables havea
scope, which defines their visibility, and a lifetime.
co
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable
a.
declaration is shown here:
iy
Here the type is any primitive data types, or class name. The identifier is the name of the
variable. We can initialize the variable by specifying the equal sign and value.
un
Example
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing
sD
// d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; //the variable x ahs the value 'x'
al
float z=Math.sqrt(x+y);
void function1()
{//outer block
int a;
//here a,b,c are visible to the inner scope
int a=10;
if(a==10)
m
{// inner block
int b=a*20;
int c=a+30;
co
}//end of inner block
b=20*2;
// b is not known here, which declared in inner scope
a.
}//end of the outer block
Literals
iy
A literal is a value that can be passed to a variable or constant in a program. Literals can be
numeric, boolean, character, string notation or null. A constant value can be created using a
un
literal representation of it. Here are some literals:
Comments
In java we have three types of comments: single line comment, Multiple line comment, and
al
/**……….*/.
Separators
to
In Java, there are a few characters that are used as separators. The most commonly usedseparator
in Java is the semicolon. As you have seen, it is used to terminate statements.The separators are
Tu
m
co
a.
The Java Keywords
iy
There are 50 keywords currently defined in the Java language (see Table bellow). These
keywords,combined with the syntax of the operators and separators, form the foundation of the
un
Javalanguage. These keywords cannot be used as names for a variable, class, or method.
a lsD
ri
to
Tu
Operators
An operator performs an operation on one or more operands. Java provides a rich
operator environment. An operator that performs an operation on one operand is called unary
operator. An operator that performs an operation on two operands is called binary operator.
Most of its operators can be divided into thefollowing four groups:arithmetic, bitwise,
relational, and logical. Java also defines someadditional operators that handle certain special
situations. In Java under Binary operator we have Arithmetic, relational, Shift, bitwise and
assignment operators. And under Unary operators we have ++, - - , !( Boolean not), ~(bitwise
not) operators.
https://www.tutorialsduniya.com
Unit 2: Java Basics
Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they areused in
algebra. The following table lists the arithmetic operators:
m
co
a.
iy
un
The operands of the arithmetic operations are of numeric type. The Boolean operands are not
allowed to perform arithmetic operations. The basic arithmetic operators are: addition,
subtraction, multiplication, and division.
sD
class Arith
{
public static void main(String args[])
ri
{
int a,b,c,d;
to
a=5;
b=6;
//arithmetic addition
Tu
c=a+b;
System.out.println("The Sum is :"+c);
//aritmetic subtraction
d=a-b;
System.out.println("The Subtractio is :"+d);
//arithmetic division
c=a/b;
System.out.println("The Dision is :"+c);
//arithmetic multiplication
d=a*b;
System.out.println("The multiplication is :"+d);
}
https://www.tutorialsduniya.com
Unit 2: Java Basics
The modulus operator, %, returns the remainder of a division operation. It can be applied
tofloating-point types as well as integer types. The following demonstrates the %
m
Modulus.java
// Demonstrate the % operator.
co
class Modulus
{
public static void main(String args[])
{
a.
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
iy
System.out.println("y mod 10 = " + y % 10);
}
}
un
Arithmetic Compound Assignment Operators
Java provides special operators that can be used to combine an arithmetic operation withan
assignment. As you probably know, statements like the following are quite common
sD
inprogramming:
a = a + 4;
a += 4;
ri
This version uses the += compound assignment operator. Both statements perform the same
action: they increase the value of a by 4.
to
The ++ and the – – are Java’s increment and decrement operators. The increment operator
increases its operand by one. The decrement operator decreases its operand by one. For example,
this statement:
x = x + 1;
https://www.tutorialsduniya.com
Unit 2: Java Basics
x++;
m
is equivalent to
x--;
co
Note: If we write increment/decrement operator after the operand such expression is called post
increment decrement expression, if written before operand such expression is called pre
increment/decrement expression
a.
The following program demonstrates the increment and decrement operator.
IncDec.java
iy
// Demonstrate ++ and --
class IncDec
{
un
public static void main(String args[])
{
int a = 1;
int b = 2;
int c;
sD
int d;
c = ++b; //pre increment
d = a--; //post decrement
c++; //post increment
al
Java defines several bitwise operators that can be applied to the integer types, long, int,
short,char, and byte. These operators act upon the individual bits of their operands. They
aresummarized in the following table:
https://www.tutorialsduniya.com
Unit 2: Java Basics
m
co
a.
iy
These operators are again classified into 3 categories: Logical operators, Shift operators, and
Relational operator
un
The Bitwise Logical Operators
The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome ofeach operation. The
bitwise operators are applied to each individual bit within each operand.
a lsD
ri
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:
Tu
00101010
becomes
11010101
after the NOT operator is applied.
00001010 10
https://www.tutorialsduniya.com
Unit 2: Java Basics
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
m
00101111 47
co
The Bitwise XOR
The XOR operator, ^, combines bits such that if exactly one operand is 1, then the result is 1.
a.
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,
iy
the first operand is unchanged. You will find this property useful when performing some
types of bit manipulations.
un
00101010 42
^ 00001111 15
00100101 37
sD
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;
System.out.println(" a|b = " +c);
System.out.println(" a&b = " +d);
System.out.println(" a^b = " +e);
System.out.println("~a&b|a&~b = " +f);
System.out.println(" ~a = " + g);
}
}
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:
m
Here, numspecifies 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 specifiedby num.
co
The Right Shift
a.
The right shift operator, >>, shifts all of the bits in a value to the right a specified number
oftimes. Its general form is shown here:
iy
value >> num
Here, numspecifies the number of positions to left-shift the value in value. That is, the >>moves
un
all of the bits in the specified value to the right by the number of bit positions specifiedby num.
ShiftBits.java
sD
class ShiftBits
{
public static void main(String args[])
{
al
byte b=6;
int c,d;
//left shift
ri
c=b<<2;
//right shift
d=b>>3;
to
Relational Operators
The relational operators determine the relationship that one operand has to the
other.Specifically, they determine equality and ordering. The relational operators are shown here:
TutorialsDuniya.com
Download FREE Computer Science Notes, Programs, Projects,
Books PDF for any university student of BCA, MCA, B.Sc,
B.Tech CSE, M.Sc, M.Tech at https://www.tutorialsduniya.com
m
co
a.
The outcome of these operations is a boolean value. The relational operators are most frequently
used in the expressions that control the if statement and the various loop statements.
iy
Any type in Java, including integers, floating-point numbers, characters, and Booleanscan be
compared using the equality test, ==, and the inequality test, !=. Notice that in Javaequality is
un
denoted with two equal signs, not one. (Remember: a single equal sign is theassignment
operator.) Only numeric types can be compared using the ordering operators.That is, only
integer, floating-point, and character operands may be compared to see whichis greater or less
than the other.
sD
Java provides two interesting Boolean operators not found in many other computer
al
languages.These are secondary versions of the Boolean AND and OR operators, and are known
asshort-circuit logical operators.
ri
When we use || operator if left hand side expression is true, then the result will be true, no matter
what is the result of right hand side expression. In the case of && if the left hand side expression
results true, then only the right hand side expression is evaluated.
to
The assignment operator is the single equal sign, =. The assignment operator works in Java
much as it does in any other computer language. It has this general form:
var = expression;
Here, the type of var must be compatible with the type of expression. The assignment operator
does have one interesting attribute that you may not be familiar with: it allows you to create a
chain of assignments. For example, consider this fragment:
int x, y, z;
x = y = z = 100; // set x, y, and z to 100
https://www.tutorialsduniya.com
Unit 2: Java Basics
The ? Operator
Java includes a special ternary (three-way) operatorthat can replace certain types of if-then-
elsestatements. This operator is the ?. It can seem somewhat confusing at first, but the ? can
beused very effectively once mastered. The ? has this general form:
m
expression1 ? expression2 : expression3
co
Here, expression1 can be any expression that evaluates to a boolean value. If expression1 istrue,
then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ?operation is
a.
that of the expression evaluated. Both expression2 and expression3 are requiredto return the
same type, which can’t be void.Here is an example of the way that the ? is employed:
iy
Test.java
class Test
un
{
public static void main(String args[])
{
sD
int x=4,y=6;
int res= (x>y)?x:y;
System.out.println("The result is :"+res);
}
al
Expressions:
ri
Example:-
Tu
int m=2,n=3,o=4;
int y=m*n*o;
Table shows the order of precedence for Java operators, from highest to lowest. Notice that the
first row shows items that you may not normally think of as operators: parentheses, square
brackets, and the dot operator. Technically, these are called separators, but they act like
operators in an expression. Parentheses are used to alter the precedence of an operation. As you
m
know from the previous chapter, the square brackets provide array indexing. The dot operator is
used to dereference objects.
co
a.
iy
un
sD
al
ri
Note: The operators =,?:, ++, and – are having Right to Left Associativity. The remaining
Operators are having Left to Right Associativity.
to
Using Parentheses
Tu
Parenthesesraise the precedence of the operations that are inside them. This is often necessaryto
obtain the result you desire. For example, consider the following expression:
a >> b + 3
This expression first adds 3 to b and then shifts a right by that result. That is, this expression
can be rewritten using redundant parentheses like this:
a >> (b + 3)
However, if you want to first shift a right by b positions and then add 3 to that result,you will
need to parenthesize the expression like this:
https://www.tutorialsduniya.com
Unit 2: Java Basics
(a >> b) + 3
The control statements are used to control the flow of execution and branch based on the status
m
of a program. The control statements in Java are categorized into 3 categories:
co
ii. Loops (Iteration Statements)
iii. Branching Statements (Jump Statements)
a.
iy
un
lsD
ia
if statement: This is the Java's conditional branch statement. This is used to route the execution
through two different paths. The general form ofif statement will be as follow:
t
if (conditional expression)
Tu
{
statement1
}
else
{
statement2
}
Here the statements inside the block can be single statement or multiple statements. The
conditional expression is any expression that returns the Boolean value. The else clause is
optional.The if works as follows: if the conditional expression is true, then statement1 will be
executed. Otherwise statement2 will be executed.
https://www.tutorialsduniya.com
Unit 2: Java Basics
Example:
Write a java program to find whether the given number is even or odd?
EvenOdd.java
import java.io.*;
classs EvenOdd
m
{
public static void main(String args[])
{
co
int n;
System.out.println("Enter the value of n");
DataInputStream dis=new DataInputStream(System.in);
a.
n=Integer.parseInt(dis.readLine());
if(n%2==0)
iy
{
System.out.println(n+" is the Even Number");
}
un
else
{
System.out.println(n+"is the ODD Number");
}
sD
}
}
al
Nested if: The nested if statement is an if statement, that contains another if and else inside it.
The nested if are very common in programming. When we nest ifs, the else always associated
with the nearest if.
ri
if(conditional expresion1)
{
if(conditional expression2)
Tu
{
statements1;
}
else
{
satement2;
}
}
else
{
statement3;
https://www.tutorialsduniya.com
Unit 2: Java Basics
}
Example program:
Write a java Program to test whether a given number is positive or negative.
Positive.java
import java.io.*;
class Positive
m
{
public static void main(String args[]) throws IOException
{
co
int n;
DataInputStream dis=new DataInputStream(System.in);
n=Integer.parseInt(dis.readLine());
a.
if(n>-1)
{
if(n>0)
iy
System.out.println(n+ " is positive no");
}
else
un
System.out.println(n+ " is Negative no");
}
}
sD
A common programming construct that is based upon a sequence of nested ifs is the
if-else-if ladder. It looks like this:
al
if(condition)
statement;
else if(condition)
ri
statement;
else if(condition)
statement;
to
...
else
statement;
Tu
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
isbypassed. If none of the conditions is true, then the final else statement will be executed.
Example Program:
Write a Java Program to test whether a given character is Vowel or Consonant?
Vowel.java
import java.io.*;
class Vowel
{
https://www.tutorialsduniya.com
Unit 2: Java Basics
m
else if(ch=='e')
System.out.println("Vowel");
co
else if(ch=='i')
System.out.println("Vowel");
else if(ch=='o')
a.
System.out.println("Vowel");
else if(ch=='u')
iy
System.out.println("Vowel");
else
un
System.out.println("consonant");
sD
}
}
al
The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch
ri
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:
to
switch (expression)
{
Tu
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
https://www.tutorialsduniya.com
Unit 2: Java Basics
The expression must be of type byte, short, int, or char; each of the values specified in thecase
statements must be of a type compatible with the expression. Eachcase value must be a unique
literal (that is, it must be a constant, not a variable). Duplicate casevalues are not allowed.
m
The switch statement works like this: The value of the expression is compared with eachof the
literal values in the case statements. If a match is found, the code sequence followingthat case
statement is executed. If none of the constants matches the value of the expression,then the
co
default statement is executed. However, the default statement is optional. If no casematches and
no default is present, then no further action is taken.
The break statement is used inside the switch to terminate a statement sequence. Whena break
a.
statement is encountered, execution branches to the first line of code that follows theentire
switch statement. This has the effect of “jumping out” of the switch.
iy
un
Write a Java Program to test whether a given character is Vowel or Consonant?( Using
Switch)
SwitchTest.java
import java.io.*;
sD
class SwitchTest
{
public static void main(String args[]) throws IOException
{
al
char ch;
ch=(char)System.in.read();
switch(ch)
ri
{
//test for small letters
case 'a': System.out.println("vowel");
to
break;
case 'e': System.out.println("vowel");
break;
Tu
The break statement is optional. If you omit the break, execution will continue on into thenext
case. It is sometimes desirable to have multiple cases without break statements betweenthem.
For example, consider the following program.
m
class Switch
{
co
public static void main(String args[])
{
int month = 4;
a.
String season;
switch (month)
{
iy
case 12:
case 1:
case 2:season = "Winter";
un
break;
case 3:
case 4:
case 5:season = "Spring";
sD
break;
case 6:
case 7:
case 8:season = "Summer";
al
break;
case 9:
case 10:
ri
}
System.out.println("April is in the " + season + ".");
}
Tu
You can use a switch as part of the statement sequence of an outer switch. This is called anested
switch. Since a switch statement defines its own block, no conflicts arise between thecase
constants in the inner switch and those in the outer switch. For example, the followingfragment
is perfectly valid:
m
} //end of inner switch
break;
case 2: //statement sequence
co
break;
default: //statement sequence
} //end of outer switch
a.
There are three important features of the switch statement to note:
o The switch differs from the if in that switch can only test for equality, whereas if can
iy
evaluate any type of Boolean expression. That is, the switch looks only for a match
between the value of the expression and one of its case constants.
un
o No two case constants in the same switch can have identical values. Of course, a
switch statement and an enclosing outer switch can have case constants in common.
Java’s iteration statements are for, while, and do-while. These statements create what
wecommonly call loops. As you probably know, a loop repeatedly executes the same set
ri
i. while
to
The 'while' loops is used to repeatedly execute a block of statements based on a condition. The
Tu
condition is evaluated before the iteration starts. A 'for' loop is useful, when we know the
number of iterations to be executed in advance. If we want to execute the loop for indefinite
number of times, a while loop may be better choice. For example, if you execute a query to fetch
data from database, you will not know the exact number of records returned by the query.
Syntax:
while(condition)
{
// body of loop
increment or decrement statement
https://www.tutorialsduniya.com
Unit 2: Java Basics
The conditioncan be any Boolean expression. The body of the loop will be executed as longas
the conditional expression is true. When conditionbecomes false, control passes to thenext line
of code immediately following the loop. The curly braces are unnecessary if onlya single
statement is being repeated.
m
Example program:
Write a java program to add all the number from 1 to 10.
co
WhileTest.java
import java.io.*;
class WhileTest
a.
{
public static void main(String args[])
{
iy
int i=1,sum=0;
while(i<=10)
{
un
sum=sum+i;
i++;
}
System.out.println("The sum is :"+sum);
sD
}
}
However, sometimes it is desirable to execute the body of a loop at least once, even if the
conditional expression is false to begin with. In other words, there are times when you would like
ri
to test the terminationexpression at the end of the loop rather than at the beginning.
Fortunately, Java supplies aloop that does just that: the do-while. The do-while loop always
to
executes its body at leastonce, because its conditional expression is at the bottom of the loop. Its
general form is:
Tu
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluatesthe
conditional expression. If this expression is true, the loop will repeat. Otherwise, the
loopterminates. As with all of Java’s loops, condition must be a Boolean expression.
Example program:
Write a java program to add all the number from 1 to 10. (using do-while)
https://www.tutorialsduniya.com
Unit 2: Java Basics
WhileTest.java
import java.io.*;
class WhileTest
{
public static void main(String args[])
{
m
int i=1,sum=0;
do
{
co
sum=sum+i;
i++;
}while(i<=10);
a.
System.out.println("The sum is :"+sum);
}
}
iy
Note 1:Here the final value of the i will be 11. Because the body is executed first, then the
condition is verified at the end.
un
Note 2: The do-while loop is especially useful when you process a menu selection, because you
will usually want the body of a menu loop to execute at least once.
sD
Example program: Write a Java Program to perform various operations like addition,
subtraction, and multiplication based on the number entered by the user. And Also Display
the Menu.
DoWhile.java
al
import java.io.*;
class DoWhile
{
ri
do
Tu
{
System.out.println("Enter your choice");
System.out.println("1 Addition");
System.out.println("2 Subtraction");
System.out.println("3 Multiplicaton");
n=Integer.parseInt(dis.readLine());
System.out.println("Enter two Numbers");
int a=Integer.parseInt(dis.readLine());
int b =Integer.parseInt(dis.readLine());
int c;
switch(n)
{
https://www.tutorialsduniya.com
Unit 2: Java Basics
case 1: c=a+b;
System.out.println("The addition is :"+c);
break;
case 2: c=a-b;
System.out.println("The addition is :"+c);
break;
m
case 3: c=a*b;
System.out.println("The addition is :"+c);
break;
co
default:System.out.println("Enter Correct Number");
a.
} while(n<=3);
iy
}
}
un
iii. for statement
The for loop groups the following three common parts into one statement: Initialization,
condition and Increment/ Decrement.
sD
Syntax:
for(initialization; condition; iteration)
{
// body of the loop
al
The for loop operates as follows. When the loop first starts, the initializationportion ofthe loop is
ri
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 thatthe initialization
to
expression is only executed once. Next, conditionis evaluated. This must bea Booleanexpression.
It usually tests the loop control variable against a target value. If thisexpression is true, then the
body of the loop is executed. If it is false, the loop terminates. Third, Increment/Decrement is
Tu
ForTest.java
import java.io.*;
class ForTest
{
public static void main(String args[])
{
int i,sum=0;
for(i=1;i<=10;i++)
https://www.tutorialsduniya.com
Unit 2: Java Basics
{
sum=sum+i;
}
System.out.println("The sum is :"+sum);
}
}
m
There are some important things about the for loop
1. The initialization of the loop controlling variables can be done inside for loop.
Example:
co
for(int i=1;i<=10;i++)
2. We can write any Boolean expression in the place of the condition for second part of the
loop.
a.
Example: where b is a Boolean data type
boolean b=false;
for(int i=1; !b;i++)
iy
{
//body of the loop
b=true;
un
}
This loop executes until the b is set to the true;
3. We can also run the loop infinitely, just by leaving all the three parts empty.
sD
Example:
for( ; ;)
{
al
A for loop also provides another version, which is called Enhanced Version of the for loop. The
to
for(type itr_var:collection)
Tu
{
//body of the loop
}
Here, type is the type of the iterative variable of that receives the elements from collection, one
at a time, from beginning to the end. The collection is created sung the array.
Example program:
Write a java program to add all the elements in an array?
ForEach.java
import java.io.*;
class ForEach
TutorialsDuniya.com
Download FREE Computer Science Notes, Programs, Projects,
Books PDF for any university student of BCA, MCA, B.Sc,
B.Tech CSE, M.Sc, M.Tech at https://www.tutorialsduniya.com
{
public static void main(String args[])
{
int i, a[], sum=0;
a=new int[10];
a={12,13,14,15,16};
m
for(int x:a)
{
sum=sum+x;
co
}
System.out.println("The sum is :"+sum);
}
a.
}
iy
Java supports three jump statements: break, continue, and return. These statements transfer
control to another part of your program.
un
i. break statement
In Java, the break statement has three uses. First, as you have seen, it terminates a statement
sD
sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used as
“civilized” form of goto statement.
By using break, you can force immediate termination of a loop, bypassing the
conditionalexpression and any remaining code in the body of the loop. When a break statement
isencountered inside a loop, the loop is terminated and program control resumes at the
ri
class BreakLoop
Tu
{
public static void main(String args[])
{
for(int i=0; i<100; i++)
{
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
https://www.tutorialsduniya.com
Unit 2: Java Basics
In addition to its uses with the switch statement and loops, the break statement can also
beemployed by itself to provide a “civilized” form of the goto statement. For example, the goto
can be useful when you areexiting from a deeply nested set of loops. To handle such situations,
Java defines an expandedform of the break statement. By using this form of break, you can, for
m
example, break out ofone or more blocks of code.
co
break label;
a.
Most often, label is the name of a label that identifies a block of code. This can be a
stand-aloneblock of code but it can also be a block that is the target of another statement. When
iy
this form ofbreak executes, control is transferred out of the named block. The labeled block
must enclosethe break statement, but it does not need to be the immediately enclosing bloc.
un
To name a block, put a label at the start of it. A label is any valid Java identifier
followedby a colon. Once you have labeled a block, you can then use this label as the target of
abreak statement.
sD
Example code:
class Break
{
al
first: {
second: {
to
third: {
System.out.println("Before the break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
Tu
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
m
but stop processing the remainder of the code in its body for this particulariteration.In while and
do-while loops, a continue statementcauses 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
co
statement and then to theconditional expression. For all three loops, any intermediate code is
bypassed.Here is an example program that uses continue to cause two numbers to be printed
oneach line:
a.
// Demonstrate continue.
iy
class Continue
{
public static void main(String args[])
un
{
for(int i=1; i<=10; i++)
{
sD
if (i%5 == 0) continue;
System.out.print(i + " ,");}
}
}
al
Example code
Tu
class Test
{
p s v main(String args[]) // caller of the method
{
int a=3,b=4;
int x=method(a,b);//function call
System.out.println("The sum is :"+x);
}
int method(int x,int y) // called method
{
https://www.tutorialsduniya.com
Unit 2: Java Basics
return (x+y);
}
}
After computing the result the control is transferred to the caller method, that main in this case.
m
There are two types of conversion. They are Implicit Conversion, and Explicit Conversion.
co
Implicit Conversion
In the case of the implicit conversion type conversion is automatically performed by java when
a.
the types are compatible. For example, the int can be assigned to long. The byte cane assigned to
short. However, all the types are compatible, thus all the type conversions are implicitly
allowed.For example, double is not compatible with byte.
iy
Conditions for automatic conversion
1. The two types must be compatible
2. The destination type must be larger than the source type
un
When automatic type conversion takes place the widening conversion takes place. For example,
a=b; // here 8 bits data is placed in 32 bit storage. Thus widening takes place.
Explicit Conversion
al
Fortunately, it is still possible obtain the conversion between the incompatible types. This is
called explicit type conversion. Java provides a special keyword "cast" to facilitate explicit
conversion. For example, sometimes we want to assign int to byte, this will not be performed
ri
automatically, because byte is smaller than int. This kind of conversion is sometimes called
"narrowing conversion".Since, you are explicitly making the value narrow.The general form of
to
Here the target type specifies the destination type to which the value has to be converted.
Example
int a=1234;
byte b=(byte) a;
The above code converts the int to byte. If the integer value is larger than the byte, then it will be
reduced to modulo byte's range.
casttest.java
import java.io.*;
class casttest
https://www.tutorialsduniya.com
Unit 2: Java Basics
{
public static void main(String args[])
{
int a=258;
byte b;
b=(byte) a;
m
System.out.print(" The result is :" +b);
}
co
}
a.
output:
iy
un
sD
al
ri
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
https://www.tutorialsduniya.com
Unit 2: Java Basics
The result of the intermediate term a * b easily exceeds the range of either of its byteoperands.
To handle this kind of problem, Java automatically promotes each byte, short,or char operand
to int when evaluating an expression. This means that the subexpression a * bis performed using
integers—not bytes. Thus, 2,000, the result of the intermediate expression,50 * 40, is legal even
though a and b are both specified as type byte.
m
As useful as the automatic promotions are, they can cause confusing compile-time errors.For
example, this seemingly correct code causes a problem:
co
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
a.
The code is attempting to store 50 * 2, a perfectly valid byte value, back into a byte
variable.However, because the operands were automatically promoted to int when the expression
iy
wasevaluated, the result has also been promoted to int. Thus, the result of the expression is
nowof type int, which cannot be assigned to a byte without the use of a cast.
un
In cases where you understand the consequences of overflow, you should use an explicit
cast, such as
byte b = 50;
sD
b = (byte)(b * 2);
Java defines several type promotion rules that apply to expressions. They are as follows:
ri
First,all byte, short, and char values are promoted to int, as just described.
Then, if one operandis a long, the whole expression is promoted to long.
If one operand is a float, the entireexpression is promoted to float.
to
Introduction to Arrays
An Array is a collection of elements that share the same type and name. The elements from the
array can be accessed by the index. To create an array, we must first create the array variable of
the desired type. The general form of the One Dimensional array is as follows:
type var_name[];
Here type declares the base type of the array. This base type determine what type of elements
that the array will hold.
Example:
https://www.tutorialsduniya.com
Unit 2: Java Basics
int month_days[];
Here type is int, the variable name is month_days. All the elements in the month are integers.
Since, the base type is int.
m
In fact, the value of month_days is set to null, which represents an arraywith no value. To link
month_days with an actual, physical array of integers, you must allocateone using new and
assign it to month_days. new is a special operator that allocates memory.
co
The general form of new as it applies to one-dimensional arrays appearsas follows:
a.
array-var = new type[size];
Here, type specifies the type of data being allocated, size specifies the number of elements inthe
iy
array, and array-var is the array variable that is linked to the array. That is, to use new toallocate
an array, you must specify the type and number of elements to allocate. The elementsin the array
allocated by new willautomatically be initialized to zero. This example allocatesa 12-element
un
array of integers and links them to month_days.
month_days
Element 0 0 0 0 0 0 0 0 0 0
Index 0 1 2 3 4 5 6 7 8 9
al
After this statement executes, month_days will refer to an array of 12 integers. Further, all
elements in the array will be initialized to zero.
ri
Once you have allocated an array, you can access a specific element in the array byspecifying its
index within square brackets. All array indexes start at zero. For example,this statement assigns
to
month_days[1] = 28;
Tu
Element 0 28 0 0 0 0 0 0 0 0
Index 0 1 2 3 4 5 6 7 8 9
Example Program: Write a Java Program to read elements into array and display them?
ArrayTest.java
import java.io.*;
class ArrayTest
https://www.tutorialsduniya.com
Unit 2: Java Basics
{
public static void main(String args[]) throws IOException
{
m
int n, i; //size of the array
System.out.println("Enter the size of Array:");
n=Integer.parseInt(dis.readLine());
co
a=new int[n]; //allocating memory to array a and all the elements are set zero
a.
System.out.println("Enter the elements into Array:");
for(i=0;i<n;i++)
{
iy
a[i]=Integer.parseInt(dis.readLine());
}
//displaying the elements
un
System.out.println("The elements of Array:");
for(i=0;i<n;i++)
{
System.out.print(a[i]+",");
sD
}
}
}
al
Output
ri
to
Tu
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect,
lookand act like regular multidimensional arrays. However, as you will see, there are a coupleof
https://www.tutorialsduniya.com
Unit 2: Java Basics
m
This allocates a 4 by 4 array and assigns it to twoD. Internally this matrix is implemented as
an array of arrays of int.
co
Right Index Determines the Columns
[0,0] [0,1] [0,2] [0,3]
Left index
determines
a.
[2,0] [2,1] [2,2] [2,3]
[3,0] [3,1] [3,2] [3,3]
iy
Example Program for Matrix Addition
un
import java.io.*;
class AddMatrix
{
public static void main(String args[]) throws IOException
sD
{
int m, n, c, d;
DataInputStream dis=new DataInputStream(System.in);
al
m
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
co
System.out.print(sum[c][d]+"\t");
System.out.println();
a.
}
}
}
iy
Example program for Matrix Multiplication
un
import java.io.*;
class MulMatrix
{
sD
n = Integer.parseInt(dis.readLine());
if ( n != p )
System.out.println("Matrices with entered orders can't be multiplied with each other.");
else
https://www.tutorialsduniya.com
Unit 2: Java Basics
{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];
m
for ( c = 0 ; c < p ; c++ )
for ( d = 0 ; d < q ; d++ )
second[c][d] = Integer.parseInt(dis.readLine());
co
for ( c = 0 ; c < m ; c++ )
{
a.
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
iy
{
sum = sum + first[c][k]*second[k][d];
}
un
multiply[c][d] = sum;
sum = 0;
}
sD
System.out.print(multiply[c][d]+"\t");
System.out.print("\n");
to
}
}
}
Tu
type[ ] var-name;
Here, the square brackets follow the type specifier, and not the name of the array variable.
For example, the following two declarations are equivalent:
https://www.tutorialsduniya.com
Unit 2: Java Basics
m
char[][] twod2 = new char[3][4];
This alternative declaration form offers convenience when declaring several arrays at the
co
same time. For example,
a.
creates three array variables of type int. It is the same as writing
iy
int nums[], nums2[], nums3[]; // create three arrays
The alternative declaration form is also useful when specifying an array as a return type for
un
a method. Both forms are used.
The java command-line argument is an argument i.e. passed at the time of running the java
program.The arguments passed from the console can be received in the java program and it can
be used as an input.
al
So, it provides a convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt. The
ri
command line arguments can be accessed easily, because they are stored as Strings in String
array passed to the args in the main method. The first command line argument is stored in
to
args[0], the second argument is stored in args[1], the third argument is stored in args[2], and so
on.
Tu
Example program:
import java.io.*;
class CommnadLine
{
public static void main(String args[])
{
https://www.tutorialsduniya.com
Unit 2: Java Basics
for(int i=0;i<args.length();i++)
{
System.out.println(args[i]+" ");
}
}
m
}
Here the String class has a method length(), which is used to find the length of the string. This
co
length can be used to read all the arguments from the command line.
a.
Introduction to Strings
String is probably the most commonly used class in Java’sclass library. The obvious reason for
iy
this is that strings are a very important part ofprogramming.
The first thing to understand about strings is that every string you create is actually an
un
object of type String. Even string constants are actually String objects.
For example, in thestatement
The second thing to understand about strings is that objects of type String are
al
immutable;once a String object is created, its contents cannot be altered. While this may
seem like aserious restriction, it is not, for two reasons:
• If you need to change a string, you can always create a new one that containsthe
ri
modifications.
• Java defines a peer class of String, called StringBuffer, which allows strings
to
to be altered, so all of the normal string manipulations are still available in Java
Strings can be created in a many ways. The easiest is to use a statement like this:
1. String initialization
Tu
Once you have created a String object, you can use it anywhere that a string is allowed.
For example, this statement displays myString:
System.out.println(myString);
https://www.tutorialsduniya.com
Unit 2: Java Basics
Java defines one operator for String objects: +. It is used to concatenate two strings.
For example, this statement:
m
The String class contains several methods that you can use.
Here are a few.
co
1. equals( ) - used to test whether two strings are equal or not
2. length() –used to find the length of the string
3. charAt(i) - used to retrieve the character from the string at the index i.
a.
4. compareTo(String) –returns 0, if the string lexicographically equals to the argument,
returns greater than 0 if the argument is lexicographically greater than this string, returns
less than 0 otherwise.
iy
5. indexOf(char) –returns the index of first occurrence of the character.
6. lastIndesOf(char)- returns the last index of the character passed to it.
7. concat(String) -Concatenates the string with the specified argument
un
Example :int n=myString.length(); //gives the length of the string
Part-II
sD
Introduction to classes
Fundamentals of the class
al
A class is a group of objects that has common properties. It is a template or blueprint from
which objects are created. The objects are the instances of class. Because an object is an
ri
instanceof a class, you will often see the two words object and instance used interchangeably.
A class is used to define new type of the data. Once defined, this new type can be used to create
to
objects of its type. The class is the logical entity and the object is the logical and physical entity.
Aclass is declared by use of the class keyword. The classes that have been used up to thispoint
are actually very limited examples of its complete form. Classes can (and usually do)get much
more complex. A simplified general form of a class definition is shown here:
class classname
{
type instance-variable1;
type instance-variable2;
………………………………..
……………………………….
type instance-variableN;
TutorialsDuniya.com
Download FREE Computer Science Notes, Programs, Projects,
Books PDF for any university student of BCA, MCA, B.Sc,
B.Tech CSE, M.Sc, M.Tech at https://www.tutorialsduniya.com
type method1(parameterlist)
{
//body of the method1
}
m
type method2(parameterlist)
{
//body of the method2
co
}
……………………………………..
……………………………………..
type methodN(parameterlist)
a.
{
//body of the methodN
iy
}
}
The data or variables, defined within the class are called, instance variable.
un
The methods also contain the code.
The methods and instance variable collectively called as members.
Variable declared within the methods are called local variables.
sD
A Simple Class
Let’s begin our study of the class with a simple example. Here is a class called Box that defines
three instance variables: width, height, and depth. Currently, Box does not contain any
al
methods.
class Box
ri
{ //instance variables
double width;
double height;
to
double depth;
}
As stated, a class defines new data type. The new data type in this example is, Box. This defines
Tu
Effect: b null
Declares the class variable. Here the class variable contains the value null. An attempt to access
the object at this point will lead to Compile-Time error.
Step 2:
m
Box b=new Box();
Here new is the keyword used to create the object. The object name is b. The new operator
co
allocates the memory for the object, that means for all instance variables inside the object,
memory is allocated.
Width
a.
Effect: b Height
Depth
iy
Box Object
Step 3:
un
There are many ways to initialize the object. The object contains the instance variable.
The variable can be assigned values with reference of the object.
b.width=12.34;
sD
b.height=3.4;
b.depth=4.5;
BoxDemo.java
class Box
{
ri
double width;
double height;
double depth;
to
}
// This class declares an object of type Box.
Tu
class BoxDemo
{
public static void main(String args[])
{
//declaring the object (Step 1) and instantiating (Step 2) object
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables (Step 3)
mybox.width = 10;
mybox.height = 20;
https://www.tutorialsduniya.com
Unit 2: Java Basics
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
m
When you compile this program, youwill find that two .class files have been created, one for
Box and one for BoxDemo. The Javacompiler automatically puts each class into its own .class
co
file. It is not necessary for both theBox and the BoxDemo class to actually be in the same source
file.
To run this program, you must execute BoxDemo.class. When you do, you will see the
a.
following output:
Volume is 3000.0
iy
As stated earlier, each object has its own copies of the instance variables. This means thatif you
un
have two Box objects, each has its own copy of depth, width, and height. It is importantto
understand that changes to the instance variables of one object have no effect on the
instancevariables of another. For example, the following program declares two Box objects:
// This program declares two Box objects.
sD
class Box
{
double width;
double height;
double depth;
al
}
class BoxDemo2
{
public static void main(String args[])
ri
{
Box mybox1 = new Box();
Box mybox2 = new Box();
to
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
Tu
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}
https://www.tutorialsduniya.com
Unit 2: Java Basics
m
You might think that b2 is being assigned a reference to a copy of the object referred to byb1.
That is, you might think that b1 and b2 refer to separate and distinct objects. However,this would
co
be wrong. Instead, after this fragment executes, b1 and b2 will both refer to thesame object. The
assignment of b1 to b2 did not allocate any memory or copy any part of theoriginal object. It
simply makes b2 refer to the same object as does b1. Thus, any changesmade to the object
a.
through b2 will affect the object to which b1 is referring, since they are thesame object.
This situation is depicted here:
iy
un
sD
Introduction to Methods
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
al
type name(parameter-list)
{
// body of method
t
}
Tu
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 typemust be void.
The name of the method is specified by name. This can be any legal identifierother than those
already used by other items within the current scope. The parameter-list is asequence of type and
identifier pairs separated by commas. Parameters are essentially variablesthat receive the value
of the argumentspassed to the method when it is called. If the methodhas 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 usingthe
following form of the return statement:
return value;
https://www.tutorialsduniya.com
Unit 2: Java Basics
m
{
double width, height, double depth;
// display volume of a box
co
void volume()
{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
a.
}
Here the method name is "volume()". This methods contains some code fragment for computing
the volume and displaying. This method cane be accessed using the object as in the following
iy
code:
BoxDemo3.java
class BoxDemo3
un
{
public static void main(String args[])
{
Box mybox1 = new Box();
// assign values to mybox1's instance variables
sD
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
al
}
to
Returning a Value
A method can also return the value of specified type. In this case the type of the method should
Tu
be clearly mentioned. The method after computing the task returns the value to the caller of the
method.
BoxDemo3.java
Box
{
double width, height, depth;
double volume()
{
return (width*height*depth);
https://www.tutorialsduniya.com
Unit 2: Java Basics
}
}
class BoxDemo3
{
public static void main(String args[])
m
{
Box mybox1 = new Box();
// assign values to mybox1's instance variables
co
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
a.
double vol;
/* assign different values to mybox2's
//calling the method
iy
vol= mybox1.volume();
System.out.println("the Volume is:"+vol);
}
un
}
We can also pass arguments to the method through the object. The parameters separated with
comma operator. The values of the actual parameters are copied to the formal parameters in the
method. The computation is carried with formal arguments, the result is returned to the caller of
the method, if the type is mentioned.
al
{
width=w;
height=h;
to
depth=d;
return (width*height*depth);
}
Tu
Constructors
It can be tedious to initialize all of the variables in a class each time an instance is
created. Even if we use some method to initialize the variable, it would be better this
initialization is done at the time of the object creation.
void. This isbecause the implicit return type of a class’ constructor is the class type itself. It is the
constructor’sjob to initialize the internal state of an object so that the code creating an instance
will havea fully initialized, usable object immediately.
Example Program:
class Box
{
m
double width;
double height;
double depth;
// This is the constructor for Box.
co
Box()
{
System.out.println("Constructing Box");
width = 10;
a.
height = 10;
depth = 10;
}
iy
// compute and return volume
double volume()
{
return width * height * depth;
un
}
}
class BoxDemo6 {
public static void main(String args[]) {
sD
Parameterized Constructors
While the Box( ) constructor in the preceding example does initialize a Box object, it is notvery
to
useful—all boxes have the same dimensions. What is needed is a way to construct Boxobjects of
various dimensions. The easy solution is to add parameters to the constructor.
Tu
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
m
}
}
co
class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
a.
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
iy
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
un
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
sD
}
Constructor-overloading
In Java it is possible to define two or more class constructors that share the same name, as
al
long as their parameter declarations are different. This is called constructor overloading.
When an overloaded constructor is invoked, Java uses the type and/or number
ofarguments as its guide to determine which version of the overloaded constructor to
ri
actuallycall. Thus, overloaded constructors must differ in the type and/or number of their
parameters.
to
Example: All the constructors names will be same, but their parameter list is different.
OverloadCons.java
class Box {
Tu
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
https://www.tutorialsduniya.com
Unit 2: Java Basics
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
m
return width * height * depth;
}
}
co
class OverloadCons
{
public static void main(String args[])
a.
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
iy
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
un
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
sD
Garbage Collection
Tu
Since objects are dynamically allocated by using the new operator, you might be
wonderinghow such objects are destroyed and their memory released for later reallocation. In
somelanguages, such as C++, dynamically allocated objects must be manually released by use
ofa delete operator. Java takes a different approach; it handles deallocation for you
automatically.The technique that accomplishes this is called garbage collection.Java has its own
set of algorithms to do this as follow.
There are Two Techniques: 1) Reference Counter 2) Mark and Sweep. In the
Reference Counter technique, when an object is created along with it a reference counter is
maintained in the memory. When the object is referenced, the reference counter is incremented
by one. If the control flow is moved from that object to some other object, then the counter value
is decremented by one. When the counter reaches to zero (0), then it's memory is reclaimed.
https://www.tutorialsduniya.com
Unit 2: Java Basics
In the Mark and Sweep technique, all the objects that are in use are marked and are called
live objects and are moved to one end of the memory. This process we call it as compaction. The
memory occupied by remaining objects is reclaimed. After these objects are deleted from the
memory, the live objects are placed in side by side location in the memory. This is called
copying.
m
It works like this: when noreferences to an object exist, that object is assumed to be no
longer needed, and the memoryoccupied by the object can be reclaimed. There is no explicit
need to destroy objects as in C++.Garbage collection only occurs during the execution of your
co
program. The main job of this is to release memory for the purpose of reallocation.
Furthermore,different Java run-time implementations will take varying approaches to garbage
collection
a.
The finalize( ) Method
Sometimes an object will need to perform some action when it is destroyed. For example,
iy
if an object is holding some non-Java resource such as a file handle or character font, then you
might want to make sure these resources are freed before an object is destroyed. To handle such
situations, Java provides a mechanism called finalization. By using finalization, you candefine
un
specific actions that will occur when an object is just about to be reclaimed by thegarbage
collector.
To add a finalizer to a class, you simply define the finalize( ) method. The Java run time
sD
calls that method whenever it is about to recycle an object of that class. Inside the finalize(
)method, you will specify those actions that must be performed before an object is destroyed.The
garbage collector runs periodically, checking for objects that are no longer referenced byany
running state or indirectly through other referenced objects
al
}
Tu
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.
Overloading methods
In Java it is possible to define two or more methods within the same class that share thesame
name, as long as their parameter declarations are different. When this is the case, themethods are
said to be overloaded, and the process is referred to as method overloading. Methodoverloading
is one of the ways that Java supports polymorphism.
https://www.tutorialsduniya.com
Unit 2: Java Basics
When an overloaded method is invoked, Java uses the type and/or number ofarguments as its
guide to determine which version of the overloaded method to actuallycall. 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 isinsufficient to distinguish two versions of
a method. When Java encounters a call to anoverloaded method, it simply executes the version of
the method whose parameters matchthe arguments used in the call.
m
Here is a simple example that illustrates method overloading:
// Demonstrate method overloading.
co
class OverloadDemo
{
a.
void test()
{
System.out.println("No parameters");
iy
}
// Overload test for one integer parameter.
void test(int a)
un
{
System.out.println("a: " + a);
}
}
sD
class Overload
{
public static void main(String args[])
al
{
OverloadDemo ob = new OverloadDemo();
double result;
ri
}
}
The test() method is overloaded two times, first version takes no arguments, second
Tu
version takes one argument. When an overloaded method is invoked, Java looks for a match
between arguments of the methods.Method overloading supports polymorphism because it is
one way that Java implementsthe “one interface, multiple methods” paradigm.
static keyword
There will be times when you will want to define a class member that will be
usedindependently of any object of that class. Normally, a class member must be accessed onlyin
conjunction with an object of its class. However, it is possible to create a member that canbe
used by itself, without reference to a specific instance.
https://www.tutorialsduniya.com
Unit 2: Java Basics
To create such a member, precedeits declaration with the keyword static. When a
member is declared static, it can be accessedbefore any objects of its class are created, and
without reference to any object. You can declareboth methods and variables to be static. The
most common example of a static member ismain( ). 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
m
its class are declared, no copy of a static variable is made. Instead, all instances of the classshare
the same static variable.These variables are also called as "Class Variable".
Methods declared as static have several restrictions:
co
• They can only call other static methods.
• They must only access static data.
• They cannot refer to this or super in any way.
a.
If you need to do computation in order to initialize your static variables, you can declare astatic
block that gets executed exactly once, when the class is first loaded. The followingexample
iy
shows a class that has a static method, some static variables, and a static initializationblock:
class UseStatic
un
{
//static variable
static int a = 3;
static int b;
sD
//static method
static void meth(int x)
{
System.out.println("x = " + x);
al
//static block
static
{
to
x = 42
https://www.tutorialsduniya.com
Unit 2: Java Basics
a=3
b = 12
m
is,this is always a reference to the object on which the method was invoked. You can use
thisanywhere a reference to an object of the current class’ type is permitted.To better understand
what this refers to, consider the following version of Box( ):
co
// A redundant use of this.
Box(double w, double h, double d)
a.
{
this.width = w;
this.height = h;
iy
this.depth = d;
}
Note: This is mainly used to hide the local variables from the instance variable.
un
Example:
class Box
{
//instance variable
sD
width=width;
height=height;
depth=depth;
ri
}
}
To avoid the confusion, this keyword is used to refer to the instance variables, as follows:
to
class Box
{
//instance variable
Tu
Unit-33
Topics:
Inheritance –Types
Types of Inheritance, using the extends keyword, overriding
riding method,
method, super
keyword,, final keyword, abstract class.
m
Interfaces, Packages: Interface, extending interface, Interface Vs Abstract class, Creating
package, using the package, access protection.
protection
Exceptions and Assertions: Exception Handling techniques, User defined Exception,
co
exception encapsulation and enrichment, Assertions.
Assertions
Inheritance Vs Aggregation
a.
Inheritanceis
Inheritance is the process by which one class acquires the properties of another class.
Thisis important because it supports the concept of hierarchical classification. The class that
iy
is inherited is called superclass.
superclass. The class that is inheriting the properties is called
ca subclass
subclass.
Therefore
herefore the subclass is the specialized version of the superclass. The subclass inherits all
the instance variable and methods, and adds its own code.
un
Aggregation is the process of making an object combining number of other objects.
The behavior of the bigger object is defined by the behavior of its component objects. For
example, cars contain number of other components such as engine, clutches, breaks, starter
sD
etc.
Types of Inheritance
al
properties from
from another object
and adds its own code to it.
Multiple Inheritance:
In this one class acquires the
properties from
from two or more classes at a time and adds its own code to it.
Multilevel Inheritance:
In this one class acquires the properties from another class, which in turn has acquired the
properties from another class. Hence, in this there are many levels
level in the process of
Inheritance.
Hierarchical Inheritance:
In
n this two or more classes will acquire the properties from only one same class and add their
TutorialsDuniya.com
Download FREE Computer Science Notes, Programs, Projects,
Books PDF for any university student of BCA, MCA, B.Sc,
B.Tech CSE, M.Sc, M.Tech at https://www.tutorialsduniya.com
Note: Java Supports Single and Multilevel Inheritances between classes and Multiple
Inheritance among the Interfaces.
m
In Java, Properties from one class to another class are acquired using the keyword "extends".
co
The general for of inheritance will be as follow:
a.
//body of the subclass
}
iy
The following program creates a superclass called A and a subclass called B. Notice how the
un
keyword extends is used to create a subclass of A.
// A simple example of inheritance. SimpleInheritance.java
// Create a superclass.
class A
sD
{
int i, j;
void showij()
{
System.out.println("i and j: " + i + " " + j);
al
}
}
// Create a subclass by extending class A.
ri
class B extends A
{
int k;
to
void showk()
{
System.out.println("k: " + k);
}
Tu
void sum()
{
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance
{
public static void main(String args[])
{ // subclass object creation, which acquires all the properties of the superclass
B b = new B();
/* The subclass has access to all public members of its superclass. */
b.i = 7;b.j = 8;b.k = 9;
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
m
When a method in the subclass has the same name and type signature as a method in
its super class, the method in the sub class is said to "override" the method in the superclass.
When a overridden method is called by the subclass it always refers to the method of the
o
subclass. The super class version of the method is hidden.
.c
Example program
OverrideTest.java
import java.io.*;
a
class A
{
iy
int i;
void dooverride(int x)
{
un
i=x;
System.out.println("Value of i is:"+i);
}
lsD
}
class B extends A
{
void dooverride(int k)
{
ia
i=2*k;
System.out.println("Value of i is:"+i);
}
or
}
class OverrideTest
{ public static void main(String args[])
{
t
B b=new B();
Tu
b.dooverride(12);
}
}
Output:
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
m
hierarchy:
co
an error and will notcompile.*/
// Create a superclass.
a.
class A
{
iy
int i; // public by default
private int j; // private to A
void setij(int x, int y)
{
un
i = x;
j = y;
}
sD
}
// A's j is not accessible here.
class B extends A
{ int total;
al
void sum()
{
total = i + j; // ERROR, j is not accessible here
ri
}
}
to
class Access
{
public static void main(String args[])
Tu
{
B b = new B(); // creating the object b
b.setij(10, 12);
b.sum(); // Error, private members are not accessed
System.out.println("Total is " + subOb.total);
}
}
Note:
This program will not compile because the reference to j inside the sum( ) method of Bcauses
an access violation. Since j is declared as private, it is only accessible by other membersof its
own class. Subclasses have no access to it.
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
m
For example,
class Box
co
{
double width,height,depth;
}
a.
class Boxweight extends Box
{
double weight;
iy
Boxweight(double x,double y,double z,double z)
{
width=x; height=y; depth=z; weight=a;
un
}
void volume()
{
System.out.println("The volume is :"+(width*height*depth));
sD
}
}
//main class
class BoxDemo
al
{
//creating superclass object
public static void main(String args[])
ri
{
Box b=new Box();
//creating the subclass object
to
b=bw; // b has been created with its own data, in which weight is not a member
System.out.println ("The weight is :"+b.weight);
// here it raises error, super class does not contain the volume() method
}
}
"super" keyword
There are three uses of the super keyword.
i. super keyword is used to call the superclass constructor
ii. super keyword is used to access the super class methods
iii. super keyword is used to access the super class instance variables.
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
super(arg_list);
Here, the arg_list, is the list of the arguments in the superclass constructor. This must be the
first statement inside the subclass constructor. For example,
m
// BoxWeight now uses super to initialize its Box attributes.
class Box
{
co
double width,height,depth;
//superclass constructor
Box(double x,double y,double z)
a.
{
width=x;height=y;depth=z;
}
iy
class BoxWeight extends Box
{
double weight; // weight of box
un
// initialize width, height, and depth using super()
BoxWeight(double w, double h, double d, double m)
{
sD
The second form of super acts somewhat like this, except that it always refers to the
superclassof the subclass in which it is used. This usage has the following general form:
ri
super.member;
to
classhierarchy:
i = b; // i in B
}
void show()
{
System.out.println("i in superclass: " + super.i);
m
System.out.println("i in subclass: " + i);
}
}
co
class UseSuper
{
public static void main(String args[])
{
a.
B subOb = new B(1, 2);
subOb.show();
iy
}
}
un
"final" keyword
The "final" keyword is used for the following purposes.
to declare constants
sD
When a variable is declared as final through the program its value should not be changed by
al
the program statement. If any modification is done on the final variable, that can lead to error,
while compiling the program.
ri
class A
{
final int MAX=100; // (1) constant declaration
Tu
}
}
class B extends A
{
void disp()
{
System.out.println("The SUB class disp method :");
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
{
public static void main(String args[])
{
B b=new B();
b.disp();
}
m
}
Output:
co
E:\ksr>javac FinalTest.java
FinalTest.java:14: disp() in B cannot override disp() in A; overridden method is
final
a.
void disp()
^
1 error
iy
Explanation:
In the above program, the super class method is declared as final, and hence the sup class can
un
not override this. So we should not redefine the same method in the sub class. If we do so, it
leads to an error. If we do the same program with out disp() method in the sub class, it will
produce the following out put.
Example Program: removing the disp() method in the sub class
sD
import java.io.*;
class A
{
final int MAX=100; // (1) constant declaration
al
}
}
class B extends A
{ /*void disp() multiple comments
Tu
{
System.out.println("The SUB class disp method :");
}*/
}
class FinalTest
{ public static void main(String args[])
{ B b=new B();
b.disp();
}
}
Output:
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
m
implementations.
Here is an example of a final class:
co
final class A
{
a.
// ...
}
// The following class is illegal.
iy
class B extends A
{
un
// ERROR! Can't subclass A
// ...
}
As the comments imply, it is illegal for B to inherit A since A is declared as final.
sD
method without implementing it. The subclass can fill or implement the method according to
its requirements. This kind of situation can come into picture whenever the superclass unable
to implement the meaningful implementation of the method. For example, if we want to find
ri
the area of the Figure given, which can be Circle, Rectangle, and Traingle. The class
Figuredefines the method area(), when subclass implements its code, it implements its own
to
version of the method. The Java's solution to this problem is abstract method.
To declare a class abstract, you simply use the abstract keyword in front of the class
keywordat 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
wouldbe useless, because an abstract class is not fully defined.
Example Program:
FigureDemo.java
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
m
{
r=x;
}
co
//CIrcle implementing its own method
void area()
{
a.
a=3.14*r*r; //a is the meber of super class
System.out.println("The area of the traingle is :"+a);
}
iy
}
//Extending the super class
class Triangle extends Figure
un
{ double l,b;
Triangle(double x,double y)
{
l=x;
sD
b=y;
}
//Triangle implementing its own method
void area()
al
{
a=l*b; //a is the meber of super class
System.out.println("The area of the traingle is :"+a);
ri
}
}
class FigureDemo
to
{
public static void main(String args[])
{
Tu
Output:
E:\ksr>javac FigureDemo.java
E:\ksr>java FigureDemo
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
Up to this point, we have been using simple class hierarchies that consist of only a
superclassand a subclass. However, you can build hierarchies that contain as many layers of
inheritanceas you like. As mentioned, it is perfectly acceptable to use a subclass as a
superclass of another.For example, given three classes called A, B, and C, C can be a
m
subclass of B, which is asubclass of A. When this type of situation occurs, each subclass
inherits all of the traitsfound in all of its superclasses. In this case, C inherits all aspects of B
and A. To see howa multilevel hierarchy can be useful, consider the following program.
co
Multi Level Inheritance
Example program
class A
a.
class A{
{ methodA()
void methodA() }
iy
{
System.out.println("This is the method of A");
} class B{
un
} methodB()
//class b extends the super class A }
class B extends A
{
sD
class C extends B
{
void methodC()
to
{
System.out.println("This is the method of C");
}
Tu
}
class Hierachy
{
public static void main(String args[])
{
C cobj=new C();
c.methodA();
c.methodB();
c.methodC();
}
}
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
Let’s begin by restating an important principle: a superclass reference variable can referto a
m
subclass object. Java uses this fact to resolve calls to overridden methods at run time. Hereis
how. When an overridden method is called through a superclass reference, Java
determineswhich version of that method to execute based upon the type of the object being
co
referredto at the time the call occurs. Thus, this determination is made at run time.
Here is an example that illustrates dynamic method dispatch:
a.
class A
{
iy
void callme()
{
System.out.println("Inside A's callme method");
un
}
}
class B extends A
{
sD
// override callme()
void callme()
{
System.out.println("Inside B's callme method");
al
}
}
ri
class C extends A
{
// override callme()
to
void callme()
{
System.out.println("Inside C's callme method");
Tu
}
}
class Dispatch
{
public static void main(String args[])
{
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
The output from the program is shown here:
m
Inside A’s callme method
Inside B’s callme method
co
Inside C’s callme method
a.
Introduction to Packages
iy
One of the main features of the Object Oriented Programming language is the ability to reuse the
code that is already created. One way for achieving this is by extending the classes and
un
implementing the interfaces. Java provides a mechanism to partition the classes into smaller chunks.
This mechanism is the Package. The Package is container of classes. The class is the container of the
data and code. The package also addresses the problem of name space collision that occurs when
we use same name for multiple classes. Java provides convenient way to keep the same name for
sD
Benefits of packages:
1. The classes in the packages can be easily reused.
al
2. In the packages, classes are unique compared with other classes in the other packages.
3. Packages provide a way to hide classes thus prevent classes from accessing by other
programs.
ri
Categories of Packages
to
The Java Packages are categorized into two categories (i) Java API Packages (ii) User Defined
Packages.
1. Java API Packages –Java API provides large number of classes grouped into different
Tu
packages according to the functionality. Most of the time we use the package available with Java
API.
java
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
m
automatically uses this package. This includes the classes
such as primitive data types, String, StringBuffer,
StringBuilde etc;
co
2 java.util Contains the language utility classes such asa Vectors,
Hash Table , Date, StringTokenizer etc;
3 java.io Contains the classes that support input and output classes.
a.
4 java.awt Contains the classes for implementing the graphical user
interfaces
5 Java.net Contains the classes for networking
iy
6 Java.applet Contains the classes for creating and implementing the
applets.
un
Using the System Packages
Packages are organized in hierarchical structure, that means a package can contain another
package, which in turn contains several classes for performing different tasks. There are two ways to
access the classes of the packages.
sD
i. fully qualified class name- this is done specifying package name containing the class and
appending the class to it with dot (.) operator.
Example: java.util.StringTokenizer(); Here, "java.util" is the package and
"StringTokenizer()" is the class in that package. This is used when we want to refer to
al
ii. import statement –this is used when we want to use a class or many classes in many
ri
Packages can be named using the Java Standard naming rules. Packages begin with "lower
case" letters. It is easy for the user to distinguish it from the class names. All the class Name by
convention begin with "upper case" letters. Example:
Tu
double d= java.lang.Math.sqrt(3);
Here, "java.lang" is the package, and "Math" is the class name, and "sqrt()" is the method name.
2. User Define Packages
To create a package is quite easy: simply include a package command in the first line of the
source file. A class specified in that file belongs to that package. The package statement defines a
name space in which classes are stored. If you omit the package statement, the class names are put
in the default package, which has no name.
The general form of the package statement will be as followed: package pkg;
Here, "pkg" is the package name. Example: package MyPackage;
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
We can create hierarchy of packages. To do so, simply separate package name from the
above one with it by use of the dot (.) operator. The general form of multileveled package statement
is shown here: package pkg1.pkg2.pkg3;
Example: package iicse.asection.java
m
Finding the Packages and CLASSPATH
Packages are mirrored by the directories. This raises an import question: how does Java-Run
co
time system look for the packages that you create? The answer has three parts: (1) By default, Java-
Run time system uses the current working directory as its starting point. Thus your package is in a
subdirectory of your directory, it will be found. (2) You can specify a directory path by setting the
a.
CLASSPATH environment variable. (3) You can use - classpath option with java and iavacto specify
the path for the classes.
iy
A Short Example Package: Balance.java
un
lsD
r ia
to
Tu
Open a notepad or text editor, write the above code and save it as "Balance.java" in the
folder name "Mypackage. Here, the package name and subdirectory(folder) name must be same.
This subdirectory(Folder) must be part of your main current directory (current Folder) in which you
write the main class PackTest1.java. That means the "PackTest1.java" source file and "MyPackage"
will be in the same directory (Folder). The "Balance.java" file must be compiled to generate the
".class" file in the same directory(folder), which will be accessed in another program by importing
TutorialsDuniya.com
Download FREE Computer Science Notes, Programs, Projects,
Books PDF for any university student of BCA, MCA, B.Sc,
B.Tech CSE, M.Sc, M.Tech at https://www.tutorialsduniya.com
PackTest1.java
c om
a.
iy
Output
un
sD
al
ri
m
co
a.
Package and Member Accessing
iy
The visibility of an element is specified by the access specifiers: public, private, and
protected and also the package in which it resides. The visibility of an element is determined by its
un
visibility within class, and visibility within the package.
- If any members explicitly declared as "public", they are visible everywhere, including in
different classes and packages.
- "private" members are accessed by only other members of its class. A private member is
unaffected by its membership in a package.
sD
- A member specified as "protected" is accessed within its package and to all subclasses.
package by
subclasses
3 Visible within No YES YES YES
Tu
same package
by non-
subclass
4 Visible within NO NO YES YES
different
packages by
subclasses
5 Visible within NO NO NO YES
different
packages by
Non-
subclasses
Adding a class to a Package:
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
A.java
package p1;
public class A
{
// body of the class
m
}
co
Here, the package p1 contains one public class by the name A. Suppose if we want to add another
class B to this package. This can be done as follows:
a.
2. Place the package statement in the begin of class definition
package p1;
iy
public class B
{
//body of the class B
}
un
3. store this as "B.java" file under the directory p1.
4. Compile "B.java" file by switching to the subdirectory. This will create "B.class" file and place
it in the directory p1.
Now the package p1 will contain both A.class and B.class files
sD
Introduction to Interfaces
al
Java supports the concept of Inheritance, that is acquiring the properties from one class to
other class. The class that acquire properties is called "subclass", and the class from which it acquire
is called "superclass". Here, one class can acquire properties from other class using the following
ri
statement:
class A extends B
to
{
---------
---------
Tu
}
But, Java does not allow to acquire properties from more than one class, which we call it as
"multiple inheritance". We know that large number of real-life applications require the use of
multiple inheritance. Java provides an alternative approach known as "interface" to support the
concept of multiple inheritance.
Defining Interface
An interface is basically a kind of class. Like classes, interfaces contain the methods and
variables but with major difference. The difference is that interface define only abstract methods
and final fields. This means that interface do not specify any code to implement these methods and
data fields contain only constants. Therefore, it is the responsibility of the class that implements an
interface to define the code for these methods.
The syntax of defining an interface is very similar to that of class. The general form of an
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
interface Intyerface_name
{
//variables inside interface are by default final, publicand static
type id=value;
//by default abstract methods
m
return_type method_name(paprameter_list);
return_type method_name(paprameter_list);
return_type method_name(paprameter_list);
co
}
// Here, interface is the keyword and the Calculator is name for interface. The variables are declared
a.
as follows:
Note: 1) variables inside interface are by default final, public and static
iy
2) by default methods are public and abstract
These methods must be implemented any class that want to acquire the properties.
un
Here is an example of an interface definition that contain two variable and one method
interface Calculator
sD
{
//variables inside interface are by default final, public and static
double PI=3.14;
//by default abstract methods
al
Interfaces are used as "superclasses" whose properties are inherited by the classes. It is
therefore necessary to create a class that inherits the given interface. This is done as follows:
Here, Class_Name class, implements the interface "Interface_Name". A more general form
of implementation may look like this:
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
{
// body of the class
}
This shows that a class can extend another class while implementing interfaces. When a class
m
implements more than one interface they are separated by a comma.
co
InterfaceTest.Java
interface Calculator
{
a.
//variables inside interface are by default final, publi and static
double PI=3.14;
//by default abstract methods
iy
int add(int a,int b);
int sub(int a,int b);
int mul(int a,int b);
int div(int a,int b);
un
double area(int r);
}
class NormCal implements Calculator
sD
{
public int add(int x,int y)
{
return(x+y);
}
al
return(x-y);
}
public int mul(int x,int y)
to
{
return(x*y);
}
Tu
}
}
OutPut:
E:\ksr>javac NormCal.java
m
E:\ksr>java NormCal
The sum is:5
The sum is:-1
co
The sum is:6
The sum is:2
area of Circle is:78.5
a.
Extending the Interfaces
iy
Like classes interfaces also can be extended. That is, an interface can be subinterfaced from
other interface. The new subinterface will inherit all the members from the superinterface in the
manner similar to the subclass. This is achieved using the keyword extends as shown here:
un
interface Interface_Name1 extends Interface_Name2
{
//Body of the Interface_name1
sD
interface Const
{
static final int code=501;
ri
{
void display();
}
Tu
m
co
Interfaces Vs Abstract classes
Sl Interface Abstract
a.
1 Multiple Inheritance possible Multiple Inheritance not possible
2 implements keyword is used extends keyword is used
3 By default all the methods are Methods have to be tagged as public and abstract.
iy
public, and abstract. No need to
tag as public and abstract
4 All methods of interface need to Only abstract methods need to be overridden
un
be overridden
5 All variable declared in interface Variable if required, need to be declared in
are By default public, final and interface as public, final and static
static
sD
Introduction to Exception
ri
exceptional (that is, error) condition that has occurred in a piece of code. When an
exceptional condition arises, an object representing that exception is created and thrown in
Tu
the method that caused the error. That method may choose to handle the exception itself, or
pass it on. Either way, at some point, the exception is caught and processed.
2. If an exception occurs within the try block, it is thrown. Your code can catch this
exception (using catch) and handle it in some rational manner.
3. System-generated exceptions are automatically thrown by the Java run-time system.
To manually throw an exception, use the keyword throw.
4. Any exception that is thrown out of a method must be specified as such by a throws
clause.
m
5. Any code that absolutely must beexecuted after a try block completes is put in a
finally block.
co
Syntax:
try
a.
{
// block of code to monitor for errors
}
iy
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
un
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
sD
}
// ...
finally
{
al
Exception Types
All exception types are subclasses of the built-in class Throwable. Thus, Throwable
is at thetop of the exception class hierarchy. Immediately below (Fig 2) Throwable are two
to
subclasses thatpartition exceptions into two distinct branches. One branch is headed by
Exception. This classis used for exceptional conditions that user programs should catch. This
is also the class thatyou will subclass to create your own custom exception types. There is an
Tu
The other branch is topped by Error, which defines exceptions that are not expected
tobe caught under normal circumstances by your program. Exceptions of type Error are
usedby the Java run-time system to indicate errors having to do with the run-time
environment,itself. Stack overflow is an example of such an error. This chapter will not be
dealing withexceptions of type Error, because these are typically created in response to
catastrophic failuresthat cannot usually be handled by your program.
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
Throwable class
m
Exception class
Error
co
a.
Run_Time Exception IOException
iy
Fig 2: Exception Types
The Java Built-in Exceptions are broadly classified into two categories: Checked and
un
Unchecked exceptions.The Checked Exceptions are those for which the compiler checks to
see whether they have been handled in your program or not. Unchecked or Run_Time
Exceptions are not checked by the compiler. These Unchecked Exceptions are handled by the
Java Run_Time System automatically.
sD
InerruptedException ClassCastException
IOException BufferOverFlowException
IllegalAccessException BufferUnderFlowException
ri
Uncaught Exceptions:
to
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
Tu
class Exc0
{
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
anew exception object and then throwsthis exception. This causes the execution of Exc0 to
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
In the above program we have not provided any exception handler, in this context the
exception is caught by the default handler. The default handler displays string describing
the exception.
Here is the exception generated when this example is executed:
m
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
co
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 typeof
exception thrown is a subclass of Exception called ArithmeticException, which
a.
morespecifically describes what type of error happened.
iy
Although the default exception handler provided by the Java run-time system is useful
un
fordebugging, you will usually want to handle an exception yourself. Doing so provides
twobenefits.
First, it allows you to fix the error.
Second, it prevents the program from automatically terminating.
sD
Most users would be confused (to say the least) if your program stopped running and printed
a stack trace whenever an error occurred! Fortunately, it is quite easy to prevent this.
To guard against and handle a run-time error, simply enclose the code that you wantto
monitor inside a try block. Immediately following the try block, include a catch clausethat
al
specifies the exception type that you wish to catch. To illustrate how easily this can bedone,
the following program includes a try block and a catch clause that processes
ri
Exc2.java
to
class Exc2
{
public static void main(String args[])
Tu
{
int d, a;
try {
// monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{ // catch divide-by-zero error
System.out.println("Division by zero.");
}
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
Note: println() statement inside the "try" will never execute, because once the exception is
raised the control is transferred to the "catch" block. Here is catch is not called, hence it will
not return the control back to the "try" block. The "try" and "catch" will form like a unit. A
catch statement cannot handle the exception thrown by another "try" block.
m
Throwable overrides the toString( ) method (defined by Object) so that it returns a
stringcontaining a description of the exception. You can display this description in a println(
co
)statement by simply passing the exception as an argument. For example, the catch blockin
the preceding program can be rewritten like this:
catch (ArithmeticException e)
a.
{
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue
iy
}
When this version is substituted in the program, and the program is run, each divide-by-zero
error displays the following message:
un
Exception: java.lang.ArithmeticException: / by zero
In some cases, more than one exception could be raised by a single piece of code. To
handlethis type of situation, you can specify two or more catch clauses, each catching a
differenttype of exception. When an exception is thrown, each catch statement is inspected in
order,and the first one whose type matches that of the exception is executed. After one
al
catchstatement executes, the others are bypassed, and execution continues after the
try/catchblock. The following example traps two different exception types:
ri
{
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
m
The try statement can be nested. That is, a try statement can be inside the block of another
try.Each time a try statement is entered, the context of that exception is pushed on the stack.
If aninner try statement does not have a catch handler for a particular exception, the stack is
co
unwound and the next try statement’s catch handlers are inspected for a match. This
continuesuntil one of the catch statements succeeds, or until all of the nested try statements
are exhausted.If no catch statement matches, then the Java run-time system will handle the
a.
exception.
throw:
iy
So far, you have only been catching exceptions that are thrown by the Java run-time
systemimplicitly. However, it is possible for your program to throw an exception explicitly,
un
using the throwstatement. The general form of throw is shown here:
throwThrowableInstance;
sD
{
public static void main(String args[])
{
ri
method1();
}
to
try
{
method2();
}
catch(Exception e)
{
System.out.println("The Exception is:"+e);
}
System.out.println("After Method 2");
}
static void method2()
{
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
m
co
throws:
a.
If a method is capable of causing an exception that it does not handle, it must specify
thisbehavior so that callers of the method can guard themselves against that exception. You
dothis by including a throws clause in the method’s declaration. Athrows clause lists the
iy
typesof exceptions that a method might throw. This is necessary for all exceptions, except
those oftype Error or RuntimeException, or any of their subclasses. All other exceptions
that a methodcan throw must be declared in the throws clause. If they are not, a compile-time
un
error will result.
This is the general form of a method declaration that includes a throws clause:
lsD
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
a
Example Program:
ri
ThrowsDemo.java
to
import java.io.*;
class ThrowsDemo
{
Tu
m
catch(ArithmeticExceptionae)
{
System.out.println("Exception is:"+ae);
o
}
}
.c
}
Output:
a
iy
un
sD
finally:
al
The finally block is always is executed. It is always used to perform house keeping
operations such as releasing the resources, closing the files that already opened etc,. That
means the statement that put inside the finally block are executed compulsorily.It is always
ri
{
// statements
}
Tu
catch(Exception e) {
//Handlers
}
finally
{
//statements
}
Exception encapsulation and enrichment
The process of wrapping the caught exception in a different exception is called "Exception
Encapsulation". The Throwable super class has added one parameter in its constructor for the
wrapped exception and a "getCause()" method to return the wrapped exception. Wrapping is
also used to hide the details of implementation.
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
m
}
Disadvantages of wrapping:
It leads to the long Stack traces.
co
It is a difficult task to figure out where the exception is
Solution:
The possible solution is Exception enrichment. Here we don’t wrap exception but we add
a.
some information to the already thrown exception and rethrow it.
Example program:
iy
class ExcepDempo extends Exception
{
String message;
un
ExcepDemo(String msg)
{
message=msg;
}
sD
}
class ExcepEnrich
{
ri
{
e.addInformation("Example Exception");
}
}
public static void main(String args[])
{
try
{
testException();
}
catch(Exception e)
{
https://www.tutorialsduniya.com
Unit 3: Inheritance ,Interfaces, Packages,Exceptions and Assertions
Assertions:
Assertions are added after java 1.4 to always createreliable programs that are Correct and
robust programs. The assertions are boolean expressions.Conditions such as positve number
or negative number are examples.
m
Syntax:
assert expression1;
or
co
assert expression1:expression2;
Where assert is the keyword. Expression 1 is the boolean expression, expression2 is the
string that describes the Exceptions.
a.
Note: assertions must be explicitly enabled. The –ea option is used to enable the exception
and –da is used to disable the exception.
AI.java
iy
class AI
{
static void check(int i)
un
{
assert i>0:" I must be positive:";
System.out.prinln("Your I value if fine");
}
sD
c:>javac AI.java
Running the Program:
to
C:>java –ea AI
Unit 4
Multithreading
Topics:
MultiThreading: java.lang.Thread, the main thread, Creation of new thread, Thread priority,
m
Multithreading, Synchronization, Suspending and resuming threads, Communication between
threads, Input/Output: reading and writing data, java.io.package.
co
Introduction
The program in execution is called "Process". The program can be structured as set of individual
a.
units that can run in parallel. These units can be called as "Threads". Multithreading is actually a
kind of multitasking. The multitasking is either process-based or thread base. Process-based
multitasking is nothing but, execution of more than one program concurrently. Thread-based
iy
multitasking allows more than one thread within the program run simultaneously or
concurrently.The process is a Heavy Weight Process. The Thread is a Light Weight Process. The
context-switching of CPU from one process to other requires more overhead as it different
un
address spaces are involved in it. On the other hand, context-switching is less overhead because
of all the threads within the same program. The objective of all forms of the Multitasking
including the multithreading is to utilize the idle time of the processor. From here onwards,
thread-based multitasking is called "Multithreading".
sD
costly in terms of memory because they run on the same address space
This is not under the control of Java This is controlled by Java
Tu
Multithreading in Java
Every program that we have been writing has at least one thread, that is, the "main" thread.
Whenever a program starts executing, the JVM is responsible for creating the main thread and
calling "main()" method. Along with this main thread, some other threads are also running to
carryout the tasks such as "finalization" and "garbage collection". The thread can either die
naturally or be forced to die.
Thread dies naturally when it exits from the "run()" method.
Thread can be forced to die by calling "interrupt()" method.
https://www.tutorialsduniya.com
Unit 4: MultiThreading
java.lang.Thread package
Creation of Thread in java is very simple task. There is a class called "Thread", which belongs to
the "java.lang.Thread" package. This package contains one interface also called "Runnable".
Both these contain a common method called "run()" which is the heart of the thread. The run()
methods would have the following syntax:
m
Syntax:
public void run()
{
co
//statement for implementing the thread.
}
a.
The methods of the Thread class are as follow:
iy
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method
on the thread.
un
3. public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
sD
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
al
14. public void yield(): causes the currently executing thread object to temporarily
pause and allow other threads to execute.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been
m
interrupted.
Thread Constructors:
co
Thread ()-without arguments, default constructor
Thread(String str)- Thread contains name given as argument
a.
The Main Thread
iy
Every java program has a thread called "main" thread. When the program execution starts, the
JVM creates "main" Thread and calls the "main()" method from within that thread. Along with
this JVM also creates other threads for the purpose of the Housekeeping task such as "garbage"
un
collection. The "main" thread Spawns the other Threads. These spawned threads are called
"Child Threads". The main thread is always is the last thread to finish execution. We, as
Programmer can also take control of the main thread, using the method "currentThread()". The
main thread can be controlled by this method. We can also change the name of the Thread using
sD
Example Program:
MainThread.java
al
class MainThread
{
public static void main(String args[])
ri
{
Thread t=Thread.currentThread();
System.out.println("Name of the Thread is:"+t);
to
t.setName("KSR");
System.out.println("Name of the Thread is:"+t);
}
Tu
}
Output:
TutorialsDuniya.com
Download FREE Computer Science Notes, Programs, Projects,
Books PDF for any university student of BCA, MCA, B.Sc,
B.Tech CSE, M.Sc, M.Tech at https://www.tutorialsduniya.com
Creation of Threads
Creating the threads in the Java is simple. The threads can be implemented in the form of
object that contains a method "run()". The "run()" method is the heart and soul of any thread. It
makes up the entire body of the thread and is the only method in which the thread behavior can
be implemented. There are two ways to create thread.
m
1. Declare a class that extends the Thread class and override the run() method.
2. Declare a class that implements the Runnable interface which contains the run() method
co
1. Creating Thread using The Thread Class
We can make our thread by extending the Thread class of java.lang.Thread class. This gives us
a.
access to all the methods of the Thread. It includes the following steps:
I. Declare the class as Extending the Thread class.
II. Override the "run()" method that is responsible for running the thread.
iy
III. Create a thread and call the "start()" method to instantiate the Thread Execution.
Declaring the class
TheThread class can be declared as follows:
un
class MyThread extends Thread
{
-----------------------
----------------------
sD
----------------------
----------------------
}
al
{
----------------
----------------
to
----------------
}
Tu
Example program:
ThreadTest.java
import java.io.*;
import java.lang.*;
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("From Threaad A :i="+i);
m
}
System.out.println("Exit from Thread A");
}
co
}
a.
public void run()
{
iy
for(int j=1;j<=5;j++)
{
System.out.println("From Threaad B :j="+j);
}
un
System.out.println("Exit from Thread B");
}
}
class C extends Thread
sD
{
public void run()
{
for(int k=1;k<=5;k++)
al
{
System.out.println("From Threaad C :k="+k);
}
ri
}
class ThreadTest
{
public static void main(String args[])
Tu
{
System.out.println("main thread started");
A a=new A();
a.start();
B b=new B();
b.start();
C c=new C();
c.start();
System.out.println("main thread ended");
}
}
https://www.tutorialsduniya.com
Unit 4: MultiThreading
m
co
a.
iy
un
lsD
The Runnable interface contains the run() method that is required for implementing the threads
in our program. To do this we must perform the following steps:
ri
of the thread
IV. Call the thread's start() method to run the thread.
Tu
Example program:
Runnable.java
class A implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("A's i="+i);
}
}
}
https://www.tutorialsduniya.com
Unit 4: MultiThreading
m
System.out.println("B's i="+i);
}
}
co
}
class ITest
{
public static void main(String args[])
a.
{
A a=new A();
iy
Thread t1=new Thread(a);
t1.start();
B b=new B();
Thread t2=new Thread(b);
un
t2.start();
}
}
sD
Output: Threads A and B execution by running the above program two times. (You may see a different
sequence of Output, every time you run this program)
al
ri
to
Tu
https://www.tutorialsduniya.com
Unit 4: MultiThreading
m
By using the multithreading, your program can perform another task during this idle time.
For example, while one part of the program is sending a file over the internet, another part can
read the input from the keyboard, while other part can buffer the next block to send.
co
It is possible to run two or more threads in multiprocessor or multi core systems
simultaneously.
a.
Thread States
A thread can be in one of the several states. In general terms, a thread can running. It can be
iy
ready to run as soon as it gets the CPU time.A running thread can be suspended, which is a temporary
halt to its execution. It can later be resumed. A thread can be blocked when waiting for the resource. A
un
thread can be terminated.
{
----------- //body
----------
ri
} //ending
to
Multithreaded Program
Tu
A unique property of the java is that it supports the multithreading. Java enables us the
multiple flows of control in developing the program.
Each separate flow of control is thought as tiny program known as "thread" that runs in
parallel with other threads.
In the following example when the main thread is executing, it may call thread A, as the
Thread A is in execution again a call is mad for Thread B. Now the processor is switched
from Thread A to Thread B. After the task is finished the flow of control comes back to
the Thread A.
The ability of the language that supports multiple threads is called "Concurrency". Since
threads in the java are small sub programs of the main program and share the same
address space, they are called "light weight processes".
https://www.tutorialsduniya.com
Unit 4: MultiThreading
Main thread
m
Start
Start
Start
co
switch
Thread A Thread B switch Thread C
a.
The Main Thread
iy
When a Java program starts up, one thread begins running immediately. This is usuallycalled the
main thread of your program, because it is the one that is executed when yourprogram begins.
un
The main thread is important for two reasons:
• It is the thread from which other “child” threads will be spawned.
• Often, it must be the last thread to finish execution because it performs
variousshutdown actions.
sD
Although the main thread is created automatically when your program is started, it canbe
controlled through a Thread object. To do so, you must obtain a reference to it by callingthe
method currentThread( ), which is a public static member of Thread. Its general form isshown
here:
al
static Thread.currentThread( )
ri
This method returns a reference to the thread in which it is called. Once you have a reference
to the main thread, you can control it just like any other thread.
Let’s begin by reviewing the following example:
to
CurrentThreadDemo.java
// Controlling the main Thread.
class CurrentThreadDemo
Tu
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " + t);
try
{
https://www.tutorialsduniya.com
Unit 4: MultiThreading
m
}
catch (InterruptedException e)
{
co
System.out.println("Main thread interrupted");
}
}
a.
}
Output
iy
un
sD
al
So far, you have been using only two threads: the main thread and one child thread. However,
your program can spawn as many threads as it needs. For example, the following program
to
m
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
co
}
} catch (InterruptedException e)
{
a.
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
iy
}//end of run method
}//end of NewThread
class MultiThreadDemo
un
{
public static void main(String args[])
{
new NewThread("One"); // start threads
sD
new NewThread("Two");
new NewThread("Three");
try
{
al
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
to
}
System.out.println("Main thread exiting.");
}
Tu
It is often very important to know which thread is ended. This helps to prevent the main from
terminating before the child Thread is terminating. To address this problem "Thread" class
provides two methods: 1) Thread.isAlive() 2) Thread.join().
This method returns the either "TRUE" or "FALSE" . It returns "TRUE" if the thread is alive,
returns "FALSE" otherwise.
While isAlive( ) is occasionally useful, the method that you will more commonly use towait for a
m
thread to finish is called join( ), shown here:
co
This method waits until the thread on which it is called terminates. Its name comes from
theconcept of the calling thread waiting until the specified thread joins it. Additional forms
a.
ofjoin( ) allow you to specify a maximum amount of time that you want to wait for the
specifiedthread to terminate.
iy
Example Program:
// Using join() to wait for threads to finish.
class NewThread implements Runnable
un
{
String name; // name of thread
Thread t;
NewThread(String threadname)
sD
{
name = threadname;
t = new Thread( name);
System.out.println("New thread: " + t.getName());
al
{
for(int i = 5; i > 0; i--)
{
Tu
class DemoJoin
{
public static void main(String args[])
{
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
m
NewThread ob3 = new NewThread("Three");
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
co
System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
// wait for threads to finish
try {
a.
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
iy
ob3.t.join();
}
catch (InterruptedException e)
un
{
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
sD
}
Life Cycle of a Thread
During the life time of the thread, there are many states it can enter. They include the following:
ri
Newborn state
Runnable State
to
Running State
Blocked state
Dead state
Tu
A thread can always in any one of the five states. It can move from one state to other via variety of
ways as shown in the fig.
Newborn State: When we create a thread it is said to be in the new born state. At this state we can do
the following:
schedule it for running using the start() method.
Kill it using stop() method.
https://www.tutorialsduniya.com
Unit 4: MultiThreading
Runnable State: A runnable state means that a thread is ready for execution and waiting for the
availability of the processor. That is the thread has joined the queue of the threads for execution. If all
the threads have equal priority, then they are given time slots for execution in the round rabin fashion,
first-come, first-serve manner. The thread that relinquishes the control will join the queue at the end
and again waits for its turn. This is known as time slicing.
m
Running state: Running state means that the processor has given its time to the thread for it execution.
The thread runs until it relinquishes the control or it is preempted by the other higher priority thread. As
co
shown in the fig. a running thread can be preempted using the suspen(), or wait(), or sleep() methods.
Blocked state: A thread is said to be in the blocked state when it is prevented from entering into
runnable state and subsequently the running state.
a.
Dead state: Every thread has a life cycle. A running thread ends its life when it has completed execution.
iy
It is a natural death. However we also can kill the thread by sending the stop() message to it at any time.
factors besides its priority. (For example, how an operating system implements multitaskingcan
affect the relative availability of CPU time.) A higher-priority thread can also preempt(stop)
alower-priority one. For instance, when a lower-priority thread is running and a higher-
prioritythread resumes (from sleeping or waiting on I/O, for example), it will preempt the
al
lowerprioritythread.
To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.
ri
Here, level specifies the new priority setting for the calling thread. The value of level must
bewithin the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1
Tu
You can obtain the current priority setting by calling the getPriority( ) method of Thread,shown
here:
Example Program:
https://www.tutorialsduniya.com
Unit 4: MultiThreading
m
System.out.println(" Child 1 is started");
}
}
co
class PThread2 extends Thread
{
public void run()
{
a.
System.out.println(" Child 2 is started");
}
iy
}
class PThread3 extends Thread
{
un
public void run()
{
System.out.println(" Child 3 is started");
}
sD
class PTest
{
public static void main(String args[])
al
{
//setting the priorities to the thread using the setPriority() method
ri
pt2.setPriority(9);
PThread3 pt3=new PThread3();
pt3.setPriority(6);
Tu
pt1.start();
pt2.start();
pt3.start();
//getting the priority
System.out.println("The pt1 thread priority is :"+pt1.getPriority());
}
}
https://www.tutorialsduniya.com
Unit 4: MultiThreading
Synchronization
When two or more threads need access to a shared resource, they need some way to
ensurethat the resource will be used by only one thread at a time. The process by which this
isachieved is called synchronization.
m
Key to synchronization is the concept of the monitor (also called a semaphore). A
monitoris an object that is used as a mutually exclusive lock, or mutex. Only one thread can own
amonitor at a given time. When a thread acquires a lock, it is said to have enteredthe monitor.All
co
other threads attempting to enter the locked monitor will be suspended until the firstthread
exitsthe monitor. These other threads are said to be waitingfor the monitor. A threadthat owns a
monitor can reenter the same monitor if it so desires.
a.
Let us try to understand the problem without synchronization. Here, in the following example to
threads are accessing the same resource (object) to print the Table. The Table class contains one
iy
method, printTable(int ), which actually prints the table. We are creating two Threads, Thread1
and Thread2, which are using the same instance of the Table Resource (object), to print the table.
When one thread is using the resource, no other thread is allowed to access the same resource
Table to print the table.
un
Example without the synchronization:
sD
Class Table
{
void printTable(int n)
{//method not synchronized
al
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
ri
try{
Thread.sleep(400);
}
to
catch(InterruptedException ie)
{
System.out.println("The Exception is :"+ie);
}
Tu
}
} //end of the printTable() method
}
t.printTable(5);
}
} //end of the Thread1
m
MyThread2(Table mt)
{
t=mt;
co
}
public void run()
{
t.printTable(100);
a.
}
} //end of Thread2
iy
class TestSynchronization1
{
public static void main(String args[])
{
un
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
sD
t2.start();
}
}
The output for the above program will be as follow:
al
Output: 5
100
10
ri
200
15
to
300
20
Tu
400
25
500
In the above output, it can be observed that both the threads are simultaneously accessing the
Table object to print the table. Thread1 prints one line and goes to sleep, 400 milliseconds, and
Thread1 prints its task.
method, it automatically acquires the lock for that object and releases it when the thread
completes its task.
The general form of the synchronized method is:
synchronized type method_name(para_list)
{
m
//body of the method
}
co
where synchronized is the keyword, method contains the type, and method_name represents the
name of the method, and para_list indicate the list of the parameters.
a.
Example using the synchronized method
Class Table
iy
{
Thread.sleep(400);
}
catch(InterruptedException ie)
{
System.out.println("The Exception is :"+ie);
al
}
}
} //end of the printTable() method
ri
{
Table t;
MyThread1(Table t)
{
Tu
this.t=t;
}
public void run()
{
t.printTable(5);
}
} //end of the Thread1
this.t=t;
}
public void run()
{
t.printTable(100);
}
} //end of Thread2
m
class TestSynchronization1
{
co
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
a.
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
iy
}
}
Output: 5
un
10
15
20
sD
25
100
200
al
300
400
500
ri
In the above output it can be observed that when Thread1 is accessing the Table object,
to
Thread2 is not allowed to access it. Thread1 preempts the Thread2 from accessing the
printTable() method.
Tu
Note:
1. This way of communications between the threads competing for same resource is
called implicit communication.
2. This has one disadvantage due to polling. The polling wastes the CPU time. To save
the CPU time, it is preferred to go to the inter-thread communication.
Inter-Thread Communication
If two or more Threads are communicating with each other, it is called "inter thread"
communication. Using the synchronized method, two or more threads can communicate
indirectly. Through, synchronized method, each thread always competes for the resource. This
https://www.tutorialsduniya.com
Unit 4: MultiThreading
way of competing is called polling. The polling wastes the much of the CPU valuable time. The
better solution to this problem is, just notify other threads for the resource, when the current
thread has finished its task, meanwhile other threads will be doing some useful work.. This is
explicit communication between the threads.
Java addresses this polling problem, using via wait(), notify(), and notifyAll() methods. These
m
methods are implemented as finalmethods in Object, so all classes have them. All three methods
can be called only fromwithin a synchronized context.
co
wait( ) tells the calling thread to give up the monitor and go to sleep until some
other thread enters the same monitor and calls notify( ).
notify( ) wakes up a thread that called wait( ) on the same object.
a.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of
the threads will be granted access.
iy
These methods are declared within Object, as shown here:
recommends that calls to wait( ) should take placewithin a loop that checks the condition on
which the thread is waiting. The followingexample shows this technique.
ri
class Q
to
{
int n;
boolean valueSet = false;//flag
Tu
valueSet = false;
notify();
return n;
} //end of the get() method
synchronized void put(int n)
{
m
while(valueSet)
try {
wait();
co
}
catch(InterruptedException e)
{
a.
System.out.println("InterruptedException caught");
}
this.n = n;
iy
valueSet = true;
System.out.println("Put: " + n);
notify();
un
}//end of the put method
} //end of the class Q
{
Q q;
Producer(Q q)
{
al
this.q = q;
new Thread(this, "Producer").start();
}
ri
while(true)
{
q.put(i++);
Tu
}
}
}//end of Producer
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q = q;
new Thread(this, "Consumer").start();
}
https://www.tutorialsduniya.com
Unit 4: MultiThreading
m
}
}//end of Consumer
co
class PCFixed
{
a.
public static void main(String args[])
{
Q q = new Q();
iy
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
un
}
}
Whenever we want stop a thread we can stop from running using "stop()" method of thread
class. It's general form will be as follows:
Thread.stop();
al
This method causes a thread to move from running to dead state. A thread will also move to
dead state automatically when it reaches the end of its method.
Blocking Thread
ri
A thread can be temporarily suspended or blocked from entering into the runnable and running
state by using the following methods:
sleep() —blocked for specified time
to
runnable state when the specified time is elapsed in the case of sleep(), the resume() method is invoked
in the case of suspend(), and the notify() method is called in the case of wait().
Example program:
The following program demonstrates these methods:
// Using suspend() and resume().
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
m
// This is the entry point for thread.
public void run()
{
co
try
{
for(int i = 15; i > 0; i--)
a.
{
System.out.println(name + ": " + i);
Thread.sleep(200);
iy
}
}
catch (InterruptedException e)
un
{
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
sD
}
}
class SuspendResume
{
al
Thread.sleep(1000);
ob1.t.suspend();
System.out.println("Suspending thread One");
Tu
Thread.sleep(1000);
ob1.t.resume();
System.out.println("Resuming thread One");
ob2.t.suspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.t.resume();
System.out.println("Resuming thread Two");
}
catch (InterruptedException e)
{
https://www.tutorialsduniya.com
Unit 4: MultiThreading
m
ob1.t.join();
ob2.t.join();
}
co
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
a.
}
System.out.println("Main thread exiting.");
}
iy
}
Thread Exceptions
un
Note that a call to the sleep() method is always enclosed in try/ catch block. This is necessary because
the sleep() method throws an exception, which should be caught. If we fail to catch the exception the
program will not compile.
it general form will be as follows:
sD
try
{
Thread.sleep(1000);
}
al
cathc(Exception e)
{ --------
---------
ri
}
Deadlock
Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a
to
thread is waiting for an object lock, that is acquired by another thread and second thread is
waiting for an object lock that is acquired by first thread. Since, both threads are waiting for
each other to release the lock, the condition is called deadlock.
Tu
Thread1 Thread2
Y
Here, in the above figure, the resource X is held by Thread1, and at the same time the Thread1 is
trying to access the resource which is held by the Thread2. This is causing the circular
dependency between two Threads. This is called, Deadlock.
https://www.tutorialsduniya.com
Unit 4: MultiThreading
Example program:
TestDead.java
public class TestDead
{
public static void main(String[] args)
{
m
final String resource1 = "John Gardner";
final String resource2 = "James Gosling";
// t1 tries to lock resource1 then resource2
co
Thread t1 = new Thread()
{
a.
public void run()
{ //locking the resource
synchronized (resource1)
iy
{
System.out.println("Thread 1: locked resource 1");
un
try {
Thread.sleep(100);
}
catch (Exception e)
sD
{
System.out.println(e);
}
al
synchronized (resource2)
{
System.out.println("Thread 1: locked resource 2");
ri
}
}
} //end of run()
to
}; //end of t1
synchronized (resource1)
https://www.tutorialsduniya.com
Unit 4: MultiThreading
{
System.out.println("Thread 2: locked resource 1");
}
}
}//end of run()
}; //end of t2
m
t1.start();
o
t2.start();
}
.c
}
a
Output:
iy
un
a lsD
ri
There are two predefined packages in java that contain classes to perform I/O operations. These
Tu
are java.io.*, and java.nio.*. The java.io.* used to perform reading and writing to console and
reading and writing to the Files. The java.nio.*, contains all the classes of java.io.*, and aslo
contain the classes to perform advanced operations such as buffering, memory mapping,
character encoding and decoding etc;. The java.io.* package provides separate classes for
reading and writing data , these are byte streams and character streams.
Stream
A stream can be defined as a sequence or flow of data. There are two kinds of Streams.
https://www.tutorialsduniya.com
Unit 4: MultiThreading
m
co
Byte Streams
8 bit bytes.
Java byte streams are used to perform input and output of 8-bit
a.
Though there are many classes related to byte streams but the most
FileOutputStream.
frequently used classes are , FileInputStream and FileOutputStream
iy
Following is an example which makes use of these two classes to copy an
input file into an output file:
un
CopyFile.java
import java.io.*;
java
sD
publicclass
publicclassCopyFile{
String args[])throws
publicstaticvoid main(String IOException
throwsIOException
{
al
FileInputStream
FileInputStreamin=null;
FileOutputStreamout=null
FileOutputStream null;
ri
try{
to
in=newFileInputStream "input.txt");
FileInputStream("input.txt"
out=newFileOutputStream
FileOutputStream( );
("output.txt");
Tu
int c;
while((c =in 1)
in.read())!=-1
out
out.write(c);
} //end of try
finally{
if(in!=null
null)
{
https://www.tutorialsduniya.com
Unit 4: MultiThreading
in.close();
if(out!=null)
m
out.close();
co
}//end of finally
}//end of main
} //end of class
a.
List of methods in java.io.InputStream class are as follow:
iy
Method Description
int available throws IOException Returns the number of available bytes that can be read
un
from input stream
void close() throws IOException Closes the input stream
Void mark( int readlimit) Makes the mark at the current position in the input
stream. readlimit defines after how many lines this
sD
mark is nullified
Void markSupported() Mark() method works if this method returns true
Abstract int read() Used to read next byte from the input stream. It returns
the byte, other wise -1 if EOF is encountered
al
Int read(byte []b) Reads the byte and stores them in byte array b if return
the true, otherwise -1 if EOF is encountered.
ri
Int read(byte []b, int off, int len) Reads the byte and stores them in byte array b upto the
length from the offset off in b.
Void reset() Resets the current pointer to the position set by the
to
mark
Long skip(long n) Skips the specified number of bytes from the input
stream
Tu
Method Description
Void close() Closes the output stream
Void flush() Flushes the output stream
Void write(byte [] b) Writes the contents of the byte array b to the output
stream
Void write(byte [] b, int off, int len) Writes the specified number of bytes (len) to the
output stream starting from the offset off in b
Abstract void write(int b) Abstract method to write to the output stream
https://www.tutorialsduniya.com
Unit 4: MultiThreading
m
co
a.
iy
un
java.io.File class
lsD
The Java.io.File class is an abstract representation of file and directory pathnames. Following
are the important points about File:
Instances may or may not denote an actual file-system object such as a file or a directory. If it does
a
denote such an object then that object resides in a partition. A partition is an operating system-
specific portion of storage for a file system.
ri
A file system may implement restrictions to certain operations on the actual file-system object, such
to
as reading, writing, and executing. These restrictions are collectively known as access permissions.
Instances of the File class are immutable; that is, once created, the abstract pathname represented b
Tu
m
pathname string.
String[] list() This method returns an array of strings naming the
files and directories in the directory denoted by this
co
abstract pathname.
boolean isDirectory() This method tests whether the file denoted by this
abstract pathname is a directory.
a.
boolean isFile() This method tests whether the file denoted by this
abstract pathname is a normal file.
iy
Example program:
FileDemo.java
import java.io.File;
un
class FileDemo
{
public static void main(String args[])
{
sD
Output:
ri
to
Tu
FIleInputStream and FileOutputStream classes are used to read and write respectively. The
Constructor will be as follow:
m
1 public void close() throws IOException{}
co
This method closes the file output stream. Releases any system resources associated
with the file. Throws an IOException.
a.
2 protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of
iy
this file output stream is called when there are no more references to this stream.
Throws an IOException.
un
3 public int read(int r)throws IOException{}
This method reads the specified byte of data from the InputStream. Returns an int.
sD
Returns the next byte of data and -1 will be returned if it's end of file.
This method reads r.length bytes from the input stream into an array. Returns the
total number of bytes read. If end of file -1 will be returned.
ri
Gives the number of bytes that can be read from this file input stream. Returns an
int.
Tu
FileOutputStream is used to create a file and write data into it. The stream would create a file, if
it doesn't already exist, before opening it for output.
The Constructor will be as follow:
m
1 public void close() throws IOException{}This method closes the file output stream.
Releases any system resources associated with the file. Throws an IOException
co
2 protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this
file output stream is called when there are no more references to this stream. Throws
a.
an IOException.
iy
This methods writes the specified byte to the output stream.
import java.io.*;
publicclass fileStreamTest{
al
try{
to
OutputStream os =newFileOutputStream("test.txt");
Tu
os.close();
InputStreamis=newFileInputStream("test.txt");
System.out.print((char)is.read()+" ");
is.close();
m
}catch(IOException e){
System.out.print("Exception");
co
}
a.
Reading and Writing Using Character Streams
iy
Files can be read and written using character streams. The FileReader class used for reading
contents of a file, and the FileWriter is used to write the contents to the file.
un
Example program:FileReadDemo.java
import java.io.*;
class FileReadDemo
sD
{
public static void main(String args[]) throws IOException
{
File f=new File(args[0]);
al
if(f.exists())
{
FileReader fr=new FileReader(f);
ri
int n;
while((n=fr.read())!=-1)
{
to
System.out.print((char)n);
}
}
Tu
Output:
The "Hell.java" contains String contained in the String variable s.
https://www.tutorialsduniya.com
Unit 4: MultiThreading
m
co
a.
iy
un
Reading and Writing Using the Console (Scanner class)
The java.util package contains one particular class called Scanner class, which is used to read
sD
{
public static void main(String args[])
{
ri
int age;
System.out.println("Enter your name:");
name=s.nextLine();
Tu
Unit 5
Applets and Event Handling
Topics:
Applets: Applet class, Applet structure, An example of Applet, Applet life Cycle, Event
m
Delagation Model, Java.awt.event description, Sources of Events, Event Listeners, Adapter class,
inner class
co
Part-1: Applet Programming
Introduction to Applet
a.
Applets are small Java programs that are used in Internet computing. The Applets can be easily
transported over the internet from one computer to another computer and can be run using
iy
"appletviewer" or java enabled "Web Browser". An Applet like any application program can do many
things for us. It can perform arithmetic operations, display graphics, animations, text, accept the user
input and play interactive games.
un
Applets are created in the following situations:
Types of Applet
al
applets use the Abstract Window Toolkit(AWT)for designing the graphical user
interface.
The second type of type of the Applets are based on the Swing class JApplet. The swing
to
Applet Basics
All applets are subclasses (either directly or indirectly) of Applet. Applets are not
stand-alone programs. Instead, they run within either a web browser or an applet viewer,
which is provided by the JDK.
Execution of an applet does not begin at main( ).
Output to your applet’s window is not performed by System.out.println( ). Rather, in
non-Swing applets, output is handled with various AWT methods, such as drawString( ),
which outputs a string to a specified X,Y location
To use an applet, it is specified in an HTMLfile. One way to do this is by using the
APPLET tag.(HTML stands for Hyper Text Markup Language)
https://www.tutorialsduniya.com
Unit 5 : Applets
The applet will be executed by a Java-enabled web browser when it encounters the
APPLET tag within the HTMLfile.
To just test the applet it can be executed using the appletviewer. The applet tag must be
included as comment lines in the java source program as follow:
/*<applet code="applet_name" width=400 height=400 ></applet> */
To view the applet using the HTML file, it can be included in the HTML file with
m
<applet. Tag as follw:
Filename.HTML
<html>
co
<head><title> The name of the Web Page</title>
</head>
<body>
a.
<applet code="applet_name" width=400 height=400 ></applet>
</body>
</html>
iy
Note: Here, the <applet> is the name of the tag, and "code" ,"width" and "height"
are called attributes of the Tag, applet_name, 400, 400 are called values
un
respectively.
The Applet class defines several methods that support for execution of the applets, such
as starting and stopping. It also provides methods to load and display images. It also provides
methods for loading and playing the audio clips. The Applet extends the AWT class Panel. The
al
Panel extends Container class, which in turn extends from the Component.The applet will be
executed by a Java-enabled web browser when it encounters the APPLET tag within the
ri
HTMLfile.
to
Component
Tu
Container
Panel
Applet
JApplet
destroy()
Called by the browser or applet viewer to inform this applet that it is being reclaimed and
that it should destroy any resources that it has allocated.
m
getAppletContext()
Determines this applet's context, which allows the applet to query and affect the
environment in which it runs.
co
getAppletInfo()
Returns information about this applet.
getAudioClip(URL)
a.
Returns the AudioClip object specified by the URL argument.
getAudioClip(URL, String)
Returns the AudioClip object specified by the URL and name arguments.
iy
getCodeBase()
Gets the base URL.
getDocumentBase()
un
Gets the document URL.
getImage(URL)
Returns an Image object that can then be painted on the screen.
getImage(URL, String)
sD
init()
Called by the browser or applet viewer to inform this applet that it has been loaded into
the system.
to
isActive()
Determines if this applet is active.
play(URL)
Tu
start()
Called by the browser or applet viewer to inform this applet that it should start its
execution.
stop()
Called by the browser or applet viewer to inform this applet that it should stop its
execution.
m
Applet Architecture
co
An applet is a window-based program. As such, its architecture is different from the console-
basedprograms. The key concepts are as follow:
First, applets are event driven. An applet waits until an event occurs. The run-
a.
timesystem notifies the applet about an event by calling an event handler that has been
providedby the applet. Once this happens, the applet must take appropriate action and
then quicklyreturn.
iy
Second, the user initiates interaction with an applet. These interactions are sent to the
applet as events to which the applet must respond. For example, when the user clicks the
mouse inside the applet’s window, a mouse-clicked event is generated. If the user presses
un
a key while the applet’s window has input focus, a keypress event is generated
Most of the applets override a set of methods of the Applet. Four of these methods, init( ), start(
), stop( ), and destroy( ), apply to all applets and are defined by Applet. Default
implementations for all of these methods are provided. Applets do not need to override those
methods they do not use.
al
AWT-based applets will also override the paint( ) method, which is defined by the AWT
Component class. This method is called when the applet’s output must be redisplayed. These
ri
// An Applet skeleton.
to
import java.awt.*;
import java.applet.*;
/*
Tu
m
{
// suspends execution
}
co
/* Called when applet is terminated. This is the last
method executed. */
public void destroy()
a.
{
// perform shutdown activities
}
iy
// Called when an applet's window must be restored.
public void paint(Graphics g)
{
un
// redisplay contents of window
}
}
sD
m
co
a.
iy
un
Life Cycle of an Applet
It is important to understand the order in which the various methods shown in the skeletonare
called. When an applet begins, the following methods are called, in this sequence:
sD
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
al
1. stop( )
2. destroy( )
Let’s look more closely
closely at these methods.
i
t or
Tu
init( )
The init( ) method is the first method to be called. This is where you should initialize
variables.This method is called only once during the run time of your applet.
m
start( )
The start( ) method is called after init( ). It is also called to restart an applet after it has
co
beenstopped. Whereas init( ) is called once—the first time an applet is loaded—start( ) is
calledeach time an applet’s HTML document is displayed onscreen. So, if a user leaves a web
pageand comes back, the applet resumes execution at start( ).
a.
paint( )
iy
The paint( ) method is called each time your applet’s output must be redrawn. This situationcan
occur for several reasons. For example, the window in which the applet is running maybe
overwritten by another window and then uncovered. Or the applet window may beminimized and
un
then restored. paint( ) is also called when the applet begins execution.Whatever the cause,
whenever the applet must redraw its output, paint( ) is called. The paint( )method has one
parameter of type Graphics. This parameter will contain the graphics context,which describes
the graphics environment in which the applet is running. This context is usedwhenever output to
sD
stop( )
al
The stop( ) method is called when a web browser leaves the HTML document containing
theapplet—when it goes to another page, for example. When stop( ) is called, the applet
isprobably running. You should use stop( ) to suspend threads that don’t need to run when
ri
theapplet is not visible. You can restart them when start( ) is called if the user returns to the
page.
to
destroy( )
The destroy( ) method is called when the environment determines that your applet needs tobe
Tu
removed completely from memory. At this point, you should free up any resources theapplet
may be using. The stop( ) method is always called before destroy( ).
One of the important architectural constraints that have been imposed on an applet is that it
must quickly return control to the AWT run-time system. It cannot create a loop inside paint( ).
This would prevent control from passing back to the AWT. Whenever your applet needs to
update theinformation displayed in its window, it simply calls repaint( ). The repaint( )
method is defined by the AWT that causes AWT run-time system to execute a call to your
applet's update() method, which in turn calls paint(). The AWT will then execute a call to
TutorialsDuniya.com
Download FREE Computer Science Notes, Programs, Projects,
Books PDF for any university student of BCA, MCA, B.Sc,
B.Tech CSE, M.Sc, M.Tech at https://www.tutorialsduniya.com
paint( ) that will display the stored information. The repaint( ) method has four forms. The
simplest version of repaint( ) is:
1. void repaint ( )
m
This causes the entire window to be repainted. Other versions that will cause repaint
are:
co
2. void repaint(int left, int top, int width, int height)
a.
iy
If your system is slow or busy, update( ) might not be called immediately. If multiple
calls have been made to AWT within a short period of time, then update( ) is not called
un
very frequently. This can be a problem in many situations in which a consistent update
time is necessary. One solution to this problem is to use the following forms of repaint(
):
sD
4. void repaint (long maxDelay, int x, int y, int width, int height)
al
Where "maxDelay" is the number milliseconds should be elapsed before updat() method is
ri
called.
to
In addition to displaying information in its window, an applet can also output a messageto the
Tu
status window of the browser or applet viewer on which it is running. To do so, callshowStatus(
) with the string that you want displayed. The status window is a good placeto give the user
feedback about what is occurring in the applet, suggest options, or possiblyreport some types of
errors. The status window also makes an excellent debugging aid,because it gives you an easy
way to output information about your applet.
Example program
StatusWindow.java
// Using the Status Window.
import java.awt.*;
https://www.tutorialsduniya.com
Unit 5 : Applets
import java.applet.*;
/*
<applet code="StatusWindow" width=500 height=500>
</applet>
*/
public class StatusWindow extends Applet
m
{
Image img;
public void init()
co
{
setBackground(Color.cyan);
//initializing the image object
a.
img=getImage(getCodeBase(),"Life.jpg");
}
iy
public void paint(Graphics g)
{
g.drawString("This is in the applet window.", 10, 20);
un
showStatus("This is shown in the status window.");
g.drawLine(60,60,80,80);
//drawing the image on applet
g.drawImage(img,100,100,200,200,this);
sD
}
}
Running applet:
1. javac StatusWindow.java
al
2. appletviewer StatusWindow.java
Output:
ri
to
Tu
https://www.tutorialsduniya.com
Unit 5 : Applets
o m
a .c
iy
un
Passing parameters to Applet
sD
We can supply user defined parameters to an applet using the <param> Tag of HTML. Each
<param> Tag has the attributes such as "name" , "value" to which actual values are assigned. Using this
tag we can change the text to be displayed through applet. We write the <param> Tag as follow:
al
using command line arguments. To set up and handle parameters, we need to do two things:
Example Program:
Tu
ParaPassing.java
import java.applet.*;
import java.awt.*;
public class ParaPassing extends Applet
{
String str;
public void init()
{
str=getParameter("name1");
if(str==null)
https://www.tutorialsduniya.com
Unit 5 : Applets
str="Java";
str="Hello "+str;
}
public void paint(Graphics g)
{
g.drawString(str,50,50);
m
}
}
co
para.html
<html>
<head><title> Passing Parameters</title></head>
a.
<body bgcolor=pink >
<param name="name1" value="Example Applet for Passing the Parameters" >
<applet code="ParaPassing.class" width=400 height=400 >
iy
</param>
</applet>
</body>
un
</html>
Running the Program:
1. Compile the "ParaPassing.java" using the "javac" command, which generates the
sD
Output:
ri
to
Tu
https://www.tutorialsduniya.com
Unit 5 : Applets
m
Next step is to retrieve the contents from the text fields for display of calculations, if any. The
text fields contain the item in the form of String. They need to be converted to the right form, before
co
they are used in any computations.
Example Program:
a.
import java.applet.*;
import java.awt.*;
public class InputApplet extends Applet
iy
{
TextField text1,text2;
Label l1,l2;
un
public void init()
{
text1=new TextField(8);
l1=new Label("Enter First No");
sD
text2=new TextField(8);
l2=new Label("Enter second No");
add(l1);
add(text1);
al
add(l2);
add(text2);
text1.setText("0");
ri
text2.setText("0");
} public void paint(Graphics g)
{
to
int x=0,y=0,z=0;
String s1,s2,res;
g.drawString("Enter a number in each text box",50,100);
Tu
try
{
s1=text1.getText();
x=Integer.parseInt(s1);
s2=text2.getText();
y=Integer.parseInt(s2);
}
catch(Exception e)
{
}
https://www.tutorialsduniya.com
Unit 5 : Applets
z=x+y;
res=String.valueOf(z);
g.drawString("The Sum is :",50,150);
g.drawString(res,150,150);
}
public boolean action(Event e,Object obj)
m
{
repaint();
return true;
co
}
}
a.
sum.html
iy
<html>
un
<head><title>Geting input from the User </title>
</head>
sD
<body>
</body>
al
</html>
ri
Output:
to
m
co
a.
iy
un
sD
al
ri
There are two types of Event handling mechanisms supported by Java. First, the approach
supported by Java 1.0, where the generated event is given hierarchically to the objects until it
was handled. This can be also called as Hierarchical Event Handling Model.
Second, the approach supported by Java 1.1, which registers the listeners to the source of
the event and the registered listener processes the event and returns response to the source. This
is called "Event Delegation Model"
The modern approach to handling events is based on the delegation event model,
model which
definesstandard and consistent mechanisms to generate and process events (1).. Its concept is
quite simple:a source (2)generates
(2)generates an event and sends it to one or more listeners
listener (3).. In this
scheme, the listenersimply waits until it receives an event. Once an event is received, the listener
processes the eventand then returns response.
response
m
The advantage of this design is that the application logic that processes eventsis cleanly
separated from the user interface logic that generates those events. Auser interfaceelement is
able to “delegate” the processing of an event to a separate piece of code.
co
In the delegation event model, listeners must register with a source in order to receive
anevent notification. This provides an important benefit: notifications are sent only to
a.
eve nts than the design
listenersthat want to receive them. This is a more efficient way to handle events
usedby the old Java 1.0 approach. Previously, an event was propagated up the containment
hierarchyuntil it was handled by a component. This required components to receive events that
iy
they didnot process, and it wasted valuable time. The delegation event model eliminates this
overhead.
un
sD
al
ri
to
1. What is an Event?
In the delegation model, an event is an object that describes a state change in a source. It
can be generated as a consequence of a person interacting with the elements in a graphical user
interface.
Examples: ressing a button, entering a character via the keyboard, selecting an item in a
Example Pressing
list, and clicking the mouse etc..
2. Event Sources
https://www.tutorialsduniya.com
Unit 5 : Applets
Asource is an object that generates an event. This occurs when the internal state of that
object changes in some way. Sources may generate more than one type of event. A source must
register listeners in order for the listeners to receive notifications about a specific type of event.
Each type of event has its own registration method. Here is the general form:
m
Here, Typeis the name of the event, and elis a reference to the event listener. For
example, the method that registers a keyboard event listener is called addKeyListener( ). The
co
method that registers a mouse motion listener is called addMouseMotionListener( ). When an
event occurs, all registered listeners are notified and receive a copy of the event object. This is
known as multicastingthe event. In all cases, notifications are sent only to listeners that register
a.
to receive them.
Some sources may allow only one listener to register. The general form of such a methodis this:
iy
public void addTypeListener(TypeListener el) throws java.util.TooManyListenersException
Here, Typeis the name of the event, and elis a reference to the event listener. When
un
suchan event occurs, the registered listener is notified. This is known as unicastingthe event.A
source must also provide a method that allows a listener to unregister an interestin a specific
type of event. The general form of such a method is this:
sD
Here, Typeis the name of the event, and el is a reference to the event listener. For
example,to remove a keyboard listener, you would call removeKeyListener( ).The methods that
al
add or remove listeners are provided by the source that generatesevents. For example, the
Component class provides methods to add and remove keyboardand mouse event listeners.
ri
3. Event Listeners
Alisteneris an object that is notified when an event occurs. It has two major requirements.
to
First, it must have been registered with one or more sources to receive notifications about
specific types of events.
Tu
The methods that receive and process events are defined in a set of interfaces found
injava.awt.event. For example, the MouseMotionListener interface defines two methods
toreceive notifications when the mouse is dragged or moved.
EventObject class
It is the root class from which all event state objects shall be derived. All Events are constructed
with a reference to the object, the source, that is logically deemed to be the object upon which
the Event in question initially occurred upon. This class is defined in java.util package.
The summary
m
EventObject is a superclass of all events.
AWTEvent is a superclass of all AWT events that are handled by the delegation event
co
model.
The package java.awt.event defines many types of events that are generated by varioususer
interface elements. Table 1 shows several commonly used event classes and providesa brief
a.
description of when they are generated. Commonly used constructors and methods ineach class
are described in the following sections
iy
un
sD
al
ri
to
The ActionEvent class defines 5integer constant and also defines 3 methods.
Methods:
https://www.tutorialsduniya.com
Unit 5 : Applets
m
generated.
iii. long getWhen() -used to get the time when the event took place.
co
2. The AdjustmentEvent Class
a.
Integer Constants:
iy
An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment
events. The AdjustmentEvent class defines integer constants that can be used to identify
them. The constants and their meanings are shown here:
un
sD
al
Methods:
ii. int getAdjustmentType() - the type of adjustment event can be obtained by this
method.
iii. int getValue() -the amount of adjustment can be obtained by this method
to
Method:
https://www.tutorialsduniya.com
Unit 5 : Applets
m
container. There are two types of container events.
Integer Constants:
COMPONENT_ADDED and COMPONENT_REMOVED.
co
The ContainerEvent class defines int constants that can be used to identify them.
Methods:
i. container getContainer() - used to get thereference of the container that has
a.
generated this event
ii. Component getChild() - used to get the component that has been added or
removed.
iy
5. The FocusEvent Class
un
A FocusEvent is generated when a component gains or loses input focus.
Integer Constants:
sD
Methods:
al
For example, assume that the focus is in a text field. If the user moves the mouse to adjust
a scroll bar, the focus is temporarily lost.) The other component involved in the focus change,
called the opposite component, is passed in other.
ri
The abstract class InputEvent is a subclass of ComponentEvent and is the superclass for
component input events. Its subclasses are KeyEvent and MouseEvent.
Integer Constants:
i. boolean isAltDown( ) -
ii. boolean isAltGraphDown( )
iii. boolean isControlDown( )
iv. boolean isMetaDown( )
https://www.tutorialsduniya.com
Unit 5 : Applets
v. boolean isShiftDown( )
Integer Constants:
m
co
Methods:
i. Object getItem( ) –used to get the reference of the item that has generated the event
ii. ItemSelectable getItemSelectable( )- used to get reference to the selectable items.
iii. int getStateChange( )- return the state change for the event.
a.
8. The KeyEvent Class
iy
A KeyEvent is generated when keyboard input occurs. There are three types of
key events, which are identified by these integer constants: KEY_PRESSED,
KEY_RELEASED, and KEY_TYPED. The first two events are generated when any
un
key is pressed or released. The last event occurs only when a character is generated.
Remember, not all keypresses result in characters. For example, pressing SHIFT does not
generate a character.
sD
Integer Constants:
There are many other integer constants that are defined by KeyEvent. For
example, VK_0through VK_9 and VK_A through VK_Z define the ASCII equivalents
al
Methods:
The KeyEvent class defines several methods, but the most commonly used ones are
Tu
getKeyChar( ), which returns the character that was entered, and getKeyCode( ), which returns
the key code. Their general forms are shown here:
char getKeyChar( )
int getKeyCode( )
Integer Constants:
https://www.tutorialsduniya.com
Unit 5 : Applets
m
co
Methods:
Two commonly used methods in this class are getX( ) and getY( ). These return the X
andY coordinates of the mouse within the component when the event occurred. Their forms are
a.
shown here:
iy
i. int getX( ) – used to get the X coordinate
ii. int getY( ) –used to get the Y coordinate
iii. Point getPoint( ) –used to obtain the coordinates of the mouse
iv.
un
getClickCount( ) - method obtains the number of mouse clicks for this event. Its
signature is shown here:
v. isPopupTrigger() - method tests if this event causes a pop-up menu to appear on
thisplatform
sD
Java SE 6 added three methods to MouseEvent that obtain the coordinates of the mouse relative
to the screen rather than the component. They are shown here:
al
Point getLocationOnScreen( )
ri
int getXOnScreen( )
int getYOnScreen( )
to
MouseEvent.Not all mice have wheels. If a mouse has a wheel, it is located between the left and
rightbuttons. Mouse wheels are used for scrolling. MouseWheelEvent defines these two
integerconstants:
Methods:
MouseWheelEvent defines methods that give you access to the wheel event. To obtain the number of
rotational units, call getWheelRotation( ), shown here:
int getWheelRotation( )
https://www.tutorialsduniya.com
Unit 5 : Applets
It returns the number of rotational units. If the value is positive, the wheel moved counterclockwise. If the value
is negative, the wheel moved clockwise. To obtain the type of scroll, call getScrollType( ), shown next:
int getScrollType( )
m
shown here:
int getScrollAmount( )
co
11. The TextEvent Class
Instances of this class describe text events. These are generated by text fields and text areaswhen
a.
characters are entered by a user or program.
TextEvent defines the integer constant:
iy
TEXT_VALUE_CHANGED.
The one constructor for this class is shown here:
un
TextEvent(Object src, int type)
Here, src is a reference to the object that generated this event. The type of the event isspecified
by type.
sD
There are ten types of window events. TheWindowEvent class defines integer constants that
al
can be used to identify them. The constants and their meanings are shown here:
ri
Integer Constants:
to
Tu
Methods:
Acommonly used method in this class is getWindow( ). It returns the Window object that generated the event.
Its general form is shown here:
Window getWindow( )
https://www.tutorialsduniya.com
Unit 5 : Applets
WindowEvent also defines methods that return the opposite window (when a focus or activation event has
occurred), the previous window state, and the current window state. These methods are shown here:
Window getOppositeWindow( )
int getOldState( )
int getNewState( )
m
Event Sources
The following are the event source classes, that actually generate the event.
co
a.
iy
un
sD
package.When an event occurs, the event source invokes the appropriate method defined by
thelistener and provides an event object as its argument.
ri
to
Tu
https://www.tutorialsduniya.com
Unit 5 : Applets
m
co
a.
iy
un
sD
This interface defines the actionPerformed( ) method that is invoked when an action event
occurs. Its general form is shown here:
al
This interface defines four methods that are invoked when a component is resized,
moved,shown, or hidden. Their general forms are shown here:
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
m
void componentRemoved(ContainerEvent ce)
co
This interface defines two methods. When a component obtains keyboard focus, focusGained( )
is invoked. When a component loses keyboard focus, focusLost( ) is called. Their general
a.
forms are shown here:
iy
void focusLost(FocusEvent fe)
This interface defines three methods. The keyPressed( ) and keyReleased( ) methods
areinvoked when a key is pressed and released, respectively. The keyTyped( ) method is
invokedwhen a character has been entered.For example, if a user presses and releases the A key,
ri
three events are generated in sequence:key pressed, typed, and released. If a user presses and
releases the HOME key, two key eventsare generated in sequence: key pressed and released.
to
This interface defines five methods. If the mouse is pressed and released at the same
point,mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered(
)method is called. When it leaves, mouseExited( ) is called. The mousePressed( )
andmouseReleased( ) methods are invoked when the mouse is pressed and released,
respectively.
https://www.tutorialsduniya.com
Unit 5 : Applets
m
void mouseReleased(MouseEvent me)
co
This interface defines two methods. The mouseDragged( ) method is called multiple timesas the
mouse is dragged. The mouseMoved( ) method is called multiple times as the mouseis moved.
Their general forms are shown here:
a.
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
iy
The MouseWheelListener Interface
This interface defines the mouseWheelMoved( ) method that is invoked when the mousewheel
un
is moved. Its general form is shown here:
This interface defines the textChanged( ) method that is invoked when a change occurs
in a text area or text field. Its general form is shown here:
al
are called when a window gains or loses input focus. Their general forms are shown here:
m
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
co
void windowOpened(WindowEvent we)
a.
Using the Delegation Model for Handling the Mouse Events
iy
To handle mouse events, you must implement the MouseListener and the
MouseMotionListenerinterfaces. It displays the current coordinatesof the mouse in the applet’s
status window. Each time a button is pressed, the word “Down”is displayed at the location of the
un
mouse pointer. Each time the button is released, the word“Up” is shown. If a button is clicked,
the message “Mouse clicked” is displayed in the upperleftcorner of the applet display area
As the mouse enters or exits the applet window, a message is displayed in the upper-
sD
leftcorner of the applet display area. When dragging the mouse, a * is shown, which tracks
withthe mouse pointer as it is dragged. Notice that the two variables, mouseX and mouseY,
storethe location of the mouse when a mouse pressed, released, or dragged event occurs.
Thesecoordinates are then used by paint( ) to display output at the point of these occurrences.
al
ri
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
Tu
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet
implements MouseListener, MouseMotionListener
{
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init()
{
addMouseListener(this);
https://www.tutorialsduniya.com
Unit 5 : Applets
addMouseMotionListener(this);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{
// save coordinates
m
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
co
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me)
a.
{
// save coordinates
iy
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
un
}
// Handle mouse exited.
public void mouseExited(MouseEvent me)
sD
{
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
al
repaint();
}
// Handle button pressed.
ri
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
Tu
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me)
{
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
https://www.tutorialsduniya.com
Unit 5 : Applets
m
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
co
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me)
{
a.
// show status
showStatus("Moving mouse at " + me.getX() + ", " +
iy
me.getY());
}
// Display msg in applet window at current X,Y location.
un
public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
sD
OutPut:
al
ri
to
Tu
https://www.tutorialsduniya.com
Unit 5 : Applets
Adapter Classes
Java provides a special feature, called an adapter class, that can simplify the creation of
eventhandlers in certain situations. An adapter class provides an empty implementation of
allmethods in an event listener interface. Adapter classes are useful when you want to receiveand
m
process only some of the events that are handled by a particular event listener interface.You can
define a new class to act as an event listener by extending one of the adapter classesand
implementing only those events in which you are interested.
co
For example, the MouseMotionAdapter class has two methods, mouseDragged( )and
mouseMoved( ), which are the methods defined by the MouseMotionListenerinterface. If you
a.
were interested in only mouse drag events, then you could simply extendMouseMotionAdapter
and override mouseDragged( ). The empty implementation ofmouseMoved( ) would handle the
mouse motion events for you.
iy
The Following table provide the commonly used adapter classes:
un
sD
al
ri
to
// Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet
{
public void init()
{
https://www.tutorialsduniya.com
Unit 5 : Applets
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter
{
m
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo)
{
co
this.adapterDemo = adapterDemo;
}
// Handle mouse clicked.
a.
public void mouseClicked(MouseEvent me)
{
adapterDemo.showStatus("Mouse clicked");
iy
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter
un
{
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo)
{
sD
this.adapterDemo = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me)
al
{
adapterDemo.showStatus("Mouse dragged");
}
ri
Inner Classes
to
An inner class is a class defined within another class, or even within an expression.
Tu
Example program:
{
https://www.tutorialsduniya.com
Unit 5 : Applets
m
//inner class
class MyMouseAdapter extends MouseAdapter
{
co
//overriding the mousePressed() method
public void mousePressed(MouseEvent me)
{
showStatus("Mouse Pressed");
a.
}
}
}
OutPut:
iy
un
sD
al
ri
to
Tu