Java Notes1
Java Notes1
TABLE OF CONTENTS
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 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.
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.
• 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.
• 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
The main feature of java is its platform independent, Java developers have identified the
following as the features of their language
3
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
• Robust
• Secure
• High Performance
• Multithreaded and Interactive
• Dynamic and Extensible
Platform Independent:
• 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
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
• 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.
• 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
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
The Java application launcher tool (java) uses the Java virtual machine to run your application.
• You can launch the Notepad editor from the Start menu by selecting Programs > Accessories
> Notepad.
• In a new document, type in the following code:
• Save the code in file [Link] and note the file name and the class name should be same.
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\
set path=C:\jdk1.3\bin
• Now you are ready to compile. At the prompt, type the following command and press Enter.
javac [Link]
java Sample
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:
**---------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
• 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:
Examples:
These identifiers are valid:
MyClass
$amount
totalGrades;
TotalGrades;
TAX_RATE
one
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" ""
11
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Separators
• 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 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:
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.
For example
Forexample
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.
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:
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
Example:
3) Character constant
4) String Constants:
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
15
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Where:
Important points:
2. The values assigned to a variable correspond to its type. Statements below represent
assignment of values to a variable.
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;
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
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
Scope of Variables
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
• member variable
• local variable
• method parameter
• exception handler parameter
17
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Member variable
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.
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;
* 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
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
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
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"?:"
It is basically used as an short hand for simple if..else
20
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
The "?:" 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 x= (a>b) ? a : b;
In the above example the value of x is assigned the value of b since the
condition is false.
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:
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.
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
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
Example:
class X {
int i, j;
}
class Y {
int i, j;
}
class Z extends X {
int k;
}
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]);
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
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.
for(int i=0;i<7;i++)
{
[Link]("i="+i);
}
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:
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:
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:
Example:
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:
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:
28
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
class ifladder
{
public static void main(String args[])
{
int avg;
avg=[Link](args[0]);
if(avg>79)
[Link]("Distinction");
else if(avg>59)
[Link]("First Class");
else if(avg>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
Syntax:
while(condition)
{
statement(s);
}
next_statement;
Execution:
30
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
When program execution reaches a while statement, the following events occur:
Flow chart:
Example:
}
}
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:
Example:
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:
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:
class ForDemo
{
public static void main(String[] args)
{
for(int i=1; i<=5; i++)
{
[Link]("Value of i :" + i);
}
}
}
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:
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];
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.
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.
• One-dimensional arrays
• Two-dimensional arrays
• Multidimensional Arrays
One-dimensional Arrays
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.
1. Declaring an array
2. Allocating memory
35
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Syntax 1:To declare a one-dimensional array
or
For e.g.
For e.g.
You can declare and allocate memory to a user-defined array in a single statement.
Syntax
for e.g
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;
• In this case we need not explicitly use new operator to allocate size of the array, it is
automatically assumed.
Example:
for(int i=0;i<test_scores.length;i++)
[Link](test_scores[i]);
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.
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:
Initialilzation of 2D Array
Example:
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<3;i++)
{
for(int j=0;j<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
Creating Vectors
Whenever you start working with vectors in Java, it is convenient to first import the Vector class
from the [Link] package.
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.
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 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
+ concatenation
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” ;
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?.
String class has overloaded constructors. Following are some of the constructors of String class
1) String( );
2) String(String value)
Example:
3) String(char char[]);
Example:
Initializes the string with the characters from the given character array starting from the given
index and adding number of characters.
Example:
1. s. concat(String s2)
Concatenates one string onto another. Appends the String s2 to the String s.
Example:
[Link](str3);
2. [Link]()
Example:
43
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
String str1 = new String("Hello ");
int n=[Link]();
[Link]("Length="+n);
3. [Link](char, char)
Example:
[Link](newstr);
4. [Link]()
5. s. toUpperCase()
Example:
The output is
Upper:THIS IS MIXED CASE
Lower:this is mixed case
6. trim()
Example:
44
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
The output is
The length before trim :10
The length after trim :6
1. s. charAt(int)
Example:
3. s. substring(int i)
Example:
4. substring(int i, int k)
Example:
//negative differences
//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 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.
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
1. StringBuffer()
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]()
2. length()
3. [Link](int index)
The specified character of the sequence currently represented by the string buffer, as indicated by
the index argument, is returned.
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.
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)
Note that the StringBuffer class has got many overloaded ‘append’ methods which can be used
based on the application need.
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
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
Example:
class Rectangle
{
int len,bre;
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
<access apecifier> returntype methodname (datatype arg1, datatype arg2,...., datatype arg3)
{
//Method Body
[return statement]
}
</access>
Creating Objects
• 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
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
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:
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
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.
• Single Inheritance
• Multilevel Inheritance
53
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
Properties of Inheritance
• 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.
• 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.
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:
Example:
Types of Inheritance
Based on the number of super class and subclass we can classify inheritance into several types.
They are
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
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:
/* 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 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:
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,.
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.
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.
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:
Example:
interface one
{
int x=10,y=16;
public void display();
}
Note:
Syntax:
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:
/* 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 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.
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.
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.
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
Once defined we could use myVector object to access the members of Vector class.
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
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
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
A naming convention is a rule to follow as you decide what to name your identifiers (e.g. class, package,
variable, method, etc..).
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.
The remainder of a package name should consist of one or more components describing the package.
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:
• Calling the package from any applications .The classes in the package are loaded into a Java
application by using:
import<package name>.* ;
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
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.
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)
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
Definition of thread
• 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.
• 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
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
Syntax:
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:
One way of creating thread is to extend the Thread class. The steps to create a thread using thread class
is as follows:
Syntax:
4. Call the start( ) method of class Thread. The start( ) calls run() method.
Syntax:
Thread States:
71
FAMEBOX SOFTWARE & ANIMATION COLLEGE JAVA NOTES
4. Blocked state
5. Dead 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.
• 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
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.
The Thread class has methods that can be used to control the behaviour of threads. There are two
constructors in thread class
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 .
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
Syntax
5. isAlive() method
Syntax
boolean isAlive( )
6. stop() method
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
Syntax
void setPriority(int P)
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.
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
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.
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.
• 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:
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:
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:
• 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:
import [Link].*;
import [Link].*;
publicclass MyApplet extends Applet
{
publicvoid paint(Graphics g)
{
//Statements
}
}
</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.)
Set the current pen color, where c has several standard choices such as [Link], [Link],
[Link], etc.
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).
7)draw3DRect (int x, int y, int width, int height, int arcWidth, 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)
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.
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.
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.
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.
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,.
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.
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.
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
Constructor
public CheckboxGroup()
Creates a new instance of CheckboxGroup.
Constructors of Checkbox
• Checkbox()
• Checkbox(String)
• Checkbox(String, boolean)
Creates a check box with the specified label and sets the specified state.
Constructs a Checkbox with the specified label set to the specified state and in the specified check
box group.
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 */
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].*;
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);
}
}
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