0% found this document useful (0 votes)
4 views99 pages

Java Notes1

Uploaded by

venus 814
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views99 pages

Java Notes1

Uploaded by

venus 814
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES

TABLE OF CONTENTS

Features of Java Nested if statement


Java Environment if..elseif Ladder
Introduction to Java Switch Statement
Types of Java Program do..while Statement
Creating and Executing Java Program for loop
Character set Nested for loops
Identifiers One-dimensional Arrays
Literals Syntax 2: Allocating Memory to Arrays
Separators Multi-Dimensional Arrays
Command line Arguments Vectors
Comments in Java Creating Vectors
Lexical Structure of a Java Program Wrapper Classes
Java Elements String Class
Java Constants String Class Methods
Java Variables String Arrays
Java Datatypes String Buffer Class
Scope of Variables Classes and Objects
Type Casting Defining a class
Java Operators Accessing class members
Arithmetic Operators Constructors
Bitwise Operators Method Overloading
Conditional Operator Inheritance
Increment and Decrement Operators Method Overriding
Logical Operators Packages
Relational Operator The Java System Package
instanceof Operator Java API Packages
Java Expressions MULTITHREADING
Evaluation of Expressions Applets
Decision Making Statements Exception Handling
if Statement I/O Streams
if..else Statement Files

1
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
PROGRAMMING IN JAVA NOTES

Java

Java is a programming language expressly designed for use in the distributed environment of the
Internet.
It was designed to have the "look and feel" of the C++ language, but it is simpler to use than C++
and enforces an object-oriented programming model.
Java can be used to create complete applications that may run on a single computer or be
distributed among servers and clients in a network.
It can also be used to build a small application module or applet for use as part of a Web page.
Applets make it possible for a Web page user to interact with the page

History of Java

The Birth of JAVA - as a technology for Set Top Boxes!

• The Java platform and language began as an internal project at Sun Microsystems in December
1990, providing an alternative to the C++/C programming languages. Engineer Patrick
Naughton, James Gosling and Mike Sheridan were attempting to develop a new technology for
programming next generation smart appliances (like set-top boxes!), which Sun expected to be
a major new opportunity. It was called the Green project.

James Gosling -Father of Java

The team originally considered using C++, but it was rejected for several reasons as follows:

• Because they were developing an embedded system with limited resources, they decided that
C++ demanded too large a footprint and that its complexity led to developer errors.
• C/C++ does not have garbage collection. This means that programmers have to manually manage
system memory - a difficult and error-prone task.
• C/C++ also suffered from lack of portable facilities for security, distributed programming, and
threading.
• Finally, they wanted a platform that could be easily ported to all types of devices.

Initially, Gosling attempted to modify and extend C++ but soon abandoned that in favor of creating an
entirely new language, which he called Oak, after the tree that stood just outside his office.

By the September of 1992, they were able to demonstrate portions of the new platform including the
Green OS, the Oak language, the libraries, and the hardware.

Java was initially developed to write software for consumer electronic products like television, ovens
etc. Later with the development of Internet and World Wide Web there was a need for a programming
language that is platform independent, So Java gained popularity and became one of most popular
language for Internet programming.

Java meets Internet

• In June and July 1994, John Gage, the Director of Science for Sun, Gosling, Joy, Naughton, Wayne
Rosing, and Eric Schmidt (the now CEO of Google) re-targeted the platform for the World Wide
Web. With the arrival of the first graphical web browser, Mosaic, they felt the Internet was on

2
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
its way to evolving into a powerful, highly interactive medium. As a prototype, Naughton wrote
a small browser, WebRunner, later renamed HotJava.
• That year, the language was renamed Java after a trademark search revealed that Oak was used
by another company. The first public release of Java and the HotJava browser was on 23 May
1995. Netscape browsers started to include Java support. On 9 January 1996, the JavaSoft group
was formed by Sun Microsystems in order to develop the technology.

Major Java Versions

• JDK (Java Development Kit) 1.0 was released on (January 23, 1996),JDK 1.1 was released on
February 19, 1997. Major alterations were on the AWT event model, inner classes, JavaBeans and
JDBC were added to the language.
• J2SE 1.2 (December 8, 1998) — This and subsequent releases were rebranded Java 2. The
version name "J2SE" (Java 2 Platform, Standard Edition) was used instead of JDK. J2EE (Java 2
Platform, Enterprise Edition) and J2ME (Java 2 Platform, Micro Edition) were available. Major
additions included reflection, a Collections framework and the integration of the Swing graphical
API into the core classes. Sun's JVM was equipped with a JIT compiler for the first time.
• J2SE 1.3 (May 8, 2000) - Notable changes included the bundling of the HotSpot JVM, Java Sound,
Java Naming and Directory Interface (JNDI) and Java Platform Debugger Architecture (JPDA).
• J2SE 1.4 (February 6, 2002) — regular expressions modeled after Perl, exception chaining, an
integrated XML parser and XSLT processor (JAXP), and Java Web Start.
• J2SE 5.0 (September 30, 2004) — Internal version numbered 1.5. A number of significant new
language features include the for-each loop, generics, autoboxing and var-args.
• The current version, Java SE 6 (December 11, 2006) — is bundled with a database manager,
facilitates the use of scripting languages (currently JavaScript) with the JVM and has Visual Basic
language support.
• As of this version, Sun replaced the name "J2SE" with Java SE and dropped the ".0" from the
version number 6.0. Lots of GUI improvements including native UI enhancements to support the
look and feel of Windows Vista and improvements to the Java Platform Debugger Architecture
(JPDA) & JVM Tool Interface for better debugging were new features.
• Java SE 7— Codename Dolphin is in the early planning stages.

Features of Java

Write Once, RunAny Where

The main feature of java is its platform independent, Java developers have identified the
following as the features of their language

• Simple, Small and familiar


• Compiled and interpreted
• Platform independent and portable
• Pure Object-oriented
• Distributed

3
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
• Robust
• Secure
• High Performance
• Multithreaded and Interactive
• Dynamic and Extensible

Platform Independent:

• The concept of Write-once-run-anywhere (known as the Platform independent) is one of


the important key features of java language that makes java as the most powerful language. Not
even a single language is idle to this feature but java is more closer to this feature.
• The programs written on one platform can run on any platform provided the platform must have
the JVM.

Simple, Small and Familiar:

• There are various features that makes the java as a simple language. Programs are easy to write
and debug because java does not use the pointers explicitly.
• It is much harder to write the java programs that can crash the system but we cannot say about
the other programming languages.
• Java provides the bug free system due to the strong memory management. It also has the
automatic memory allocation and deallocation system.

Object Oriented:

To be an Object-Oriented language, any language must follow at least the four characteristics.

Inheritance

It is the process of creating the new classes and using the behavior of the existing classes
by extending them just to reuse the existing code and adding the additional features as needed.

Encapsulation

It is the mechanism of combining the information and providing the abstraction.

Polymorphism

As the name suggest one name multiple form, Polymorphism is the way of providing the
different functionality by the functions having the same name based on the signatures of the methods.

Dynamic binding

Sometimes we don't have the knowledge of objects about their specific types while writing our
code. It is the way of providing the maximum functionality to a program about the specific type at
runtime.
4
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
• As the languages like Objective C, C++ fulfills the above four characteristics yet they are not fully
object-oriented languages because they are structured as well as object-oriented languages.

• But in case of java, it is a fully Object-Oriented language because object is at the outer most level
of data structure in java. No standalone methods, constants, and variables are there in java.
Everything in java is object even the primitive data types can also be converted into object by
using the wrapper class.

Robust:

• Java has the strong memory allocation and automatic garbage collection mechanism. It provides
the powerful exception handling and type checking mechanism as compare to other
programming languages.
• Compiler checks the program whether there any error and interpreter checks any run time error
and makes the system secure from crash. All of the above features makes the java language
robust.

Distributed:

• The widely used protocols like HTTP and FTP are developed in java. Internet programmers can
call functions on these protocols and can get access the files from any remote machine on the
internet rather than writing codes on their local system.

Portable:

• The feature Write-once-run-anywhere makes the java language portable provided that the
system must have interpreter for the JVM.
• Java also have the standard data size irrespective of operating system or the processor. These
features makes the java as a portable language.

Dynamic:

• While executing the java program the user can get the required files dynamically from a local
drive or from a computer thousands of miles away from the user just by connecting with the
Internet.

Secure:

• Java does not use memory pointers explicitly. All the programs in java are run under an area
known as the sand box. Security manager determines the accessibility options of a class like
reading and writing a file to the local disk.
• Java uses the public key encryption system to allow the java applications to transmit over the
internet in the secure encrypted form. The bytecode Verifier checks the classes after loading.

Performance:

• Java uses native code usage, and lightweight process called threads. In the beginning
interpretation of bytecode resulted the performance slow but the advance version of JVM uses
the adaptive and just in time compilation technique that improves the performance.

5
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Multithreaded:
• As we all know several features of Java like Secure, Robust, Portable, dynamic etc; you will be
more delighted to know another feature of Java which is Multithreaded.
• Java is also a Multithreaded programming language. Multithreading means a single program
having different threads executing independently at the same time.
• Multiple threads execute instructions according to the program code in a process or a program.
Multithreading works the similar way as multiple processes run on one computer.
• Multithreading programming is a very interesting concept in Java. In multithreaded programs
not even a single thread disturbs the execution of other thread.
• Threads are obtained from the pool of available ready to run threads and they run on the system
CPUs. This is how Multithreading works in Java which you will soon come to know in details in
later chapters.

Interpreted:

• We all know that Java is an interpreted language as well. With an interpreted language such as
Java, programs run directly from the source code.
• The interpreter program reads the source code and translates it on the fly into computations.
Thus, Java as an interpreted language depends on an interpreter program.
• The versatility of being platform independent makes Java to outshine from other languages. The
source code to be written and distributed is platform independent.
Java Environment
JDK contains tools that are required to build and execute Java applications and applets. JDK can
be freely downloaded from the sun's website.
• javac _Java Compiler
The Java source code will be compiled by this compiler, which checks for the syntax of the program
and will list out errors if any, or will generate the byte code. The Java compiler generate the .class
file (byte code).
• java –Java interpreter
Java interpreter reads the .class file of the application programs that contains the byte code and
executes the code in a local machine.
• appletviewer
The applet viewer runs the Java applets
• javadoc_ Java Documentation
Document generator that can be used to create documents for large source codes.
• javah_ C header
Produces header files that are used for writing native methods.
• javap_ Disassembler
Helps to convert byte code into program description.
• jdb-Debugger
Helps to find errors in our program.

6
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
API
What is Java API?
Java API is not but a set of classes and interfaces that comes with the JDK. Java API is actually a huge
collection of library routines that performs basic programming tasks such as looping, displaying GUI form etc.
In the Java API classes and interfaces are packaged in packages. All these classes are written in Java
programming language and runs on the JVM. Java classes are platform independent but JVM is not platform
independent. You will find different downloads for each OS.

Introduction to Java

Java is an object-oriented, cross platform, multi-purpose programming language developed by


James Gosling, Patrick Naughton and their team members at Sun Microsystems.
Initially called Oak and renamed ‘Java’ in 1995, it has earned a prominent place in the
world of computer programming.

Duke - The Java Mascot

It was developed to be a machine independent web technology. It was based on C and


C++ syntax to make it easy for programmers from those communities to learn. But a
number of features of C and C++ that were considered as sources of problems were
removed.

Java has many characteristics that have contributed to its popularity:

• Platform independence - If a program is compiled in Java, it can run on any operating system
in the world without any modification or recompilation at all. The only restriction is that the
operating systems must have a Java Virtual Machine available and installed.
• Simple and easy to use - Java was designed from ground up to be object oriented and hence
code could be written efficiently and easily.
• Multi-functional - Java can produce many applications from command-line programs to applets
to Swing based GUI applications.

The Java platform does have some drawbacks too.

• As java does automate garbage collection, java programs can require more memory than other
similar languages.
• There are often implementation differences in the Java VM on different platforms. This means
that code written and developed on one platform may not run exactly on another platform. This
led to Java programs needing to be tested on multiple platforms.
• Since java programs run on an abstract "virtual machine", the Java program doesn't have access
to the operating system's APIs directly.
Types of Java Program
There are two types of Java programs
1. Application Programs
2. Applet Programs

Application Programs

7
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Application programs are stand-alone programs that are written to carry out certain tasks on local
computer such as solving equations, reading and writing files etc.
The application programs can be executed using two steps

1. Compile source code to generate Byte code using Javac compiler.


2. Execute the byte code program using Java interpreter.

Applet programs:

Applets are small Java programs developed for Internet applications. An applet located in distant
computer can be downloaded via Internet and executed on a local computer using Java capable
browser. The Java applets can also be executed in the command line using appletviewer, which is
part of the JDK

Creating and Executing Java Program


Your first application, will simply display the greeting message. To create this program, you will:
• Create a source file
A source file contains code, written in the Java programming language, that you and other
programmers can understand. You can use any text editor to create and edit source file
• Compile the source file into a .class file
The Java programming language compiler (javac) takes your source file and translates its text into
instructions that the Java virtual machine can understand. The instructions contained within this
file are known as bytecodes.

Run the program

The Java application launcher tool (java) uses the Java virtual machine to run your application.

Creating the Source File:

First, start your editor.

• You can launch the Notepad editor from the Start menu by selecting Programs > Accessories
> Notepad.
• In a new document, type in the following code:

/* My first java Program */


class Sample
{
public static void main(String[] args)
{
[Link]("Welcome to Sir Thegaraya College"); // Display the string.
}
}

• Save the code in file [Link] and note the file name and the class name should be same.

Compile the source File into a .class File

8
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
• Bring up a "command," window.
• You can do this from the Start menu by choosing Command Prompt (Windows XP), or by
choosing Run... and then entering cmd.
• The prompt shows your current directory. When you bring up the prompt, your current
directory is usually your home directory for Windows XP (as shown in the preceding figure).
• To compile your source file, change your current directory to the directory where your file is
located. For example, if your source directory is java on the C drive, type the following command
at the prompt and press Enter:

Cd\

• Now the prompt should change to C:\>


• If you enter dir at the prompt, you should see your source file.
• Then set path to the directory where your JDK is located by using path command (For example
if JDK is present in C:)

set path=C:\jdk1.3\bin

• Now you are ready to compile. At the prompt, type the following command and press Enter.

javac [Link]

• The compiler has generated a bytecode file, [Link].


• Now that you have a .class file, you can run your program.

Run the Program

• In the same directory, enter the following command at the prompt:

java Sample

The program prints Welcome to Sir Thegaraya College to the screen.

The following figure illustrates the above steps

9
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Java Tokens:

The Smallest individual units in a program are called tokens. Java language includes five types of tokens

• Reserved words
• Identifiers
• Literals
• Operators
• Separators

Keywords:

• Keywords are reserved words and have predefined meaning.


• The keywords cannot be used as identifiers.
• There are 50 keywords in java.
• All the keywords are written in lowercase.

The following table lists the java keyword

Abstract continue For New switch


assert*** default goto* Package synchronized
Boolean do If Private this
Break double Implements Protected throw
Byte else Import Public throws
Case enum**** Instanceof Return transient
Catch extends Int Short try
Char final Interface Static void
Class finally Long strictfp** volatile
const* float Native Super while

Where *----------- Not used

**---------Added in 1.2

***-------Added in 1.4

****-----Added in 5.0

Character set

Character set defines the characters that are used in a programming languages

• Java uses unicode character set.

• Unicode is a 16-bit character set designed to cover all the world's major living languages, in
addition to scientific symbols and dead languages that are the subject of scholarly interest.
• The first 256 values are the same as the ASCII character set.
10
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Identifiers

Identifiers are names we give to our variables, constants, classes, and methods.
Identifiers must satisfy the following rules:

• The first character of an identifier must be a letter, an underscore(_), or a dollar sign($).


• The rest of the characters in the identifier can be a letter, underscore, dollar sign, or digit. Note
that spaces are NOT allowed in identifiers.
• Identifiers are case-sensitive. This means that age and Age are different identifiers.
• Identifiers cannot match any of Java's reserved words.

Examples:
These identifiers are valid:

MyClass
$amount
totalGrades;
TotalGrades;
TAX_RATE
one

These identifiers are NOT valid:

My Class // spaces are not allowed


numberOf*s // the asterisk cannot be used
final // final is a reserved word
1Way // identifiers cannot start with a digit

Literals

A constant value in a program is denoted by a literal. Literals represent numerical (integer or floating-
point), character, boolean or string values.

Example of literals:
Integer literals: 33 0 -9
Floating-point literals: .3 0.3 3.14
Character literals: '(' 'R' 'r' '{'
Boolean literals: (predefined values)true false
String literals: "language" "0.2" "r" ""

Note: Three reserved identifiers are used as predefined literals:


true and false representing boolean values.
null representing the null reference.

11
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Separators

Separators help define the structure of a program.

The table lists the six Java separators .

Encloses arguments in method definitions and calling; adjusts precedence in arithmetic


()
expressions; surrounds cast types and delimits test expressions in flow control statements
{} defines blocks of code and automatically initializes arrays
[] declares array types and dereferences array values
; terminates statements
separates successive identifiers in variable declarations; chains statements in the test, expression
,
of a for loop
Selects a field or method from an object; separates package names from sub-package and class
.
names
: Used after loop labels

Command line Arguments

• Any number of arguments can be passed to the java program through command line.
• While running the program any things written after the name of the class are the command line
arguments.
• If more than one argument is present they are separated by spaces.

The Syntax for giving command line arguments

java filename arg1 arg2 arg3 ..........

The arguments passed from the command line are stored in the String array parameter of the main
method which can be referred inside our main method using the array name and the index.

Example:

/* Command line arguments */


class cmdline
{
public static void main(String args[])
{
[Link]("The first argument : "+args[0]);
[Link]("The second argument: "+args[1]);
}
}

Output:
D:\java>javac [Link]
D:\java>java cmdline Java Programming
The first argument : Java
The second argument: Programming

12
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Comments in Java

• Comments are non-executable statements and are ignored by the Java compiler.
• The comments increases the readability of the programs.

There are three types of comments used in Java. They are

1. // text -Single Line Comment


The line starting from slashes to the end is considered as a comment.

For example

// Program to find the area of triangle.

2. /* text */ - Multiline Comment


To add a comment of more than one line, we can use this comment. Everything in between these two
delimiters is discarded by the Java compiler.

Forexample

/* Program to find the sum of two numbers

Use two command line arguments to run the program */

3. /** documentation */
This is a special type of comment that indicates documentation comment. This type of comment is
readable to both, computer and human. The JDK javadoc tool uses doc comments when preparing
automatically generated [Link] instance

/**
* These are used to extract documentation from the Java source.

Lexical Structure of a Java Program

Lexical Structure of a Java Program

The lexical structure of a programming language is the set of elementary rules that define what are
the tokens or basic atoms of the program. It is the lowest level syntax of a language and specifies what
is punctuation, reserved words, identifiers, constants and operators. Some of the basic rules for Java
are:

• Java is case sensitive.


• Whitespace, tabs, and newline characters are ignored except when part of string constants. They
can be added as needed for readability.
• Single line comments begin with //
• Multiline comments begin with /* and end with */
• Documentary comments begin with /** and end with **/
• Statements terminate in semicolons! Make sure to always terminate statements with a
semicolon.
• Commas are used to separate words in a list

13
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
• Round brackets are used for operator precedence and argument lists.
• Square brackets are used for arrays and square bracket notation.
• Curly or brace brackets are used for blocks.
• Keywords are reserved words that have special meanings within the language syntax.
• Identifiers are names for constants, variables, functions, properties, methods and objects. The
first character must be a letter, underscore or dollar sign. Following characters can also include
digits. Letters are A to Z, a to z, and Unicode characters above hex 00C0. Java styling uses initial
capital letter on object identifiers, uppercase for constant ids and lowercase for property,
method and variable ids.

Note: an identifier must NOT be any word on the Java Reserved Word List.

Java Elements

▪ Java Constants
▪ Java Variables
▪ Java Data types
▪ Scope of Variables
▪ Type Casting
▪ Java Operators
▪ Java Operators
▪ Arithmetic Operators
▪ Bitwise Operators
▪ Conditional Operator
▪ Increment and Decrement Operators
▪ Logical Operators
▪ Relational Operator
▪ instance of Operator
▪ Java Expressions
▪ Evaluation of Expressions

Java Constants

Constant in Java refer to fixed values that do not change during the execution of the program. Java
supports several types of constants. They are

1) Integer constant

Integer constant refers to sequence of numbers without decimal point. There are three types of
integer constants
Decimal integers: They consist of combination digits 0 through 9 with or without negative sign.
Example:
105 -245 0
Octal integer: They consist of combination of digits 0 through 7 with leading zero.
Example:
074 0 034
Hexadecimal integer: They consist of combination of digits 0 through 9 and letter a through f or
A through F with leading 0x or 0X.
Example:
0X7A4 0Xa 0xA4

14
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
2) Real constants

Real constant refers to sequence of numbers with decimal point. They can be represented in two
forms decimal notation and exponential notation
Decimal notation : The deciaml notation has three parts the integer part, the decimal point and
the fractional part and can be used to represent sinle precision numbers.

Example:
2.15 -7.8 0.78
Exponential notation: The exponential notation is used to represent double precision numbers
and has the following syntax

mantissa e/E Exponent


The mantissa is either a real number expressed in decimal notaion or an integer. The exponent
is an integer withan optional + or - sign. e2 means 102.

Example:

0.97e4 12e-2 -1.2E-4

3) Character constant

A single character enclosed within single quotes is called character constant.


Example:
‘5’ ‘E’ ‘$’

4) String Constants:

A sequence of characters enclosed within double quotes is called string constant.


Example:
“Hai” “Java programming” “1998”

5) Back slash character constant

They are special character constants that are used in output methods.
Example:
‘\b’ - Back space
‘\t’ -Horizontal tab
‘\n’ -New line
‘\r’ -Carriage return
These constants are also known as escape sequences.

Java Variables

A variable is a name given to storage location in memory.


A variable's value can change, depending on conditions or on information passed to the program.

The syntax for declaring a variable is:

datatype var1, var2, var3......;

15
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Where:

• datatype can be one of the primitive datatypes


• var1,var2........ are valid java identifiers

Important points:

1. A variable has to be declared before being used.

2. The values assigned to a variable correspond to its type. Statements below represent
assignment of values to a variable.

1. x = 100; // x is an integer variable.


2. y = 'A'; // y is a character variable.
3. abc = 10.45; // abc is of type double (real numbers).

3. Both variable declaration and assignment of values can be done in same statement. For example,

int x;
x = 100; is same as int x = 100;

4. A variable is declared only once.

int x; // Declaration for x.


x = 100; // Initialization.
x = x + 12; // Using x in an assignment statement.

Java Datatypes

The Java programming language is strongly-typed, which means that all variables must first be
declared before they can be used. A variable's data type determines the values it may contain, plus the
operations that may be performed on it. Java has two groups of data types

• Primitive data types


• Reference data types

Java Primitive Data Types

Data Type Purpose Contents Default Value*


boolean Truth value true or false Fales
char Character Unicode characters \u0000
byte Signed integer 8 bit two's complement (byte) 0
short Signed integer 16 bit two's complement (short) 0
int Signed integer 32 bit two's complement 0
long Signed integer 64 bit two's complement 0L
float Real number 32 bit IEEE 754 floating point 0.0f
double Real number 64 bit IEEE 754 floating point 0.0d

One way to remember the Java primitive data types is by using this mnemonic aid: BeCareful, Bears
Shouldn't Ingest Large Furry Dogs.
16
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Java Reference Data Types

• In Java a reference data type is a variable that can contain the reference or an address of
dynamically created object.
• These type of data type are not predefined like primitive data type.
The reference data types are:

1. Arrays

2. Classes

3. Interfaces

The following figure illustrates the java datatypes

Scope of Variables

What is the scope of a Java variable?

The scope of a Java variable is defined by the block of code within which the variable is accessible.

The scope also determines when the variable is created (memory set aside to contain the data stored
in the variable) and when it possibly becomes a candidate for destruction (memory returned to the
operating system for recycling and re-use).

Scope categories

The scope of a variable places it in one of the following four categories:

• member variable
• local variable
• method parameter
• exception handler parameter

17
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Member variable

A member variable is a member of a class (class variable) or a member of an object instantiated


from that class (instance variable). It must be declared within a class, but not within the body of a
method of the class.

Local variable

A local variable is a variable declared within the body of a method or within a block of code
contained within the body of a method.

Method parameters

Method parameters are the formal arguments of a method. (A method is a function defined inside
of a class.) Method parameters are used to pass values into and out of methods. The scope of a
method parameter is the entire method for which it is a parameter.

Exception handler parameters

Exception handler parameters are arguments to exception handlers.

Type Casting

The process of converting one data type to another is called Type Casting. There are two types of
casting in Java. They are

• Implicit casting
• Explicit casting.

Implicit Casting:

Implicit casting is the process of simply assigning one entity to another without any
transformation guidance to the compiler. This type of casting is not permitted in all kinds of
transformations and may not work for all scenarios.

Example

int i = 1000;

long j = i; //Implicit casting

Implicit conversion of primitive types may occur in these contexts:

* Assignment
* Method call
* Arithmetic promotion
* Assignment

18
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Explicit Casting:
Explicit casting in the process in which the complier are specifically informed to about
transforming the object. The synatx for explicit conversion is

(datatype) variable/ Expression


Example
long i = 700.20;
int j = (int) i; //Explicit casting
Note:
A boolean may not be converted to any other type.
Java Operators
Operators are special symbols that perform specific operations on one, two, or three operands,
and then return a result.
Operands
An operands are the values on which the operators act upon.
An operand can be:
A numeric variable - integer, floating point or character
Any primitive type variable - numeric and boolean
Reference variable to an object
A literal - numeric value, boolean value, or string.
An array element, "a[2]"
char primitive, which in numeric operations is treated as an unsigned two byte integer

Types of Operators:
The operators can be classified into three types based on the Number of operands
1. Unary if it acts on a single operand (Eg : ++, --)
2. Binary if it requires two operands. (Eg: +, * )
3. Ternary if it requires three operands. The conditional operator is the only ternary
operator in Java.
The operators can be classified into the following categories based on the operations they
perform
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Bitwise Operators
5. Assignment Operators
6. Conditional Operators
7. Special Operators
19
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Arithmetic Operators

Java's arithmetic operators are used for performing basic arithmetic operations on numerals and
characters. The following table lists arithmetic operators

Operator Name Example Result Description


Adds the two operands( Can also be used for String
a+b Addition 3+5 8
Concatenation)
a-b Subtraction 3-5 -2 Subtracts the second operand from the first Operand.
a*b Multiplication 3 *5 15 Multiplie both the operands.
a/b Division 15 /3 5 Divides the first operand by the second.
Modulo Returns the remainder after dividing the first number
a%b 3%2 1
Division by the second

Bitwise Operators

Java's bitwise operators operate on individual bits of integer (int and long) values. If an operand is
shorter than an int, it is promoted to int before doing the operations.

It helps to know how integers are represented in binary. For example the decimal number 3 is
represented as 11 in binary and the decimal number 5 is represented as 101 in binary. Negative integers
are store in two's complement form. For example, -4 is 1111 1111 1111 1111 1111 1111 1111 1100.
The following table lists bitwise operators

Operator Name Example Result Description

a& b and 3&5 1 1 if both bits are 1.

a|b or 3|5 7 1 if either bit is 1.

a^b xor 3^5 6 1 if both bits are different.

~a not ~3 -4 Inverts the bits.

left Shifts the bits of n left p positions. Zero bits are shifted into the
n<<p 3 <<< 2 12
shift low-order positions.
Shifts the bits of n right p positions. If n is a 2's complement
right
n>>p 5 >> 2 1 signed number, the sign bit is shifted into the high-order
shift
positions.
right Shifts the bits of n right p positions. Zeros are shifted into the
n>>>p -4 >>> 28 15
shift high-order
Conditional Operator
Java supports another conditional operator that is known as the ternary operator"?:&quot;
It is basically used as an short hand for simple if..else

boolean expression ? operand1 : operand2;

20
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
The "?:&quot; operator evaluates an expression which may also be an operand and returns operand1 if
the expression is true; otherwise returns oprand2, if the expression is false. We can understand this
thing with the help of a diagram shown as:

Example:

int a=14, b=20;

int x= (a>b) ? a : b;

In the above example the value of x is assigned the value of b since the
condition is false.

Increment and Decrement Operators

The ++ and the – are java’s increment and decrement [Link] increment operator increases
its operand by one. The decrement operator decreases its operand by one.

For example, this statement: x = x + 1 can be rewritten like this by use for the increment operator
x++;Similarly, this statement x = x –1 is equivalent to x--;

Increment and decrement operators can be applied to all integers and floating point [Link]
operators are unique in that they can appear both in postfix form (x--, x++) and prefix form (--x, ++x),
where they precede the operand.

In postfix form, the previous value is obtained for use in the expression, and then the operand is
modified. For example:

x = 42;

y = ++x;

In this case, y is set to 43 as you would expect, because the increment occurs before x is assigned
to y. thus, the line y=++x; is the equivalent of these two statements:

x = 42;

y = x++;

The value of x is obtained before the increment operator is executed, so the value of y is 42. Of
course, in both cases x is set to 43. Here, the line y = x++; is the equivalent of these two statements:

y =x;

x = x + 1;

Example:

/* Demo increment and decrement operator */


class InDec

21
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
{
public static void main (String args[])
{
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
[Link](“a = “ + a);
[Link](“b= “ + b);
[Link](“c = “ + c);
[Link](“d = “ + d);
}
}

Logical Operators

Relational operators enable you to compare two variables to determine whether they are equal or if
one is greater than the other, and so on. But when you want to check to see if a variable is in between a
range of values or to check multiple conditions we use logical operators.

The following table lists the logical operators

Operator Name Example Result Description


a && b Logical AND (3>5) && (2>5) True Returns true if the both operands is true.
a || b Logical OR (3>5) && (10>5) True Returns true if any of the operands is true
!a NOT ! (3>= 5) True Complements the result of the expression

Relational Operator
Relational Operators are used for comparing numerals and the characters.
The result of applying relational operators is either true or false.
The following table lists the relational operators

Operator Name Example Result Description


Returns true if the first operand is greater than
a>b Greater than 3>5 False
the second operand
Returns true if the first operand is lesser than the
a <b Lesser than 5<5 False
second operand
Greater than or Returns true if the first operand is greater than
a>= b 3 >= 5 False
equal or equal to the second operand.
Lesser than or Returns true if the first operand is lesser than or
a <= b 15 <= 15 True
equal to equal to the second operand.
Returns true if the first operand is equal to the
a == b Equal To 3 == 2 False
second operand.
Returns true if the first operand is not equal to
a != b Not equal to 3 != 2 True
the second operand.

22
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
instanceof Operator

Java provides a run-time operator instanceof to compare a class and an instance of that class.
This operator " instanceof" compares an object to a specified class type. The instanceof operator is
defined to know about an object's relationship with a class. It evaluates to true, if the object or array
is an instance of the specified type; otherwise it returns false. The instanceof operator can be used
with the arrays and objects. It can't be used with primitive data types and values.

Its syntax is

object instanceof type

Example:

class X {
int i, j;
}
class Y {
int i, j;
}
class Z extends X {
int k;
}

public class InstanceOfDemo {


public static void main(String args[]) {
X x = new X();
Y y = new Y();
Z z = new Z();
if(x instanceof X)
[Link]("x is instance of X");
X obj;
obj = z; // X reference to c
if(obj instanceof Z)
[Link]("obj is instance of Z");
}
}

Java Expressions

An expression is a construct made up of variables, operators, and method invocations, which are
constructed according to the syntax of the language, that evaluates to a single value.

int sum = 0;
mark[0] = 100;
[Link]("Element 1 at index 0: " + mark[0]);

int result = 1 + 2; // result is now 3


if(value1 == value2) [Link]("value1 == value2");

23
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
The data type of the value returned by an expression depends on the elements used in the expression.
The expression sum=0 returns an int because the assignment operator returns a value of the same data
type as its left-hand operand; in this case, cadence is an int. As you can see from the other expressions,
an expression can return other types of values as well, such as boolean or String.

Evaluation of Expressions

Expressions are evaluated using the assignment statement


Syntax:

variable=expression

In java the expressions are evaluated based on some rules known as operator precedence and
associativity. Normally the expressions to the right of the assignment operator are evaluated from left
to right based on the operator precendence and the result is assigned to the variable on the left hand
side.
The following are the rules that are to be followed when evaluating an arithmetic expression

• () Any thing within the parenthesis is evaluated first irrespective of the precedence.
• ++, -- The pre_increment and decrement calculations are performed next
• *, /, % Do all multiplications, divisions and remainders from left to right.
• +, - Do additions and subtractions from left to right.

= Assign the right-hand side to the left-hand side

for(int i=0;i&lt;7;i++)
{
[Link]("i="+i);
}

Control statements in JAVA:

A program is a group of statements that are executed to achieve a predetermined task. Statements
in a program are generally executed in a sequential manner, which is called sequential execution or
sequential control flow. However, by putting the decision-making statement in the program, the normal
flow of the program can be controlled. Statements that control the flow of the program are called control
statements.

Control statements are used in programming languages to cause the flow of control to advance and
branch based on changes to the state of a program.

The kinds of control flow statements supported by different languages vary, but can be categorized
by their effect:

• Continuation at a different statement (jump),


• Executing a set of statements only if some condition is met (choice),
• Executing a set of statements zero or more times, until some condition is met (loop),
• Executing a set of distant statements, after which the flow of control may possibly return
(subroutines, coroutines, and continuations),
• Stopping the program, preventing any further execution (halt).
24
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Java supports three types of control structures

* Decision-making statements (if-then, if-then-else, switch),


* Looping statements (for, while, do-while),
* Branching statements (break, continue, return)

Decision Making Statements

The decision-making statements are used to change the flow of the program based on conditions. The
various decision-making statements are

• if statement
• if..else statement
• if..else if Ladder
• Nested if statements
• switch statement

if Statement

If Statement:

This is a control statement to execute a single statement or a block of code, when the given
condition is true and if it is false then it skips if block and rest code of program is executed

Syntax:

if(boolean expression)
{
statements
}
Explanation:

If the condition is true then the statements within the block is executed otherwise the control is
transferred to the next statement following the if block.
The condition should be a valid relational or logical expression.
The condition should not be followed by semicolon.

Flowchart

Example:

int a=10, b=3;

if(b!=0)
{
float x=a/b;
[Link]("a/b="+x);
}

25
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES

if..else Statement

This is two way branching statement and is an extension of if statement and informs what to do if the
condition evaluates to false.

Syntax:
if (condition)
{
//true block statement 1
}
else
{
//false block statement 2
}
next statement

Flowchart:

Execution:

• If the condition is true then the true block


statements are executed and then the control is
transferred to the next statement.
• If the condition is false then the false block
statements are executed and the control is
transferred to the next statements.

Example:

/* Biggest of two numbers */


class big
{
public static void main(String args[])
{
int a=5, b=10;
if(a>b)
[Link]("A is big");
else
[Link]("B is big");
}
}

Nested if statement

When if ..else statement is placed inside another if..else statement then it is called nested if…else
statement. This is used for making multiway decisions.

26
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Syntax:

Nested if

if (condition1)
{
if (condition2)
{
//statement-1
}
else
{
//statement2
}

}
else
{
//false block
}
next statement

Execution:

In the case of nested if else statement the condition in first if statement is evaluated if true then
the if statement within the if block will be evaluated and so on.

If the condition is false then the else block statements will be executed.

Example:

/* Biggest of three numbers */


class biggest
{
public static void main(String args[])
{
int a=5,b=10,c=7;
if(a>b)
{
if (a>c)
[Link]("A is big");
else
[Link]("C is big");
}
else
{
if (b>c)
[Link]("B is big");
else
27
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
[Link]("C is big");
}
}
}

if..elseif Ladder

This is another way of multiway decision. In this statement each else statement has an associated if
statement.

Syntax:
….
if (condition1)
{
statement-1
}
else if (condition 2)
{
statement-2
}
……………
else if(conditio n)
{
statement-n
}
else
{
default statement
}
next statement

Execution:

• The <condition1> is evaluated first. If it evaluates to true, then /* statements 1 */ are executed.
The rest of the if-else-if construct is ignored.
• If <condition 1> is false, then <condition 2> is checked; if <condition 2> is false, <condition 3>
is checked.
• This process continues until a condition evaluates to true. At this point, the statements following
the associated if or else-if are executed.
• If none of the conditions evaluate to true, if there is a final else clause, those statements are
executed. Otherwise, execution continues with the statements after the if-else-if construct.
• If the clauses for any of the conditions is more than one statement, than curly brackets are
necessary. Otherwise, the brackets are optional.

Example:

/* To find grade of the student*/

28
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
class ifladder
{
public static void main(String args[])
{
int avg;
avg=[Link](args[0]);
if(avg&gt;79)
[Link]("Distinction");
else if(avg&gt;59)
[Link]("First Class");
else if(avg&gt;39)
[Link]("Second Class");
else
[Link]("Fail");
}
}
Switch Statement
• An alternative to a series of else if is the switch statement.
• The switch statement allows you to choose a block of statements to run from a selection of code,
based on the return value of an expression.
• The expression used in the switch statement must return an byte, short, char, and int primitive
data types or a enumerated data type.
Syntax:
switch(expression)
{
case <val-1>:
block-1
break;
case <val-2>:
block-2
break;
…….
case <val-n>:
block-n
break;
default :
default_block
}
Execution:
• The expression that creates labels for the case must be unique.
• The switch expression is matched with each case label.
• Only the matched case is executed ,if no case matches then the default statement (if present) is
executed.
Example:
class DemoSwitch
{
public static void main(String args[])
{
int day = 5;
switch (day)
{
29
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thrusday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
default:
[Link]("Invalid entry");
}
}
}

Looping Statements

Looping statements are used to execute single or group of statements repeatedly until thegiven
condition is true. Java supports three types of Looping statements

1. while Loop
2. do...while Loop
3. for Loop

The while Statement:


This executes a block of statements as long as a specified condition is true.

Syntax:

while(condition)
{
statement(s);
}
next_statement;

• The (condition) may be any valid Java expression.


• The statement(s) may be either a single or a compound (a block) statement.

Execution:
30
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
When program execution reaches a while statement, the following events occur:

1. The (condition) is evaluated.


2. If (condition) evaluates as false the while statement terminates and execution passes to the first
statement following statement(s) that is the next_statement.
3. If (condition) evaluates as true the statement(s) iside the loop are executed.
4. Then, the execution returns to step number 1.

Flow chart:

Example:

/* while loop example , Printling the even numbers from 0 to 10*/


class even
{
public static void main(String args[])
{
int i=0; //Initialize loop variable
[Link]("Even numbers\n");
while(i<=10)
{
[Link](i);
i+=2;
}

}
}

do..while Statement

31
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
• do..while loop is used when you need to run some statements and processes once at least before
checking the condition to execute the loop.

Syntax:

do
{
statements;
}
while(condition);
next Statement;

Execution:

1. The statement in the do..while block is executed once.


[Link] the condition.
3. If the condition evaluates to true goto step1. If the condition is false then goto step 4.
4. Execute the statement following the do..while statement.

Example:

/* Program to find the reverse of the number */


public class DoWhile
{
public static void main(String[] args)
{
int n = 12345;
int t,r = 0;
[Link]("The original number : " + n);
do
{
t = n % 10;
r = r * 10 + t;
n = n / 10;
}while (n != 0);
[Link]("The reverse number : " + r);
}}

for loop

The for loop statement is similar to while loop. Usually it is used to execute set of statements repeatedly
a known number of times.

Syntax:

for( initialization; termination; increment/decrement)


{
statements;
}
next Statement;

32
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Execution

1. When the loop first starts, the initialization portion of the loop is executed. Generally, this is an
expression that sets the value of the loop control variable, which acts as a counter that controls
the [Link] initialization expression is only executed once.
2. Next, condition is evaluated. This must be a Boolean expression. It usually tests the loop control
variable against a target value. If this expression is true, then the body of the loop is executed. If
it is false, the loop terminates.
3. Next, the increment/ decrement portion of the loop is executed. This is usually an expression
that increments or decrements the loop control variable.
4. The loop then iterates, first evaluating the conditional expression, then executing the body of the
loop, and then executing the iteration expression with each pass. This process repeats until the
controlling expression is false.

Flowchart

Example:

/* Printing numbers from 1 to 5 */

class ForDemo
{
public static void main(String[] args)
{
for(int i=1; i<=5; i++)
{
[Link]("Value of i :" + i);
}
}
}

Nested for loops

Nested for Loops:

33
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
• When we write a for loop under another for loop then it is called nested loop. The first for loop
is called outer loop and the second for loop is called inner loop.
• In case of nested loop the inner loop executes each time the outer loop got executed.

Example:

public class ForLoop


{
public static void main(String[] args)
{
for(int i = 1;i<= 5;i++) // Outer Loop
{
for(int j = 1;j<= i;j++) //Inner Loop
{
[Link](i);
}
[Link]();
}
}
}

34
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Arrays:

An array is a fundamental data structure that enables us to store and manipulate potentially huge
quantities of data. An array stores an ordered sequence of homogeneous values. Homogeneity means
that all the values are of the same type, e.g., 180 integer exam marks, 50 student's names etc.

For e.g.

To store the marks of 5000 students, you can declare an array, marks, of size 5000 and can store the
marks of as many students.
int marks[] = new int[5000];

Note: - Array index element number always starts with 0(zero).

Each item in an array is called an element, and each element is accessed by its numerical index. As
shown in the above illustration, numbering begins with 0. The 9th element, for example, would
therefore be accessed at index 8.

Advantages of using Arrays

1. You can refer to a large number of elements by just specifying the index number and the array
name.
2. Arrays make it easy to do calculations in a loop.

The various types of arrays in java are:

• One-dimensional arrays
• Two-dimensional arrays
• Multidimensional Arrays

One-dimensional Arrays

One-dimensional array is a list of variables of the same data type.

Creating Array

The length of an array is fixed at the time of its creation. An array represents related entities having
the same data type in contiguous or adjacent memory locations. The related data having data items form
a group and are referred to by the same name.

Creating an array consists of two steps

1. Declaring an array
2. Allocating memory
35
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Syntax 1:To declare a one-dimensional array

type array_name []; //type is the datatype of the array.

or

type[] array_name ; //type is the datatype of the array.

For e.g.

int test_scores []; // test_scores is name of the array.

Syntax 2: Allocating Memory to Arrays

The new operator is used to allocate memory to an array.

array_name = new type[size];

For e.g.

test_scores = new int[4]; //size of the array is 4.

You can declare and allocate memory to a user-defined array in a single statement.

Syntax

type arr [] = new type[size];

for e.g

int test_scores[]=new int[4];

Initializing Arrays

• An element of an array must be given a value before it is used. With Java compilers, all variables,
including array elements, are given default initial values. For example, all number elements are
initialized to 0.
• We can initialize values to the array elements using assignment operator as

Arrayname[index]=value
36
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
For example

test_scores[0]=78;

test_scores[1]=89;

test_scores[2]=98;

test_scores[3]=90;

• We can also initialize all the array elements in a single step as

Datatype Arrayname[ ]={value1, value2,……,value n);

int test_scores[ ] ={ 78, 89, 98, 90 };

• In this case we need not explicitly use new operator to allocate size of the array, it is
automatically assumed.

Getting Array length

• Actually, arrays do have one named instance variable: length.


• It contains the length of the array (number of elements).
• It is a good idea to use this value as the upper bound of a loop, rather than a constant value.

Example:

for(int i=0;i<test_scores.length;i++)

[Link](test_scores[i]);

test_scores.length in this case will be 4.

Array Processing

Processing array means accessing the individual elements in an array. This is done by following the
array name with a pair of square brackets containing the index of the element. Note that array indices
range from 0 to size of array minus one. So an array of 10 elements will have indices 0 through 9.

Normally for loop is used to process the array elements.

Example:

/* Array example */
class arraydemo
{
publicstaticvoid main(String args[])
{
int a[]={2,5,6,7,8}; //Array initialization
[Link]("Number of elements in array A: "+[Link]);
[Link]("Elements in array A");

37
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
for(int i=0;i <[Link];i++)
[Link](i+"\t");
}
}

Multi-Dimensional Arrays

Multi-Dimensional Arrays
An array with more than one dimension is called multidimensional arrays.
Two dimensional Arrays
A two-dimensional array, also known as a table or a matrix, where each element associates with a
pair of indexes, is another simple array. We conceptualize a two-dimensional array as a rectangular grid
of elements divided into rows and columns, and we use the (row, column) notation to identify a specific
element.
The following figure illustrates this conceptual view and the element-specifying notation.

Creating 2D Arrays:
The 2D array can be declared in the same way as 1D Array by specifying the row and column value
Syntax
datatype arrayname[ ][ ]=new datatype[rowsize][columnsize];
Example:
Internally, Java stores 2 dimensional arrays as an array of arrays:

int [][] nums = new int[5][4];

Initialilzation of 2D Array

datatype arrayname[][] ={ {row_1 values}, {row _ values}.......{row_n Values}}

Example:

int nums[][] = { {2,8,1,6}, (1,6,5,3}, {3,2,6,4},{2,9,7,2} };

This is represented by the figure below

38
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES

Example:

/* Matrix printing */
class matrix
{
public static void main(String args[])
{
//Declaring two dimensional array and Initialization
int a[][]={{1,2,3},{4,5,6},{7,8,9}};
[Link]("The given matrix");
for(int i=0;i&lt;3;i++)
{
for(int j=0;j&lt;3;j++)
{
[Link](a[i][j]+"\t");
}
[Link]();
}
}
}

Vectors

Vectors

• An array is a data type for collecting a fixed number of data of the same type.
• "Arrays" of variable sizes are provided by the Vector class.
• The Vector class is an example of what is called a container. Other container classes are Stack
(for implementing last-in, first-out sequence) and Hashtable (for an associative array).
• Characteristic of Java container classes is that they automatically resize themselves so that you
can put in any number of objects.
• Furthermore, a Java container looses all type information and simply holds objects of type
Object. It is left to the programmer to remember what he or she actually puts into the container
and to perform a cast to the correct type before using the elements.
• The Vector class is available in [Link] package

Note: The Vectors can contain only Objects and they cannot store primitive datatypes.

Properties of Vectors

39
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Vectors are much like arrays in that Vectors are

• Heterogenois - vectors typically can store different kinds of element;


• Indexed -vectors permit clients to access values using integers that indicate position;
• Efficient - vectors provide fast access to values.
• Expandable - you can continue to add elements to a vector, even if the vector has grown beyond
its original size.

Creating Vectors

Whenever you start working with vectors in Java, it is convenient to first import the Vector class
from the [Link] package.

import [Link]; // load Vector package


To create a vector, use three steps:
• Declare a variable to hold the vector.
• Vector v; // declare a vector object
Declare a new vector object and assign it to the vector variable.
v = new Vector(); // create an empty vector object
You may also add a number to specify the (initial) capacity of the object, e.g.,
v = new Vector(5); // create a vector object with initial capacity 5

Wrapper Classes

Wrapper Classes

Wrapper class is a wrapper around a primitive data type. It represents primitive data types in their
corresponding class instances o, there is an Integer class that holds an int variable, there is a Double
class that holds a double variable, and so on. The wrapper classes are part of the [Link] package,
which is importedby default into all Java programs. All of the primitive wrapper classes in Java are
immutable i.e. once assigned a value to a wrapper class instance cannot be changed further.

Features Of the Wrapper Classes


Some of the sound features maintained by the Wrapper Classes are as under :

• All the methods of the wrapper classes are static.


• The Wrapper class does not contain constructors.
• Once a value is assigned to a wrapper class instance it cannot be changed, anymore.

Following table lists the primitive types and the corresponding wrapper classes:

Primitive Wrapper
boolean [Link]
byte [Link]
char [Link]
double [Link]
float [Link]
40
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
int [Link]
long [Link]
short [Link]
void [Link]

Strings

Strings in Java:

• Handling character strings in Java is supported through two final classes: String class and String
Buffer class.
• The Java String class implements immutable character strings, which are read-only once the
string has been created and initialized, whereas the String Buffer class implements dynamic
character strings.
• All string literals in Java programs, are implemented as instances of String class. Strings in Java
are 16-bit Unicode

String Class

• String is normally defined as sequence of characters.


• String is not a data type in java but a class i.e. java implements strings as objects of type String.
String is the name of a predefined class.

– Its actual name is [Link]

• String class in one of the most important class in the Java api. String class provides the functions
to manipulate strings in Java Program.
• The String class is a little special

– It has support for literals, like "Hello Class"

– It has support for operators:

+ concatenation

+= assignment and concatenation, as in

41
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
s += " Append to end of s";

• String class objects are immutable objects which mean that they cannot be altered. When we try
to change them a new object is created. An example to show this fact is illustrated below.

String s= ”Hello” ;

// here s is referring to a string object that contains character ‘hello’.

s=s + ”Students” ;

// A new string class object containing helloStudents is formed and the old object (that
holds hello) is collected by java garbage collector.

Literal Strings
• Are anonymous objects of the string class
• Are defined by enclosing text in double quotes. “This is a literal string”
• Don’t have to be constructed.
• Can be assigned to string variables.
• Can be passed to methods and constructors as parameters.
• Have methods you can call.

Example:
String s="This is a String Literal";\

Once the string has been created and initialized, what a String can do for you?.

A String object can:


– tell you it's length
– tell you if it contains a substring (and where).
– tell you if it matches a regular expression.
– tell you what is at any position
– create a copy that is all lowercase or uppercase
– compare itself to another String

Constructors of String Class

String class has overloaded constructors. Following are some of the constructors of String class

1) String( );

Initializes a string with empty character sequence.

2) String(String value)

Initializes the string with the given string object.

Example:

String s = new String ("Java Programming");


[Link](s);
42
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
The output will be Java Programming

3) String(char char[]);

Initializes the string with the given character array.

Example:

char chars [ ]={ ‘a’ , ‘b’, ‘c’ };


String s = new String (chars);
[Link](s);

The output will be abc

4) String(char char[], int startindex, int numchar);

Initializes the string with the characters from the given character array starting from the given
index and adding number of characters.

Example:

char chars[ ] = { ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’ };


String s = new String (chars,2,3);
[Link](s);

The output will be cde

String Class Methods

Basic string methods

1. s. concat(String s2)

Concatenates one string onto another. Appends the String s2 to the String s.

Example:

String str1 = new String("Hello ");


String str2 = new String("World");
String str3 = [Link](str2);

[Link](str3);

The output is "Hello World":

2. [Link]()

Returns the length of the string.

Example:

43
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
String str1 = new String("Hello ");
int n=[Link]();

[Link]("Length="+n);

The output is Length=5

3. [Link](char, char)

Replaces all occurrences of one character with a different character.

Example:

String str = “java” , newstr ;


newstr=[Link](‘a’,’#’);

[Link](newstr);

The output is j#v#

4. [Link]()

Converts the entire string to lowercase.

5. s. toUpperCase()

Converts the entire string to uppercase.

Example:

String str = new String("This is MiXeD caSE");


String upper = [Link]();
String lower = [Link]();
[Link]("Upper:"+upper);
[Link]("Lower:"+lower);

The output is
Upper:THIS IS MIXED CASE
Lower:this is mixed case

6. trim()

Trims both leading and trailing whitespace from the string.

Example:

String s1= “ ab cd “; // There are 6 spaces.


[Link]("The length before trim:"+[Link]()); // 4 characters + 6spaces=10
s1 = [Link]();
[Link]("The length after trim"+ [Link]()); // 4 characters + 2spaces=6

44
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
The output is
The length before trim :10
The length after trim :6

Methods for getting substring

1. s. charAt(int)

Returns the character at the specified location.

Example:

String str = new String("This is a String");


char ch = [Link](8);
[Link]("Character at index 8:"+ch);
The output is
Character at index 8:a

3. s. substring(int i)

Returns the substring from the i-th char to the end

Example:

String str = new String("This is a Java");


String substr = [Link](10);
[Link]("Substring from index 10:"+substr);
The output is
Substring from index 10:Java

4. substring(int i, int k)

Returns the substring of chars in positions from i to k-1

Example:

String str = new String("Java Programming");


String substr = [Link](5,9);
[Link]("Substring from index 5 to 9:"+substr);
The output is
Substring from index 5 to 9:Prog

Methods for comparing strings


1. [Link](String s2)
Compares two strings. Returns 0 if they are equal, a negative value if the specified string is greater
than the string, or a positive value otherwise.
2. [Link](String s2)
Compares two strings. Returns 0 if they are equal, a negative value if the specified string is greater
than the string, or a positive value otherwise. This is not case sensitive
45
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Some String comparison Examples:

//negative differences

diff = “apple”.compareTo(“berry”); //a before b


diff = “Zebra”.compareTo(“apple”); //Z before a
diff = “dig”.compareTo(“dug”); //i before u
diff = “dig”.compareTo(“digs”); //dig is shorter

//zero differences
diff = “apple”.compareTo(“apple”); //equal
diff = “dig”.compareToIgnoreCase(“DIG”); //equal

//positive differences
diff = “berry”.compareTo(“apple”); //b after a
diff = “apple”.compareTo(“Apple”); //a after A
diff = “BIT”.compareTo(“BIG”); //T after G
diff = “huge”.compareTo(“hug”); //huge is longer
3. [Link](String s2)
Returns true if the string matches the object.
4. [Link](String s2)
Returns true if the string matches the specified [Link] is case insensitive

Example:

String str1 = new String("abc");


boolean result = [Link]("ABC"); // Returns false
boolean result = [Link]("ABC"); // Returns true

String Arrays

An array is the collection of same data type. Suppose if we have a declare an array of type String, then
it will store only the String value not any other data type. When we have a closely related data of the
same type and scope, it is better to declare it in an array.

Syntax:
String arrayname[]=new String[size];

Example:
String name[]=new String[15]; // This declares a string array of size 15.

String Buffer Class

The String Buffer Class

The primary limitation of the string class is that once the string is created you cannot change it. If
you need to store text that may need to be changed you should use the String Buffer class. The
String Buffer class includes methods for inserting and appending text. Additionally, a String Buffer
object may be easily converted into a String class when necessary.

46
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Advantages of String Buffer

• Alternative to String class


• Can be used wherever a string is used
• More flexible than String
• Has three constructors and more than 30 methods for managing the buffer and modifying strings
in the buffer

Constructors of String Buffer class

1. StringBuffer()

Constructs a StringBuffer object with no characters in it and an initial capacity of 16 characters.

2. StringBuffer(int length)

Constructs a String Buffer object with no characters in it and an initial capacity specified by length

3. StringBuffer(String s)

Constructs a StringBuffer object so that it represents the same sequence of characters as the
strings; returns a reference to the new object with a capacity of length of String s +16.

Methods in StringBuffer

1. [Link]()

Returns the current capacity of the String buffer.

2. length()

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

3. [Link](int index)

The specified character of the sequence currently represented by the string buffer, as indicated by
the index argument, is returned.

4. [Link](int offset, char c)

Inserts the string representation of the char argument into this string buffer.

Note that the StringBuffer class has got many overloaded ‘insert’ methods which can be used based
on the application need.

5. [Link](int start, int end, String str)

Replaces the characters in a substring of this StringBuffer with characters in the specified String.

6. [Link]()

47
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
The character sequence contained in this string buffer is replaced by the reverse of the sequence.

7. [Link](String str)

Appends the string to this string buffer.

Note that the StringBuffer class has got many overloaded ‘append’ methods which can be used
based on the application need.

Classes and Objects

Introduction to Classes

• Java is a true OOPs language and therefore the underlying structure of all Java programs is
classes.
• Anything we wish to represent in Java must be encapsulated in a class that defines the “state”
and “behaviour” of the basic program components known as objects.
• Classes create objects and objects use methods to communicate between them.
• They provide a convenient method for packaging a group of logically related data items and
functions that work on them.
• A class essentially serves as a template for an object and behaves like a basic data type “int”.
• It is therefore important to understand how the fields and methods are defined in a class and
how they are used to build a Java program that incorporates the basic OO concepts such as
encapsulation, inheritance, and polymorphism.

Defining a class

A class definition is a description of a type of container – it describes what pieces of information the
new type holds and the methods with which that information can be manipulated. so the class is
composed of fields and methods

The basic syntax for a class definition:

<access specifier>class ClassName [extends SuperClassName]


{
[fields declaration]
[Constructors]
[methods declaration]
}
</access>

The access apecifier can be public, private,protected or left undefined

The class is a keyword and the classname is a user defined name.

Defining fields

• A field is a variable defined within a class definition that is associated with an instance of that
class or with all instances of the class.
• All fields must have a declared type, just as other variables do
48
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
• A field can be static(the keyword static), indicating that it is a “class variable”, a variable whose
value is shared across all instances of the class or, a field can be non-static (no keyword is
required), indicating that there is a separate copy associated with each instance of the class
• Static fields can be accessed using the name of the class or through an instance of the class,
although the former is preferred over the latter Fields can also have access modifiers in their
declaration

Syntax for defining a field:

<access specifier> datatype variable_name;

The access-specifier can be public, private, protected or left undefined.

Example:

class Rectangle
{
int len,bre;

public String color;


}

Defining methods

• A Java method is a set of Java statements which can be included inside a Java class
• A class with only data fields has no life. Objects created by such a class cannot respond to any
messages.
• Methods are declared inside the body of the class but immediately after the declaration of data
fields.
• Methods operate on fields or on arguments that are passed in
• All methods have a return type (the type of value they return to the calling method) or void
indicating that no value is returned
• Methods also may have access modifiers that control access to the method much as they do for
fields
• Methods return their value using return

Syntax for defining a method

<access apecifier> returntype methodname (datatype arg1, datatype arg2,...., datatype arg3)
{
//Method Body
[return statement]
}
</access>

Creating Objects

In order to create and Use Objects from Existing Classes we must

• Declare an object
• Create an object

49
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
• Access the members of class using object

Declare an object:

We have to specify what type (i.e. class) the object will be.

The syntax

<class name> object name>;

Where class name is the name of the already defined class and the object name is a valid identifier.

Creating Objects

The operator you will use in your code to create new objects is called, appropriately, new. When you
call the new operator in your code, you follow it by the name of the class from which you want to
instantiate the object. Java automatically allocates a portion of memory to store instances of the
variables declared in the class. This portion of memory is the object. After allocating an object, you will
use methods in the object's class to send messages to it. You also can send messages to the object from
methods in other classes.

<objectname>=new classname([arguments]);

When you create an object, you typically declare a reference variable that will hold the object's
reference. Java creates a reference automatically whenever new instantiates an object in order to locate
the object in memory when [Link] very rudimentary form of an object creation follows:

Example:

Let us create an object for the already defined Recatngle class in the previos chapter
Rectangle r1; //Rectangle name of the class, r1 name of the object
r1=new Rectangle(); //Allocating memory

The following figure illustrates the above process

Accessing class members

Once we have defined an object we can now access the members of the class using the dot (.)
operator.

Syntax:
objectname. instancevariablename // To access the fields
objectname. methodname(parameter list) // To access the methods
But we cannot reference the private members of a class using an object.

50
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Constructors

A constructor can be thought of as a specialized method of a class that creates (instantiates) an instance
of the class and performs any initialization tasks needed for that instantiation. The syntax for a
constructor is similar but not identical to a normal method and adheres to the following rules:

• The name of the constructor must be exactly the same as the class it is in.
• Constructors may be private, protected or public.
• A constructor cannot have a return type (even void). This is what distinguishes a constructor
from a method.
• Multiple constructors may exist, but they must have different signatures, i.e. different numbers
and/or types of input parameters.
• Default constructor: If you don't define a constructor for a class, a default parameter less
constructor is automatically created by the compiler. The default constructor calls the default
parent constructor (super()) and initializes all instance variables to default value (zero for
numeric types, null for object references, and false for Booleans).
• The existence of any programmer-defined constructor will eliminate the automatically
generated, no parameter, default constructor. If part of your code requires a no parameter
constructor and you wish to add a parameterized constructor, be sure to add another, no-
parameter constructor.

Example:

class Rectangle
{
double length,bre;
Rectangle() // Constructor with no argument
{
length=bre=0;
}
Rectangle(double l) /* Constructor 1 */
{
length=bre=l;
[Link]("Constructor 1 called");
}
Rectangle(double l,double b) /* Constructor 2 */
{
length=l;
bre=b;
[Link]("Constructor 2 called");
}
void area()
{
[Link]("\nArea of the Given rectangle");
[Link]("Length ="+length);
[Link]("Breadth ="+bre);
[Link]("Area ="+(length*bre));
}
}
/* Main class */
class construct
51
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
{
public static void main(String args[])
{
Rectangle r1,r2;
[Link]("Creating the object r1");
r1=newRectangle(6); //Uses constructor 1
[Link]("Creating the object r1");
r2=newRectangle(2.5,3.0); //Uses constructor 2
[Link](); //Calling method
[Link]();
}
}

Method Overloading

In Java it is possible to define two or more methods within the same class with the same name, with
different parameters. Different parameters means the number of arguments or type of argument or the
both may differ. When this is the case, the methods are said to be overloaded, and the process is
referred to as method overloading. Method overloading is one of the ways that Java
implementspolymorphism.

When an overloaded method is invoked, Java uses the type and/or number of arguments as its
guide to determine which version of the overloaded method to actually call. While overloaded methods
may have different return types, the return type alone is insufficient to distinguish two versions of a
method.

When Java encounters a call to an overloaded method, it simply executes the version of the method
whose parameters match the arguments used in the call. This match need not always be exact. In some
cases Java's automatic type conversions can play a role in overload resolution

Example:

// Automatic type conversions apply to overloading.


class OverloadDemo
{
void test()
{
[Link]("No parameters");
}
// Overload test for two integer parameters.
void test(int a, int b)
{
[Link]("a and b: "+ a +" "+ b);
}
// overload test for a double parameter
void test(double a)
{
[Link]("Inside test(double) a: "+ a);
}
}
class Overload
52
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
{
public static void main(String args[])
{
OverloadDemo ob =newOverloadDemo();
int i =88;
[Link]();
[Link](10,20);
[Link](i); // This will invoke test(double)
[Link](123.2); // This will invoke test(double)
}
}

OverloadDemo does not define test(int). Therefore, when test( ) is called with an integer argument
inside Overload, no matching method is found. However, Java can automatically convert an integer into
a double, and this conversion can be used to resolve the call. Therefore, after test(int) is not found, Java
elevates i to double and then calls test(double). Of course, if test(int) had been defined, it would have
been called instead. Java will employ its automatic type conversions only if no exact match is found.

Inheritance

Inheritance

All men are mortal.


Socrates is a man.
Therefore Socrates is mortal.
—Typical Syllogism

Inheritance is a major component of object-oriented programming. Inheritance will allow you to


define a very general class (Existing), and then later define more specialized classes (New class) by
simply adding some new details to the older more general class definition. This saves work, because the
more specialized class inherits all the properties of the general class and you, the programmer, need
only program the new features.

The already existing class is known as the parent (or super class or base class) and the new classes
are known as children (or subclasses or derived classes). The concept of inheritance greatly enhances
the ability to reuse code as well as making design a much simpler and cleaner process.

The following kinds of inheritance are there in java.

• Single Inheritance
• Multilevel Inheritance

Pictorial Representation of Single and Multilevel Inheritance

Single Inheritance Multilevel

53
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES

Properties of Inheritance

What You Can Do in a Subclass

• A subclass inherits all of the public and protected members of its parent, no matter what package
the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-
private members of the parent. You can use the inherited members as is, replace them, hide
them, or supplement them with new members:

• The inherited fields can be used directly, just like any other fields.

• You can declare a field in the subclass with the same name as the one in the super class, thus
hiding it (not recommended).

• You can declare new fields in the subclass that are not in the super class.

• The inherited methods can be used directly as they are.

• You can write a new instance method in the subclass that has the same signature as the one in
the super class, thus overriding it.

• You can write a new static method in the subclass that has the same signature as the one in the
super class, thus hiding it.

• You can declare new methods in the subclass that are not in the super class.

• You can write a subclass constructor that invokes the constructor of the super class, either
implicitly or by using the keyword super.

Advantages of inheritance:

• No need to write code from scratch. You can start coding with existing class
• Through inheritance you can very easily convert small system into large systems
• Code reusability through inheritance increased.
• Good at representing the objects
• Inheritance provide a clear model structure which is easy to understand
• Codes are easy to manage and divided into parent and child classes.

Deriving a sub class

In java we can derive a subclass of an existing class using the extends keyword. One important
point in java inheritance is that a class can extend only one super class.

Syntax:

class subclassname extends superclassname


54
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
{
//Variable declaration
//method declaration
}

where class, extends are the keywords.

Example:

class one // Super class


{
//member declarations
}
class two extends one //sub class
{
// member declarations
}

Types of Inheritance

Based on the number of super class and subclass we can classify inheritance into several types.
They are

(1) Simple / Single Inheritance

Here only one subclass is derived from a single super class.

(2) Multilevel Inheritance

When a subclass is derived from a derived class then this mechanism is known as the multilevel
inheritance. The derived class is called the subclass or child class for it's parent class and this
parent class works as the child class for it's just above ( parent ) class. Multilevel inheritance can
go up to any number of level.

3) Hierarchical inheritance

In this type of inheritance we can derive more than one sub class from a single super class.

4) Multiple Inheritances

When a subclass is derived from more than one super class then it is called multiple inheritances.
Multiple inheritances is not supported by Java. Multiple inheritance can be implemented with the
help of interface in Java.

5) Hybrid inheritance

This is a combination of multilevel and hierarchical inheritance.


The following figure represents the types of inheritance

55
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES

Method Overriding

• In a class hierarchy, when a method in a subclass has the same name and type signature as a
method in its super class, then the method in the subclass is said to override the method in the
super class.
• When an overridden method is called from within a subclass, it will always refer to the version
of that method defined by the subclass.
• The version of the method defined by the super class will be hidden.
• Method overriding occurs only when the names and the type signatures of the two methods are
identical. If they are not, then the two methods are simply overloaded.

Example:

/* Method overriding example */


class one //Super class
{
void calculate(int x,int y)
{
[Link]("Class one");
[Link]("X="+x+"\nY="+y+"\nX+Y="+(x+y));
}
}
class two extends one //sub class
{
void calculate(int x,int y) //Overrided method
{
[Link]("Class two overrided method");
[Link]("X="+x+"\nY="+y+"\nX*Y="+(x*y));
}
void calculate(float x,float y) //Overloaded method
{
[Link]("Class two overloaded method");
[Link]("X="+x+"\nY="+y+"\nX*Y="+(x*y));
}
}

/* Main Class */
class override
{
public static void main(String args[])
{
two t=new two(); //Creating object of class two
[Link](6,7);
56
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
[Link](2.5f,3.2f);
one o=new one(); //Creating object of class one
[Link](6,7);
}
}

In the above example the calculate (int,int) method of the class one has been overridden by the
class two. so in order to access the calculate method of class one we need to create an object for the
class [Link] you wish to access the super class version of an overridden method from within the subclass,
you can do so by using super keyword.

Final Variables, methods & Classes

Final Keyword

The word final is a keyword in java. The final keyword is used in several different contexts with the
variable declaration, methods and classes as a modifier meaning that what it modifies cannot be
changed in some sense.

Final variables:

• When a variable is declared final, it is a constant which will not and cannot change. It can be set
once (for instance when the object is constructed, but it cannot be changed after that.)
• Attempts to change it will generate either a compile-time error or an exception

Example:

final PI=3.14;

The value of PI is declared asd final soit cannot be changed in the course of the program.

Final Methods:

You can also declare that methods are final. A method that is declared final cannot be overridden in a
subclass. The syntax is simple, just put the keyword final after the access specifier and before the return
type like this:

Syntax:

access specifier final returntype methodname(arguments)


{
//method body
}

When you try to override method that has been declared final it will generate compile time error.

Example:

class A
{
final void meth() //Final method

57
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
{
[Link]("This is a final method.");
}
}

class B extends A
{
void meth() // ERROR! Can't override.
{
[Link]("Illegal!");
}
}

Final Class
You can prevent others from extending your class by making it final using the keyword final in the
class declaration
Syntax:
final class FinalClass
{
//Members
}
Example
final class finalclass
{
//Definitions of members
}
class errorclass extends finalclass
{
//Definitions of members
}
The above program segment contains error since we tried to extend a final class.

finalize Method
Garbage collection
The objects are dynamically allocated by using the new operator, such
objects must be destroyed and their memory released for later reallocation. Java takes a different
approach; it handles deallocation automatically. The technique that accomplishes this is called
garbage collection.
It works like this: when no references to an object to an object exist, that object is assumed to be
no longer needed, and the memory occupied by the object can be reclaimed. There is no explicit need
to destroy objects. Garbage collection only occurs at irregular intervals (if at all) during the execution
of your program. It will not occur simply because one or more objects exist that are no longer used.
Furthermore, different java run-time implementations will take varying approaches to garbage
collection,.

The finalize () Method

Sometimes an object will need to perform some action when it is destroyed. For example, if an
object is holding some non-java resource such as a file handle or window character font, then you might
want to make sure these resources are freed before an object is destroyed. To handle such situations,
58
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
java provides a mechanism called finalization. By using finalization, you can define specific actions that
will occur when an object is just about to be reclaimed by the garbage collector.
To add a finalizer to a class, you simply define the finalize() method. The java run time 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 by any
running state or indirectly through other referenced objects. Right before an asset is freed, the java run
time calls the finalize() method on the object.

Syntax:
protected void finalize()
{
// finalization code here
}

Here, the keyword protected is a specifier that prevents access to finalize() by code defined
outside its class.

It is important to understand that finalize() is only called just prior to garbage collection. It is not
called when an object goes out-of-scope, for example. This means program should provide other means
of releasing system resources, etc., used by the object. It must not rely on finalize() for normal .

Visibility Control

• Encapsulation links data with the code that manipulates it. Another important attribute of
encapsulation is access control , that is to control what parts of a program can access the
members of a class.
• You can define access control as the methods by which interactions with resources are limited
to collections of users or programs for the purpose of enforcing integrity, confidentiality, or
availability constraints.
• How a member can be accessed is determined by the access specifier that modifies its
declaration. Java supplies a rich set of access specifiers. Some aspects of access control are
related mostly to inheritance or packages.
• Java's access specifiers are public, private and protected. Java also defines a default access level.

Public:
When a member of a class is modified by the public specifier then that member can be accessed by any
other code in your program.
59
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES

private
When a member of a class is specified as private then that member can only be accessed by other
members of its class.

Default access specifier

When no access specifier is used then by default the member of a class is public within it's own
package but cannot be accessed outside of its package.

Protected:

When a member of a class is specified as protected it is available to all classes in the same package
and also available to all subclasses of the class that owns the protected feature.

This access is provided even to subclasses that reside in a different package from the class that
owns the protected feature.

60
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
private protected:

When a member of a class is specified as private protected it is available to all subclasses of the
class in the same package and to the subclasses of the other packages.

The following table lists the visibility modifiers and their visibility areas.

private No Modifier Private protected public


protected
Same class Yes Yes Yes Yes Yes

Same package sub class No Yes Yes Yes Yes

Same package Non-sub class No Yes No Yes Yes

Different package sub class No No Yes Yes Yes

Different package Non-sub class No No No No Yes

Interfaces and Multiple Inheritance

This is just like model for implementation of class. That means it describe the functions only on the
definition, means what class is made for. For E.g. if we want to make chair it will provide the functions
to implement to get work done i.e.( chair in our case ). The interface is similar to an abstract class. The
main difference being the interface can contain only final static variables and public abstract methods.

Multiple Inheritances

The java does not allow multiple inheritance meaning deriving a subclass from more than one super
class. This restriction can be overcome with the help of interfaces. The interface allows extending more
than one interface in an interface and also a class can implement more than one interface. So the
multiple inheritances is applied implicitly.

Defining an interface

Defining an Interface

• The interface can be defined just like defining a class with the interface keyword.
• To create an interface, you must write both the interface declaration and the interface body.
• An interface declaration can have two other components: the public access specifier and a list of
"super interfaces".
• An interface can extend other interfaces just as a class can extend. However, while a class can
only extend one other class, an interface can extend any number of interfaces.
• The public access specifier indicates that the interface can be used by any class in any package.
If you do not specify that your interface is public, then your interface will only be accessible to
61
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
classes that are defined in the same package as the interface. The interface body contains the
constant declarations and method declarations for the methods defined within the interface.

Syntax:

[public] interface interface-name extends interface 1, interface2,......


{
//final static variables
//public abstract methods
}

Example:

interface one
{
int x=10,y=16;
public void display();
}

interface two extends one


{
public void add();
}

Note:

• An interface cannot extend classes.


• An interface inherits all constants and methods from its super interface unless the interface
hides a constant with another of the same name, or re-declares a method with a new method
declaration.
• All constant values defined in an interface are implicitly public, static, and final.
• All methods declared in an interface are implicitly public and abstract.

Implementing interface and Accessing Interface Variables


Implementing interface:
• In order to access the variables and methods of an interface we must implement the interface
inside a class
• All the methods in the interface should be defined in the class that implements the interface.
• A class can implement more than one interface in such case the class should define methods
declared in all the interfaces implemented by that class.

Syntax:

access class class_name[extends superclass ] [implements interface1[,interface 2…]


{
//Variables declaration
//Method definitions
}

62
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
When we implement an interface method in a class it should be declared public. The class
implementing an interface can have its own variables and methods. The interface reference variable
can only access the methods of the interface and not of the class.

Example:

/* Program to show a implementing two interfaces */

/* First interface */
interface One
{
int x=12;
}
/* Second interface */
interface Two
{
int y=10;
void display();
}
/* Class implementing the interfaces */
class Demo implements One,Two
{
publicvoid display()
{
[Link]("X in inteface One ="+x);
[Link]("Y in interface Two="+y);
[Link]("X+Y= "+(x+y));
}
}
/* Main class */
class TwoInterface
{
public static void main(String args[])
{
Demo d=newDemo();
[Link]();
}
}

Interface contains final static variables. So the class that implements an interface can use the
variables as constant values within the class but cannot modify it. This is called accessing an interface
variable.

Packages

Java is an object oriented programming language and any Java programmer will quickly build a large
number of different classes for use in each application that they develop.

Initially it may be tempting to store the classes in the same directory as the end application, but as
the complexity applications grow so will the number of classes. The answer is to organize the classes
into packages.
63
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
The java has a rich set of system packages and it also allows the user to create and access their own
packages.

The Java System Package

The entire standard Java API is implemented in several packages. A package can contain both classes
and other packages. A package that is contained in another package is sometimes called a "sub-
package."

One of the sub-packages of java is called "awt". Since awt is contained within java, its full name
is actually [Link]. This package contains classes that represent GUI components such as buttons and
menus in the AWT.
The package [Link] also contains a number of classes that form the foundation for all GUI
programming, such as the Graphics class which provides routines for drawing on the screen, the Color
class which represents colors, and the Font class which represents the fonts that are used to display
characters on the screen. Since these classes are contained in the package [Link], their full names are
actually [Link], [Link], and [Link]. The java package includes several other
sub-packages, such as [Link], which provides facilities for input/output, [Link], which deals with
network communication, and [Link], which provides a variety of "utility" classes. The most basic
package is called [Link]. This package contains fundamental classes such as String, Math, Integer, and
Double.

The following is the partial graphical representation of the levels of nesting in the java package,
its sub-packages, the classes in those sub-packages, and the subroutines in those classes.

Java API Packages

The Java API is the set of classes included with the Java Development Environment. These classes
are written using the Java language and run on the JVM. The Java API includes everything from collection
64
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
classes to GUI classes
Java interfaces and classes are grouped into packages. The following are the java packages, from
which you can access interfaces and classes, and then fields, constructors, and methods.

Java API packages


[Link]

Package that contains essential Java classes, including numeric’s, strings, objects, compiler,
runtime, security, and threads. This is the only package that is automatically imported into every
Java program.

[Link]

Package that provides classes to manage input and output streams to read data from and write
data to files, strings, and other sources.

[Link]

Package that contains miscellaneous utility classes, including generic data structures, bit sets,
time, date, string manipulation, random number generation, system properties, notification, and
enumeration of data structures.

[Link]

Package that provides classes for network support, including URLs, TCP sockets, UDP sockets, IP
addresses, and a binary-to-text converter.

[Link]

Package that provides an integrated set of classes to manage user interface components such as
windows, dialog boxes, buttons, checkboxes, lists, menus, scrollbars, and text fields. (AWT =
Abstract Window Toolkit)

[Link]

Package that enables the creation of applets through the Applet class. It also provides several
interfaces that connect an applet to its document and to resources for playing audio.

Using System Defined Packages

There are two ways of accessing the classes stored in packages:

• Using fully qualified class name


• Import package and use class name directly.

1. Using fully qualified class Name

Let's say that you want to use the class [Link] .Vector in a program that you are writing. Like any
class, [Link] .Vector is a type, which means that you can use it to declare variables and parameters
and to specify the return type of a function. One way to do this is to use the full name of the class as the
name of the type.

65
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
For example, suppose that you want to declare a variable named myVector of type [Link] .Vector.
You could write

[Link] myVector = new myVector( );

Once defined we could use myVector object to access the members of Vector class.

2. Import package and use class name directly

Using the full name of every class can get tiresome, so Java makes it possible to avoid using the full
name of a class by importing the class. There are two ways to imprt a class

a) Importing a particular class in a package

b) Importing all the classes in a package

a) Importing a particular class in a package

Syntax:
import [Link];
If you put
import [Link];

at the beginning of a Java source code file, then, in the rest of the file, you can abbreviate the full
name [Link] to just the simple name of the class, Vector. Using this import directive would
allow you to define

Vector myVector =new myVector();

b) Importing all the classes in a package

There is a shortcut for importing all the classes from a given [Link] "*" is a wildcard that
matches every class in the package.

Syntax:
import package.*;
You can import all the classes from [Link] by
import [Link].*;

Note:

• When we use wildcard character, it does not match sub-packages; you cannot import the entire
contents of all the sub-packages of the java package by saying import java.*
• The import line comes at the start of a file and is not inside any class. Although it is sometimes
referred to as a statement, it is more properly called an import directive since it is not a
statement in the usual sense.
• The package [Link] is so fundamental, all the classes in [Link] are automatically imported
into every program. It's as if every program began with the statement "import [Link].*;". This
is why we have been able to use the class name String instead of [Link], and [Link]()
instead of [Link]().

66
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Package Naming conventions

What Is a Naming Convention?

A naming convention is a rule to follow as you decide what to name your identifiers (e.g. class, package,
variable, method, etc..).

Why Use Naming Conventions?

Different Java programmers can have different styles and approaches to the way they program. By using
standard Java naming conventions they make their code easier to read for themselves and for other
programmers. Readability of Java code is important because it means less time is spent trying to figure
out what the code does, leaving more time to fix or modify it.

Package naming convention

• Package names should be hierarchical with the components separated by period.


• Components should consist of lowercase alphabetic characters and rarely digits.
• The name of any package used outside your organization should begin with organization's
internet domain name with the top level domain first, for example [Link], [Link], gov etc.
• The standard libraries and optional packages whose names begin with java.
• Users should not create packages whose names start with java.
• The package name should be unique.

The remainder of a package name should consist of one or more components describing the package.

Creating and Importing Packages

A Java package is simply a directory that contains one or more class files. The task of creating and
accessing user defined package can be summarized as

• Creating a new folder in the name of package. The location of packages are defined by using the
CLASSPATH environmental variable
• Moving the class file to the new folder. Each class in the package must have the following as its
first line:

Package <package name>;

• Calling the package from any applications .The classes in the package are loaded into a Java
application by using:

import<package name>.* ;

Creating and Accessing a Java Package

Step1 : (Create the folder)

The first step is (rather obviously) to create the directory for the package. The directory is created
in the root directory where your application is working. The name of the folder should be same as that
of the package you want to create.

67
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Syntax: C:\jdk1.3\bin>md pack1

Step 2: (Putting the class inside the package)

Create the class or interface that you are going to keep in the package. The class or interface
definition should begin with the package statement as the first statement.

Syntax:

package package-name;
class definition or interface definition
If you want to use the class outside the package where it is defined specify the access specifier as
public.

Step 3:(Save the java file)

Save the source file in the directory created with .java as extension.

(Save as C:\jdk1.3\bin\pack1\[Link])

Step 4: (Compile the java file in the package to create the class file)

Compile the source file from its directory. (c:\jdk1.3\bin\pack1\javac [Link])

Step 5: (Move to parent Directory)

Return to parent directory (D:\java\pack1\cd..)

Step 6: (Importing the package)

The package created can be imported into the current source file using the import statement.

Syntax:

import packageName1[.subPackName….].*;

Step 7:

Key in the main program and save it with .java as extension in the root directory. We can now
create references to the classes specified in the package just like other classes and use them in our
program.

MULTITHREADING

• Multitasking refers to performing more than one task at a time.


• Multitasking can be performed at two levels, the process level and the thread level.
68
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
• Operating systems do multitasking at the process level and the programming languages provide
support at the thread level.
• Java supports multitasking at the thread level.

Definition of thread

• A thread is a single sequential flow of control within a program.


• Thread uses a separate execution environment.
• Every thread has its own program counter and stack but they can share memory and opened
files.
• A thread itself is not a program; it cannot run on its own. Rather, it runs within a program.

Properties of single threaded program

• The process begins execution at a well-known point. In Java the thread begins execution at the
first statement of the function or method called main().
• Execution of the statements follows in a completely ordered, predefined sequence for a given set
of inputs.
• While executing, the process has access to certain data. In Java, there are three types of data a
process can access: local variables are accessed from the thread's stack, instance variables are
accessed through object references, and static variables are accessed through class or object
references.

Multithreading

• In Multithreaded programming the process is divided into smaller independent tasks that can
be simultaneously executed.
• In every program there will be at least only thread running and it is called the main thread.

Properties of Multithreaded Program

• Each thread begins execution at a predefined, well-known location. For one of the threads in the
program, that location is the main() method; for the rest of the threads, it is a particular location
the programmer decides upon when the code is written.
• Each thread executes code from its starting location in an ordered, predefined (for a given set of
inputs) sequence.
• Each thread executes its code independently of the other threads in the program. If the threads
choose to cooperate with each other, there are a variety of mechanisms we will explore that
allow that cooperation. Exploiting those methods of co- operation is the reason why
programming with threads is such a useful technique, but that cooperation is completely
optional, much as the user is never required to drag a file from the file manager into the text
editor.
• The threads appear to have a certain degree of simultaneous execution. The degree of
simultaneity is dependent on several factors-programming decisions about the relative
importance of various threads as well as operating system support for various features. The
potential for simultaneous execution is the key thing you must keep in mind when threading
your code.
• The threads have access to various types of data. At this point, the analogy breaks down
somewhat depending on the type of data the Java program is attempting to [Link] thread
is separated, so that local variables in the methods that the thread is executing are separate for
different threads. These local variables are completely private; there is no way for one thread to
69
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
access the local variables of another thread. If two threads happen to execute the same method,
each thread gets a separate copy of the local variables of that method.
• Objects and their instance variables can be shared between threads in a Java program, and
sharing these objects is much easier between threads of a Java program than sharing data objects
between processes in most operating systems.
• Java threads cannot arbitrarily access each other's data objects: they need permission to access
the objects, and one thread needs to pass the object reference to the other thread.
• Static variables are the big exception to this analogy: they are automatically shared between all
threads in a Java program.

Advantages of thread

• It increases the speed of execution.


• It allows to run more tasks simultaneously
• It reduces the complexity of the program.
• It maximizes the CPU utilization

Creating Thread using Runnable Interface

Creating a Thread:

The thread can also be created by implementing Runnable interface in our class. The Runnable
interface contains only the run( ) method that we have to define in the implementing class. The steps
that are to be followed for creating thread using Runnable interface are

1. Create a class that implements Runnable interface.

2. Implement method run( )

Syntax:

class classname implements Runnable


{
-------
-------
public void run()
{
//statements
}
}

70
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
3. Create an instance of the implemented class.

4. Instantiate an object of class Thread using the constructor with the runnable object as the parameter.

5. Call the start( ) method using the Thread object. This in turn will call the run( ) method.

Syntax:

classname obj=new classname();


Thread threadobj=new Thread(obj);
[Link]();

Creating thread using Thread class

One way of creating thread is to extend the Thread class. The steps to create a thread using thread class
is as follows:

[Link] a subclass from class Thread.

[Link] the run( ) method in the class.

Syntax:

class classname extends Thread


{
-------
-------
public void run()
{
//statements
}
}

3. Create an instance of the subclass.

4. Call the start( ) method of class Thread. The start( ) calls run() method.

Syntax:

Classname obj=new classname();


[Link]();

Life Cycle of a Thread

Thread States:

A thread can be in one of the following states

1. New born state


2. Ready to run state
3. Running state

71
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
4. Blocked state
5. Dead state

New Born state

• The thread enters the new born state as soon as it is created. The thread is created using the new
operator.
• From the new born state the thread can go to ready to run mode or dead state.
• If start( ) method is called then the thread goes to ready to run mode. If the stop( ) method is
called then the thread goes to dead state.

Ready to run mode (Runnable Mode)

• If the thread is ready for execution but waiting for the CPU the thread is said to be in ready to
run mode.
• All the events that are waiting for the processor are queued up in the ready to run mode and are
served in FIFO manner or priority scheduling.
• From this state the thread can go to running state if the processor is available using the
scheduled( ) method.
• From the running mode the thread can again join the queue of runnable threads.
• The process of allotting time for the threads is called time slicing.

Running state

• If the thread is in execution then it is said to be in running state.


• The thread can finish its work and end normally.
• The thread can also be forced to give up the control when one of the following conditions arise

1. A thread can be suspended by suspend( ) method. A suspended thread can be revived by using
the resume() method.

72
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
2. A thread can be made to sleep for a particular time by using the sleep(milliseconds) method. The
sleeping method re-enters runnable state when the time elapses.

3. A thread can be made to wait until a particular event occur using the wait() method, which can be
run again using the notify( ) method.

Blocked state

• A thread is said to be in blocked state if it prevented from entering into the runnable state and
so the running state.
• The thread enters the blocked state when it is suspended, made to sleep or wait.
• A blocked thread can enter into runnable state at any time and can resume execution.

Dead State

• The running thread ends its life when it has completed executing the run() method which is
called natural dead.
• The thread can also be killed at any stage by using the stop( ) method.

Methods in Thread class

The Thread class has methods that can be used to control the behaviour of threads. There are two
constructors in thread class

• public Thread(String threadName)


• public Thread()

1. start() method

This method is used to start a new thread. When this method is called the thread enters the ready
to run mode and this automatically invokes the run( ) method .

Syntax void start( )

2. run() method

This method is the important method in the thread and it contains the statements that are to be
executed in our program. It should be overridden in our class, which is derived from Thread class.

Syntax
void run( )
{
//Statements implementing thread

3. sleep() method

This method is used to block the currently executing thread for the specific time.

Syntax

73
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
void sleep(time in milliseconds )

4. interrupted() method

This method returns true if the thread has been interrupted

Syntax

static boolean interrupted( )

5. isAlive() method

This method returns true if the thread is running.

Syntax

boolean isAlive( )

6. stop() method

This method is used to stop the running thread.

Syntax

void stop()

7. wait() method

This method is used to stop the currently executing thread until some event occurs

Syntax

void wait()

8. yield() method

This method is used to bring the blocked thread to ready to run mode.

Syntax

void yield()

9. setPriority( ) method

This method is used to set the priority of the thread.

Syntax

void setPriority(int P)

10. getPriority( ) method

74
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
This method is used to get the priority of the thread.

Syntax

int getPriority( )

Thread Priority

The JVM schedules using a preemptive , priority based scheduling algorithm. All Java threads have
a priority and the thread with he highest priority is scheduled to run by the JVM. In case two threads
have the same priority a FIFO ordering is followed.

All Java threads have a priority in the range [Link] priority is 10, lowest priority is [Link]
priority ie. priority by default is 5.

The Thread class has three static constants that define the priority of the thread.

Thread.MIN_PRIORITY - minimum thread priority = 1

Thread.MAX_PRIORITY - maximum thread priority = 10

Thread.NORM_PRIORITY - normal thread priority = 5

Whenever a new Java thread is created it has the same priority as the thread which created
[Link] priority can be changed by the setpriority() method.

Syntax:
void setPriority(int P)
The getPriority( ) method is used to get the priority of the thread.

Syntax

int getPriority( )

Thread Scheduling

Execution of multiple threads in some order on a single CPU system is called scheduling. Java uses
fixed-priority scheduling algorithms to decide which thread to execute the thread with the highest
priority runs first. If another thread with a higher priority is started, Java makes the lower priority
thread wait . If more than one thread exists with the same priority, Java quickly switches between them
in Round-Robin Fashion BUT only if the operating system uses time-slicing.

The above act as a guide to scheduling however the actual implementation depends on the Operating
System. Most operating systems use one of two scheduling methods Preemptive scheduling or Time
slicing.

In preemptive scheduling the highest priority thread continues to run until it dies, waits, or is
preempted by a thread of higher priority . In time slicing a thread runs for a specific time and then enters
the runnable state; at which point the scheduler decides wether to return to the thread or schedule a
different thread.

75
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Example :
Let T1, T2, T3, ……….,T10 be different threads . Let their priorities be
T1 -10 T6 -10
T2 -8 T7 -8
T3 -10 T8 -6
T4 -7 T9 -6
T5 -9 T10 -2

The table below shows the scheduling of the above threads.

Thread Synchronization

• In multithreaded application, multiple threads might access the data and call methods
simultaneously and this may create problems such as violation of data and unpredictable result.
These problems are referred to as concurrency problems.

• Synchronization is the technique that can be used to overcome the concurrency problem that
may arise when two or more threads need to access the shared resources.

• Java uses the concept of semaphores (also called monitors) for synchronization. This is similar
to a lock. Whenever a thread is making an attempt to use shared resources, it will lock the
resource (if it is free) and then after using, it will release (open the lock ) the resource.

• The keyword synchronized in Java is used for synchronization. This keyword can be used in two
ways ie., a method can synchronized or a block of code can be synchronized.

76
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES

Applets

Applets
The incredible momentum enjoyed by the Java programming language can largely be attributed to
Java applets. Applets are a special type of Java application; they are embedded within a HyperText
Markup Language (HTML) document. Applets provide an ideal way to give life to a web page. Since the
HyperText Markup Language is just that-a text markup language, the medium can eventually be
limiting-especially to those who have a development background.

Working of Java Applet


Java applets like Java programs consist of one or more class definitions. Once compiled, these
classes are stored as files with a .class extension and they consist of Java bytecode. Java bytecode is
created by a Java-compatible compiler. Unlike Java applications that typically are executed by a Java-
compatible interpreter, applets are executed within a Java-enabled web browser such as Netscape
Navigator 2.x,Internet Explorer and later that includes an integrated bytecode interpreter. Applets are
embedded within an HTML document via the APPLET tag that references the Java applet's compiled
.class file.

Types of Applets:
Web pages can contain two types of applets which are named after the location at which they are
stored.

1. Local Applet
2. Remote Applet
77
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Local Applets
A local applet is one that is stored on your own computer system. When your Web page must find
a local applet, it doesn't need to retrieve information from the Internet-in fact, your browser doesn't
even need to be connected to the Internet at that time. As shown in the below listing, a local applet is
specified by a path name and a file name.
Local applets are stored on and loaded from your computer system
Specifying a Local Applet (Listing 1).

<applet
codebase="tictactoe"
code="[Link]"
width=120
height=120>
</applet>

In the above listing , the codebase attribute specifies a path name on your system for the local
applet, whereas the code attribute specifies the name of the byte-code file that contains the applet's
code. The path specified in the codebase attribute is relative to the folder containing the HTML
document that references the applet.

Remote Applets
A remote applet is one that is located on another computer system . This computer system may be
located in the building next door or it may be on the other side of the world-it makes no difference to
your Java-compatible browser. No matter where the remote applet is located, it's downloaded onto your
computer via the Internet. Your browser must, of course, be connected to the Internet at the time it
needs to display the remote applet.
Remote applets are stored on another system and are down-loaded onto your computer via the
Internet.
To reference a remote applet in your Web page, you must know the applet's URL (where it's located
on the Web) and any attributes and parameters that you need to supply in order to display the applet
correctly. If you didn't write the applet, you'll need to find the document that describes the applet's
attributes and parameters. This document is usually written by the applet's author. the below
listing shows how to compose an HTML <applet> tag that accesses a remote applet.
Specifying a Remote Applet (Listing 2)

<applet>
codebase="[Link]
code="[Link]"
width=120
height=120>
</applet>

The only difference between Listing 1 and Listing 2 is the value of the codebase attribute. In the
first case, codebase specifies a local folder, and in the second case, it specifies the URL at which the
applet is located.

Applet Life Cycle

Applet Life Cycle


Applet runs in the browser and its lifecycle method are called by JVM at its birth, its death and when
it is momentarily away.
78
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Every Applet can be said to be any of the following state
1. New Born state
2. Running state
3. Idle state (may or may not)
4. Dead state
The following figure represents the life cycle of the Applet

New Born State

• The life cycle of an applet is begin on that time when the applet is first loaded into the browser
and called the init() method.
• The init() method is called only one time in the life cycle on an applet.
• The init() method is basically called to read the PARAM tag in the html file.
• The init () method retrieve the passed parameter through the PARAM tag of html file using get
Parameter() method .
• All the initialization such as initialization of variables and the objects like image, sound file are
loaded in the init () method .
• After the initialization of the init() method user can interact with the Applet

Syntax:

public void init()


{
Statements
}

Running State

• After initialization, this state will automatically occur by invoking the start method of applet
class which again calls the run method and which calls the paint method.
• The running state also occurs from idle state when the applet is reloaded.
• This method may be called multiples time when the Applet needs to be started or restarted.
• For Example if the user wants to return to the Applet, in this situation the start Method() of an
Applet will be called by the web browser and the user will be back on the applet.
• In the start method user can interact within the applet.

Syntax:

79
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
public void start()
{
Statements
}
Idle State

• The idle state will make the execution of the applet to be halted temporarily.
• Applet moves to this state when the currently executed applet is minimized or when the user
switches over to another page.
• At this point the stop method is invoked.
• From the idle state the applet can move to the running state.
• The stop() method can be called multiple times in the life cycle of applet Or should be called at
least one time.
• For example the stop() method is called by the web browser on that time When the user leaves
one applet to go another applet

Syntax:

public void stop()


{
Statements
}

Dead State

• When the applet programs terminate, the destroy function is invoked which makes an applet to
be in dead state.
• The destroy() method is called only one time in the life cycle of Applet like init() method.

Syntax:

public void destroy()


{
Statements
}
Display State

• The applet is said to be in display state when the paint method is called.
• This method can be used when we want to display output in the screen.
• This method can be called any number of times.
• paint() method is must in all applets when we want to draw something on the applet window.
• paint() method takes Graphics object as argument

Syntax:

public void paint(Graphics g)


{
Statements
}

Creating and Executing an Applet


80
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
An applet is a Java program that runs under a Java-compatible browser such as Netscape or HotJava.
This feature allows users to display graphics and to run programs over the Internet via the WWW
relatively easily. An applet allows web documents to be both animated and interactive!

Creating and Executing applet

Step 1: Import applet package and awt package


To create an applet, you must import the Applet class. This class is in the [Link] package
The Applet class contains code that works with a browser to create a display window.
We also need to import the [Link] package. The "awt” stands for “Abstract Window Toolkit”. The
[Link] package includes classes for:

• Drawing lines and shapes


• Drawing letters
• Setting colors
• Choosing fonts etc.

Step 2: Extend the Applet class


Then, a class must be defined that inherits from the class [Link]. The Applet class is the
standard class inherited for writing applets. It contains the methods to paint to the screen and the
window. The inherited class must be declared public
Step 3: Override the paint method if you want to draw
The paint method needs the Graphics object as its parameter.
public void paint(Graphics g) { … }
public says that anyone can use this method. void says that it does not return a result. A Graphics
(short for “Graphics context”) is an object that holds information about a painting. It remembers what
color you are using. It remembers what font you are using
Syntax:

import [Link].*;
import [Link].*;
publicclass MyApplet extends Applet
{
publicvoid paint(Graphics g)
{
//Statements
}
}

where Myapplet is the name of the class.


Save the class with .java extension.

Step 4: Compiling the Program


Once you have saved your program, you need to compile it using the Java compiler. At your
command line, enter the command "javac [Link]". This command will compile your code so
that you now have a [Link] file. If you receive any error messages, look back at the above
code and make the necessary corrections.
Step 5: Creating the HTML document
To run the applet we need to create the HTML document. The BODY section of the HTML document
has a tag called APPLET that you can use to run the applet.
The HTML looks something like this:
81
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
<HTML>
<BODY>

<APPLET CODE= "class file name"


WIDTH=width in pixels
HEIGHT=height in pixels>
</APPLET>

</BODY>
</HTML>
Save the file with .html extension.
Step 6:Running an applet
The applet can be run in two ways
1. By using appletviewer
To run the appletviewer utility type appletviewer [Link]
2. By running in web browser.
In the web browser bar give the full address of your html file.

Graphics Class

The Graphics class is the class used to allow a component to draw onto itself. The Graphics class is
located in the [Link] package. To use the Graphics class, you have to pass a Graphics object as
argument to paint() method.
The Graphics class provides the framework for all graphics operations within the AWT. It plays two
different, but related, roles. First, it is the graphics context. The graphics context is information that will
affect drawing operations. This includes the background and foreground colors, the font, and the
location and dimensions of the clipping rectangle (the region of a component in which graphics can be
drawn). Second, the Graphics class provides methods for drawing simple geometric shapes, text, and
images to the graphics destination. All output to the graphics destination occurs via an invocation of
one of these methods.

Coordinate System
Note that the basic AWT coordinate system for the Graphics context methods goes as follows:
* Origin (0,0) - top left hand corner
* x (in pixels) - increases towards the right
* Maximum x = width - 1
* y (in pixels) - increases towards the bottom
* Maximum y = height -1
We can obtain the dimensions of a component in two ways. The getSize() method returns an
instance of the Dimension class, which provides direct access to its height and width variables. The
component class includes the methods getHeight() and getWidth() so you can obtain each of these
dimensions separately.
Negative values and positive values beyond the width and height of the drawing area do not cause
errors but are treated as valid coordinates (though, any drawing in those areas will be unseen, of

82
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
course.)

Basic Graphics Commands


1) setColor(Color c)

Set the current pen color, where c has several standard choices such as [Link], [Link],
[Link], etc.

2) drawLine(int x1, int y1, int x2, int y2)

Draw a line between points (x1,y1) and (x2,y2)

3) drawRect (int x, int y, int width, int height)


Draws a rectangle, (x,y) are the coordinates of the top left corner, the bottom right corner will
be at (x+width,y+height)

4) fillRect (int x, int y, int width, int height)

Draws (fills) a rectangle, (x,y) are the coordinates of the top left corner, the bottom right corner
will be at (x+width,y+height).

5) drawOval (int x, int y, int width, int height)


Draws an oval bounded by the rectangle specified by these parameters.

6) fillOval (intx, int y, int width, int height)

Draws (fills) an oval bounded by the rectangle specified by these parameters.

7)draw3DRect (int x, int y, int width, int height, int arcWidth, boolean raised)

Draws a rectangle with shaded sides that provide a 3-D appearance.

8) fill3DRect (int x, int y, int width, int height, boolean raised)

Draws (fills) a rectangle with shaded sides that provide a 3-D appearance.

9) drawRoundRect (int x, int y, int width, int height, int arcWidth, int arcHeight)

10) fill3DRect (int x, int y, int width, int height, int arcWidth, int arcHeight)

Draws (fills) a rectangle with rounded corners.

11) drawArc(int x,int y,int width, int height, int startAngle, int arcAngle)

An arc is formed by drawing an oval between a start angle and a finish angle. The start angle is
measured from the positive x-axis and is expressed in degrees. The arc angle is expressed in
degrees from the start angle. Angles extend from the center of the bounds box.

12) drawPolyline (int[] x, int[] y, int N)

Draws lines connecting the N points given by the x and y arrays.


83
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
13) drawPolygon (int[] x, int[] y, int N)

Draws lines connecting the points given by the x and y arrays. Connects the last point to the first
if they are not already the same point.

The following figure shows some of the drawing primitives

Exception Handling

An exception is an abnormal event that arises during the execution of the program and disrupts
the normal flow of the program. Abnormality to do occur when your program is running. For example,
you might expect the user to enter an integer, but receive a text string; or an unexpected I/O error pops
up at runtime. Java has a built-in mechanism for handling runtime errors, referred to as exception
handling. This is to ensure that you can write robust programs for mission-critical applications.

Exception Handling
In java, when any kind of abnormal conditions occurs with in a method then the exceptions are
thrown in form of Exception Object i.e. the normal program control flow is stopped and an exception
object is created to handle that exceptional condition.
The method creates an object and hands it over to the runtime system. Basically, all the information
about the error or any unusual condition is stored in this type of object in the form of a stack. This object
created is called an exception object the process is termed as throwing an exception.

84
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
The mechanism of handling an exception is called catching an exception or handling an Exception
or simply Exception handling.

Advantages of Exception-handling in Java:


• Exception provides the means to separate the details of what to do when something out of the
ordinary happens from the main logic of a program.
• One of the significance of this mechanism is that it throws an exception whenever a calling
method encounters an error providing that the calling method takes care of that error.
• With the help of this mechanism the working code and the error-handling code can be
disintegrated. It also gives us the scope of organizing and differentiating between different error
types using a separate block of codes. This is done with the help of try-catch blocks.
• Furthermore the errors can be propagated up the method call stack i.e. problems occurring at
the lower level in the chain can be handled by the methods higher up the call chain.

Multiple catch blocks


Several types of exceptions may arise when executing the program. They can be handled by using
multiple catch blocks for the same try block. In such cases when an exception occur the run time system
will try to find match for the exception object from the parameters of the catch blocks in the order of
appearance. When a match is found corresponding catch block will be executed.

Steps in Handling Exception (try..catch)


The following are the tasks in handling exceptions
• Find the problem (Hit the exception)
• Inform that an error has occurred (Throw the exception)
• Receive the error (Catch the exception)
• Take corrective action (Handle the exception)
Finding the problem refers to identify the part of the program where the error may occur. That part
of the program has to be enclosed in try block and the catch block contains the codes that represent the
action to be taken when the error occurs.

Try_catch block
In Java exception handling is done with the help of try..catch block. The programmers can use the
try..catch block to handle the exceptions that suit their programs. This avoids abnormal termination of
the program.

Syntax
…..
…..
try
{
//Statements that may generate the exception
}
catch(exceptionclass object)
{
//Statements to process the exception

85
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
}
catch(exceptionclass object)
{
//Statements to process the exception
}
….
finally
{
//Statements to be executed before exiting exception handler
}
……

Try Block: Inside the try block we can include the statements that may cause an exception and throw
an exception.

Catch Block: The catch block contains the code that handles the exceptions and may correct the
exceptions that ensure normal execution of the program. Catching the thrown exception object from
the try block by the corresponding catch block is called throwing an exception. The catch block should
immediately follow the try block.
We can have multiple catch blocks for a single try block.

Finally Block: The finally block is always executed, regardless of whether or not an exception happens
during the try block, or whether an exception could be handled within the catch blocks. Since it always
gets executed, it is recommended that you do some cleanup here. Implementing the finally block is
optional.

Execution of try..catch blocks:


If no exception occurs during the running of the try-block, all the catch-blocks are skipped, and
finally-block will be executed after the try-block.
If one of the statements in the try-block throws an exception, the Java runtime ignores the rest of
the statements in the try-block, and begins searching for a matching exception handler. It matches the
exception type with each of the catch-blocks sequentially. If a catch-block catches that exception class
or catches a superclass of that exception, the statement in that catch-block will be executed. The
statements in the finally-block are then executed after that catch-block. The program continues into the
next statement after the try-catch-finally, unless it is pre-maturely terminated or branch-out.
If none of the catch-blocks matches, the exception will be passed up the call stack - if the method's
signature declares that this checked exception to be thrown; or the exception is an unchecked exception.
The current method terminates

Types of Exception Classes


• The base class for all Exception objects is [Link], together with its two subclasses
[Link] and [Link].
• The Error class describes internal system errors (e.g., VirtualMachineError, LinkageError) that
rarely occur. If such an error occurs, there is little that you can do and the program will be
terminated by the Java runtime.

86
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
• The Exception class describes the error caused by your program (e.g. FileNotFoundException,
IOException). These errors could be caught and handled by your program (e.g., perform an
alternate action or do a graceful exit by closing all the files, network and database connections).
There are three types of Exceptions:
1. Checked Exceptions
2. Unchecked Exceptions
3. Error

Exceptions:
These are the exceptions which occur during the compile time of the program. The compiler checks
at the compile time that whether the program contains handlers for checked exceptions or not. These
exceptionsm must be handled to avoid a compile-time error by the programmer. These exceptions
extend the [Link] class These exceptional conditions should be predicted and recovered
by an application. Furthermore Checked exceptions are required to be caught.
For example if you call the readLine() method on a BufferedReader object then the IOException
may occur or if you want to build a program that reads data using the method readLine() then the
method should have clode to handle the IOException.
Here is the list of checked exceptions.
• NoSuchFieldException
• InstantiationException
• IllegalAccessException
• ClassNotFoundException
• NoSuchMethodException
• CloneNotSupportedException
• InterruptedException

Unchecked Exceptions:
Unchecked exceptions are the exceptions which occur during the runtime of the program.
Unchecked exceptions are internal to the application and extend the [Link] that
is inherited from [Link] class. These exceptions cannot be predicted and recovered like
programming bugs, such as logic errors or improper use of an API. These type of exceptions are also
called Runtime exceptions that are usually caused by data errors, like arithmetic overflow, divide by
zero etc.
The most common unchecked exception is the ArithmeticException which occurs when something
tries to divide by zero.
Here is the list of unchecked exceptions.
• IndexOutOfBoundsException
• ArrayIndexOutOfBoundsException
• ClassCastException
• ArithmeticException
• NullPointerException
• IllegalStateException
• SecurityException

Error :
The errors in java are external to the application. These are the exceptional conditions that could not
be usually predicted by the application and also could not be recovered from. Error exceptions belong
to Error and its subclasses are not subject to the catch or Specify requirement. An Error indicates
87
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
serious problems that a reasonable application should not try to catch. Most such errors are abnormal
conditions.
Example for error are serious and unrecoverable exceptions like running out of memory, stack
overflow etc
Here is the list of unchecked exceptions
• IllegalAccessErrors
• NoSuchFieldError
• InternalError
• StackOverFlowError

Finally clause
• The code in the finally block will be executed even or not the exception arise inside the block of
code.
• The finally block is normally used for clean up activities like file closing, flushing buffers etc.
• The finally block is optional.

Example:
/* Finally block*/
class finallydemo
{
public static void main(String args[])
{
int a,b,c;
a=[Link](args[0]);
b=[Link](args[1]);

try
{
c=a/b;
[Link](a+" / "+b+"="+c);
}

catch(ArithmeticException e)
{
[Link]("Division by zero error occurred");
[Link](e);
}

finally
{
[Link]("Inside finally block");
}
}
}

throws Keyword
If a method is capable of causing an exception that it does not handle, it must specify this behaviour
so that callers of the method can guard themselves against that exception. When throws clause is used
try..catch block is not needed.
type method-name(paramlist) throws exception-list
88
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
{
//…..
}
throws clause lists the types of exceptions that a method might throw. It is necessary for all
exceptions, except those of type Error or RuntimeException, or any of their subclasses.
Example:
/* throws clause example */
import [Link].*;
class readip
{
public static void main(String args[]) throws IOException
{
int a;
String name;
DataInputStream din=new DataInputStream([Link]);
[Link]("Enter the name:");
name=[Link]();
[Link]("Enter the register number:");
a=[Link]([Link]());
[Link]("\nNAME:"+name);
[Link]("[Link]:"+a);
}
}

I/O Streams
The Java platform includes a number of packages that are concerned with the movement of data
into and out of programs. These packages differ in the kinds of abstractions they provide for dealing
with I/O (input/output).
The [Link] package defines I/O in terms of streams. Streams are ordered sequences of data that
have a source (input streams) or destination (output streams). The I/O classes isolate programmers
from the specific details of the underlying operating system, while enabling access to system resources
through files and other means.

A program uses an input stream to read data from a source, one item at a time:

A program uses an output stream to write data to a destination, one item at time:

89
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES

Streams are byte-oriented or character-oriented. Each type has input streams and output streams.

Byte-oriented streams: Used for general-purpose input and output. Data may be primitive data types
or raw bytes.
Character-oriented streams.:Specialized for character data. Transforms data from/to 16 bit Java
char used inside programs to UTF format used externally.

Byte Stream
Byte streams can be used to read or write bytes serially from an external device. All the byte streams
are derived from the abstract superclass InputStream and OutputStream,.

Character-stream class Description


Reader Abstract class for character-input streams
BufferedReader Buffers input, parses lines
LineNumberReader Keeps track of line numbers
CharArrayReader Reads from a character array
InputStreamReader Translates a byte stream into a character stream
FileReader Translates bytes from a file into a character stream
FilterReader Abstract class for filtered character input
PushbackReader Allows characters to be pushed back
PipedReader Reads from a PipedWriter
StringReader Reads from a String
Writer Abstract class for character-output streams
BufferedWriter Buffers output, uses platform's line separator
CharArrayWriter Writes to a character array
FilterWriter Abstract class for filtered character output
OutputStreamWriter Translates a character stream into a byte stream
FileWriter Translates a character stream into a byte file
PrintWriter Prints values and objects to a Writer
PipedWriter Writes to a PipedReader
StringWriter Writes to a String

90
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES

InputStream Class
[Link] is an abstract class that contains the basic methods for reading raw bytes of
data from a stream. Although InputStream is an abstract class, many methods in the class library are
only specified to return an InputStream

Character Streams
Character streams are like byte streams, but they contain 16-bit Unicode characters rather than
eight-bit bytes.
They are implemented by the Reader and Writer classes and their subclasses.
Readers and Writers support essentially the same operations as InputStreams and
OutputStreams, except that where byte-stream methods
operate on bytes or byte arrays, character-stream methods operate on characters, character arrays,
or strings.

Why use character streams?


• The primary advantage of character streams is that they make it easy to write programs that
are not dependent upon a specific character encoding, and are therefore easy to
internationalize.
• A second advantage of character streams is that theyare potentially much more efficient than
byte [Link] implementations of many of Java's original bytestreams are oriented around
byte-at-a-time read and write operations. The character-stream classes, in contrast,are oriented
around buffer-at-a-time read and writeoperations.

Files
The File class deals with the machine dependent files in a machine-independent manner i.e. it is
easier to write platform-independent code that examines and manipulates files using the File class. This
class is available in the [Link] package.

91
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
The [Link] is the central class that works with files and directories. The instance of this class
represents the name of a file or directory on the host file system.
When a File object is created, the system doesn't check to the existence of a corresponding
file/directory. If the file exist, a program can examine its attributes and perform various operations on
the file, such as renaming it, deleting it, reading from or writing to it.
It also maintains two system-dependent properties, for you to write programs that are portable:
1. Directory Separator: Windows systems use backslash '\' (e.g., "c:\jdk\bin\[Link]"), while
Unixes use forward slash '/' (e.g., "/usr/jdk/bin/[Link]"). This system-dependent property is
maintained in the static field [Link] (as String) or [Link]. (They failed to
follow the naming convention for constants, which was adopted in JDK 1.2.)
2. Path Separator: Windows use semi-colon ';' to separate paths (or directories) white Unixes use
colon ':'. This system-dependent value can be retrieved from static field [Link] (as
String) or [Link].
Constructors:
• File(path)
Create File object for default directory (usually where program is located).
• File(dirpath,fname)
Create File object for directory path given as string.
• File(dir, fname)
Create File object for directory.
Methods that are used with the file object to get the attribute of a corresponding file
• [Link]()
Returns true if file exists.
• [Link]()
Returns true if this is a normal file.
• [Link]()
Returns true if "f" is a directory.
• [Link]()
Returns name of the file or directory.
• [Link]()
Returns true if file is hidden.
• [Link]()
Returns time of last modification.
• [Link]()

92
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Returns number of bytes in file.
• [Link]()
Returns path name.
• [Link]()
Deletes the file.
• [Link](f2)
Renames f to File f2. Returns true if successful.
• [Link]()
Creates a file and may throw IOException.
• [Link]()
Makes the file read only.

AWT Components and Event Handling

Java's Abstract Windowing Toolkit provides many of the user interface objects we find in the Windows
environment. These are called "Components" of the Java AWT. There are a wide variety of AWT
components, ranging from text labels and buttons to selection lists, windows and [Link] common
components from the [Link] package are given below.
Label
Labels are great for providing user prompts, and for displaying information that should not be modified
by users.
Button
Buttons are useful when an application must recieve specific instructions from the user before
proceeding. For example, when a user must enter data, and then wants to perform a task, a button can
be used to instruct the applet / application to proceed when the data entry is complete.
Choice
Choice components take up very little screen space, and can present the user with a series of choice
from which a single selection can be made.
List
List components fulfill much the same functionality as choice components. Items can be added, and the
currently selected item can be returned. However, they take up more space than a choice component.
This can be useful at times, however, as the items can be presented to the user, without he or she having
to actually click on the component to see. Furthermore, multiple selections are allowable with the list
component (though this feature must be enabled).
TextField
Textfield components are useful for obtaining short pieces of information from users. They are limited
to single line input (for multiple lines, use a TextArea instead). Whenever a user types data into a text
field, and hits enter or changes focus, the textfield will generate an event.
93
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
TextArea
Textarea components are useful for getting a large amount of data from a user, or for displaying a large
amount of data that is free to be modified. They take up more screen real estate than textfields, but can
conserve quite a lot of room because they have support for scrollbars.
Button
• The Button class is used to create push buttons.
• The buttons responds to ActionEvent when the Button is clicked.
constructors:
• public void Button()
Creates a button with no text label.
• public void Button(String)
Creates a button with the given string as label.
Methods of Button class
• String getLabel()
Gets the label of this button.
• void setLabel(String label)
Sets the button's label to be the specified string.
• void setActionCommand(String)
Sets the command name for the action event fired by this button. By default this action command
is set to match the label of the button.
• String getActionCommand()
Returns the command name of the action event fired by this button. If the command name is null
(default) then this method returns the label of the button.
• void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this button. Action events occur
when a user presses or releases the mouse over this button. If l is null, no exception is thrown and
no action is performed
Example:
// Example for Label and Button with ActionListener
import [Link].*;
import [Link].*;
import [Link].*;
/* <applet code=LabelButton width=200 height=200></applet>*/
public class LabelButton extends Applet implements ActionListener
{
Label l;
Button b;
public void init()
{
l=new Label("Hello from Label");
b=new Button("Click me");
add(l);
add(b);
[Link](this);
}
public void actionPerformed(ActionEvent e)
{
[Link]("Button is clicked");
}
}
Output:
94
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES

Checkbox

• A check box is a graphical component that can be in either an "on" (true) or "off" (false) state.
Clicking on a check box changes its state from "on" to "off," or from "off" to "on."
• The checkbox generates Itemevent when the CheckBox is selected or deselected.
• More than one Checkbox can be in the “on” state at a time.
• By default check boxes are unchecked when created.

Checkboxgroup

• The CheckboxGroup class is used to group together a set of Checkbox buttons.


• Exactly one check box button in a CheckboxGroup can be in the "on" state at any given time.
Pushing any button sets its state to "on" and forces any other button that is in the "on" state into
the "off" state.

Constructor
public CheckboxGroup()
Creates a new instance of CheckboxGroup.
Constructors of Checkbox

• Checkbox()

Creates a check box with no label.

• Checkbox(String)

Creates a check box with the specified label.

• Checkbox(String, boolean)

Creates a check box with the specified label and sets the specified state.

• Checkbox(String, boolean, CheckboxGroup)

Constructs a Checkbox with the specified label set to the specified state and in the specified check
box group.

• Checkbox(String, CheckboxGroup, boolean)

95
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Creates a check box with the specified label in the specified check box group and set to the
specified state.

Example:
Checkbox and ItemEvent Demo
/*RadioButton using Checkbox demo */

/* <applet code="[Link]" width="300" height="150"></applet> */


import [Link].*;
import [Link].*;
import [Link].*;
publicclass DemoradioButton extends Applet implements ItemListener
{

Checkbox d1,d2,d3;
CheckboxGroup cg=newCheckboxGroup();
TextField t1=newTextField(30);
publicvoid init()
{

setBackground(new Color(219,253,226));
d1=newCheckbox("IT",true,cg);
d2=newCheckbox("CE",false,cg);
d3=newCheckbox("ECE",false,cg);
add(new Label("Select the department"));
add(d1);
add(d2);
add(d3);
add(t1);
[Link]("I Study in IT");
[Link](this);
[Link](this);
[Link](this);

}
publicvoid itemStateChanged(ItemEvent e)
{
String msg="I study in ";
if([Link]())
msg=msg+[Link]();
elseif([Link]())
msg=msg+[Link]();
else
msg=msg+[Link]();
[Link](msg);

}
}

Output:

96
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES

Choice
• The Choice class presents a pop-up menu of choices. The current choice is displayed as the title
of the menu.
• Only one item can be selected from the choice.
• The choice object responds to ItemEvent when an item is selected.
Constructor
• public Choice()
Constructs a new Choice.

Example:
/* Choice Demo */
/*<applet code = "[Link]" width = 250 height = 150></applet> */

import [Link].*;
import [Link].*;
import [Link].*;

public class Mycombo extends Applet implements ItemListener


{

Choice c1;
Label l1;
Color col=[Link];
public void init()
{
setBackground(col);
l1=new Label("Select the background color from the Choice");
c1 = new Choice();
[Link]("Red");
[Link]("Green");
[Link]("Yellow");
[Link]("Pink");
[Link](this);
add(l1);
add(c1);
}

public void itemStateChanged(ItemEvent e)


{
String s = (String)[Link]();
if(s=="Red")
col=[Link];
else if(s=="Green")
col=[Link];
97
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
else if(s=="Yellow")
col=[Link];
else if(s=="Pink")
col=[Link];
setBackground(col);
[Link](col);
}

}
Output:

Event Handling
In life, we encounter events that force us to suspend other activities and respond to them
immediately. In Java, events represent all activity that goes on between the user and the application.
Java’s Abstract Windowing Toolkit (AWT) communicates these actions to the programs using events.
When the user interacts with a program let us say by clicking a command button, the system creates an
event representing the action and delegates it to the event-handling code within the program. This code
determines how to handle the event so the user gets the appropriate response.
In java the event are processed based on the Event Delegation Model. The main elements of JDK
event delegation model are
• Event classes
• Event source objects
• Event listener objects

Event Source: An event source is the object that generated the event. Example if you click a button an
ActionEvent Object is generated. The object of the ActionEvent class contains information about the
event.
3. Event-Handler: Is a method that understands the event and processes it. The event-handler method
takes the Event object as a parameter. Java uses Event-Delegation Model :with JDK1.1 onwards; you can
specify the objects that are to be notified when a specific event occurs. If the event is irrelevant, it is
discarded. The four main components based on this model are Event classes, Event Listeners, Explicit
event handling and Adapters. Let us take a closer look at them one by one.
Event Classes:
When the user interacts with the application by clicking a mouse button or pressing a key an event is
generated. The Operating System traps this event and the data associated with it. For example, info
about time at which the event occurred, the event types (like keypress or mouse click). This data is then
passed on to the application to which the event belongs. In Java, events are represented by objects,
which describe the events themselves. And Java has a number of classes that describe and handle
different categories of [Link] EventObject class is at the top of the event class hierarchy. It belongs
to the [Link] package. While most of the other event classes are present in [Link] package.
98
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
The getSource() method of the EventObject class returns the object that initiated the event. The getId
() method returns the nature of the event. For example, if a mouse event occurs, you can find out
whether the event was click, a press, a move or release from the event object. AWT provides two
conceptual types of events: Semantic and low-level events.
Event Listeners:
An event listener is an object to which a component has delegated the task of handling a particular kind
of event. In other words, if you want an object in your program to respond to another object which is
generating events, you must register your object with the event generating object, and then handle the
generated events when the come.
When a component experiences input, an event of an appropriate type is constructed; The event is then
passes as an argument to a method call on the listener.
Event listeners implement appropriate listener interfaces which contain methods appropriate for
handling the particular kind of event at hand.

The primary design goals of the new model in the AWT are the following:
• Simple and easy to learn
• Support a clean separation between application and GUI code
• Facilitate the creation of robust event handling code which is less error-prone (strong compile-
time checking)
• Flexible enough to enable varied application models for event flow and propagation
• For visual tool builders, enable run-time discovery of both events that a component generates
as well as the events it may observe
• Support backward binary compatibility with the old model

99

You might also like