[Go to site: main page, start]

0% found this document useful (0 votes)
3 views123 pages

Java Notes

The document provides a comprehensive overview of Java programming, covering its object-oriented principles, evolution, and key features. It discusses fundamental concepts such as classes, objects, inheritance, and polymorphism, as well as Java's history and its differences from C and C++. Additionally, it highlights Java's applications in various domains, including web development and mobile programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views123 pages

Java Notes

The document provides a comprehensive overview of Java programming, covering its object-oriented principles, evolution, and key features. It discusses fundamental concepts such as classes, objects, inheritance, and polymorphism, as well as Java's history and its differences from C and C++. Additionally, it highlights Java's applications in various domains, including web development and mobile programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA PROGRAMMING

UNIT I: Fundamentals of Object-Oriented Programming: Object-Oriented Paradigm –


Basic Concepts of Object-Oriented Programming – Benefits of Object-Oriented
Programming – Application of Object-Oriented Programming. Java Evolution: History –
Features – How Java differs from C and C++ – Java and Internet – Java and www –Web
Browsers. Overview of Java: simple Java program – Structure – Java Tokens – Statements
– Java Virtual Machine.

UNIT II: Constants, Variables, Data Types - Operators and Expressions – Decision
Making and Branching: if, if...else, nested if, switch, ? : Operator - Decision Making and
Looping: while, do, for – Jumps in Loops - Labeled Loops – Classes, Objects and
Methods.

UNIT III: Arrays, Strings and Vectors – Interfaces: Multiple Inheritance – Packages:
Putting Classes together – Multithreaded Programming.

UNIT IV: Managing Errors and Exceptions – Applet Programming – Graphics


Programming.

UNIT V: Managing Input / Output Files in Java : Concepts of Streams- Stream Classes –
Byte Stream classes – Character stream classes – Using streams – I/O Classes – File Class
– I/O exceptions – Creation of files – Reading / Writing characters, Byte-Handling
Primitive data Types – Random Access Files.

TEXTBOOK:
1. Programming with Java – A Primer - E. Balagurusamy, 3rd Edition, TMH.

REFERENCE BOOKS:
1. The Complete Reference Java 2 - Patrick Naughton & Hebert Schildt, 3rd Edition, TMH
2. Programming with Java – John R. Hubbard, 2nd Edition, TMH.
UNIT -I

FUNDAMENTALS OF OBJECT ORIENTED PROGRAMMING:

I. Object oriented paradigm:

It is based upon objects(having both data and methods) that aims to incorporate the
advantages of modularity and reusability, objects, which are usually instances of classes, are used
to interact with one another to design applications and computer programs.

• Data
• Method()
• Object
• Class

Data : information is called Data.

Method() : user can done a task from the object is called method. It defined as function.

Real time entity which consists of properties and method.

Group of object is called class.

Object = Data + Methods

Object that provides a way of module programs by creating partitioned memory area for both
data and functions that can be used as templates for creating modules on demand.

Object:

Object is real time entity which consists of methods and properties to make a particular
type of data.

Eg. Car, dog, Table etc..,

Class:

A class is a group of objects. It determines how an object will behave and what the object
will contain.

Method Method

Dat
a

Method
Method
II. OOPS concept in Java:

Java – Just Another Virtual Approach

There are 6 concepts :

1. Object
2. Class
3. Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism

1. Object:

Object is real time entity which consists of methods and properties to make a particular
type of data.

Eg. Car, dog, Table etc..,

2. Class:

A class is a group of objects. It determines how an object will behave and what the object
will contain.

3. Abstraction:

Abstraction directs to the procedure of representing essential features without including


background details.

It shows only essential details. It hide implement details.

[Link]:

Encapsulation is packing or combine the properties and method into a single components.

5. Inheritance :

Inheritance is a mechanism where in a now class is derived from an existing. It has parent
class and child class. Parent class is also called base class. Child class is also called derived
class.

Inheritance has 5 types

• Single inheritance
• Multiple inheritance
• Multilevel inheritance
• Hybrid inheritance
• Hierarchical inheritance
• Multipath inheritance
6. Polymorphism:

Polymorphism is the ability of an object to take on many forms. It allows the same
function to act differently in different classes.

Types of polymorphism

1. Compile time polymorphism or method overloading or static binding


2. Runtime polymorphism or method overriding or dynamic binding

When a type of the object is determined at a compiled time(by the compiler), it is known
as static binding.

When a type of the object is determined at run-time, it is known as dynamic binding.


Compile time and Run time:

Compile time:

Compile time may refer to any of the following.

• The operations performed by the compiler such as syntactic and semantics


analysis.
• The pre runtime assessment of the programme behavior.

Run time:

• When a program syntactically correct that the program was executed in the
computer system.
• That time only the memory was allocated that dynamic memory allocation.
• It is implementation of polymorphism

Dynamic Binding:

Binding refer to the linking of a procedure call to the code to be excuted in response to
the call.

Message communications

It consists of a set of object that communicate with each others.

Basic steps.

• Creating classes that define object and their behavior.


• Creating objects from class definitions.
• Establishing communication among object.

E.g: [Link](name);

Employee – is an object

Salary – is a message

Name – is an information
III. BENEFITS or ADVANTAGES OF OOPS:

OOPs offers several benefits to both program designer and the user.

Object orientation contribute to the solution of many problems associated with the
development and quality of the software product.

• Through inheritance we can eliminate redundant code and extend the use of existing
classes.
• It is possible to have multiple objects to co-exist without any interference.
• Object-oriented systems can be easily upgraded from small to large system.
• Software complexity can be easily managed.
• Reusability
• Scalability
• Maintainability
• Safe and secure
• Easily accessible
• Robust
• Mobile development
• Applet
• User friendly
• Flexibility.

IV. Application of oops :

• Application of oops are beginning to gain importance in many area.


• The most popular application of object oriented programming upto now has been in the
area of user interface design such as windows.
• There are hundreds of windowing system developed using oop techniques.
• Real business systems are often much more complex and contain many more objects
with complicated attributes and methods.

Applications:

• Real time systems


• Simulation and modeling
• Object oriented database
• Hyper text, hyper media and exprtext
• AI(Artificial Intelligence) and expert system.
• Neural networks and parallel program
• Decision support and office automation systems(computer aided design)
• CIM /CAD/ CAD system – CIM-Common Information System

Java Evolution

Java History

The history of Java is very interesting. Java was originally designed for interactive
television, but it was too advanced technology for the digital cable television industry at the time.
The history of Java starts with the Green Team. Java team members (also known as Green Team),
initiated this project to develop a language for digital devices such as set-top boxes, televisions,
etc. However, it was suited for internet programming. Later, Java technology was incorporated by
Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented,
Interpreted, and Dynamic". Java was developed by James Gosling, who is known as the father of
Java, in 1995. James Gosling and his team members started the project in the early '90s.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc.
There are given significant points that describe the history of Java.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991. The small team of sun engineers called Green Team.
2) Initially designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.

Why Java named "Oak"?


5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like
the U.S.A., France, Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
Why Java Programming named "Java"?

7) Why had they chosen java name for Java language? The team gathered to choose a new
name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They
wanted something that reflected the essence of the technology: revolutionary, dynamic, lively,
cool, unique, and easy to spell and fun to say.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java
was so unique, most of the team members preferred Java than other names.
8) Java is an island of Indonesia where the first coffee was produced (called java coffee). It is
a kind of espresso bean. Java name was chosen by James Gosling while having coffee near
his office.
9) Notice that Java is just a name, not an acronym.
10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 released in(January 23, 1996). After the first release of Java, there have been
many additional features added to the language. Now Java is being used in Windows
applications, Web applications, enterprise applications, mobile applications, cards, etc.
Each new version adds the new features in Java.
Java Version History

Many java versions have been released till now. The current stable release of Java is Java SE 10.

1. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan 1996)
3. JDK 1.1 (19th Feb 1997)
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
6. J2SE 1.4 (6th Feb 2002)
7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
10. Java SE 8 (18th Mar 2014)
11. Java SE 9 (21st Sep 2017)
12. Java SE 10 (20th Mar 2018)

V. JAVA EVOLUTION :

• Object oriented programming language developed by sun micro system of USA in


1991.
• Originally called by Oak James Gostling
• Java was designed for the development of software for consumer electronic devices
like TV, VCR,Theater and each other electronic machines.
• The language simple,portable and highly reliable.
• The java team where included Patrick naughton discovered that the existing
languages like c and c++ had limitations in terms of both reliability and portability.

YEAR DEVELOPMENT
1990 Sun Microsystems decided to develop special software that
could be used to manipulate consumer electronic devices.
Ateam of sun micro systems programmers headed by James
Goastling was formed to under take this task.
1991 The team announced a new language named “Oak”.
1992 The team known as green project team by sun demonstrated
the application of their new language to control a tut of home
appliances using a hand held device with a tiny touch
sensitive screen.
1993 The world wide web (www) appeared on the internet and
transformed the text based internet into a graphical rich
environment.
1994 The team developed a web browser called “Hot Java” to
locate and run applet programs on internet.
1995 Oak was renamed “Java” many popular companies including
netscape and Microsoft announced their support to Java.
1996 Sun released java development kit 1.0
1999 Sun releases java development kit 1.1(JDK 1.1)
1998 Sun release the Java 2 with version 1.2 of the software
development kit (SDK 1.2)
1999 Sun releases Java 2 platform standard edition (J2SE) and
Enterprise Edition (J2EE)
2000 J2SE with SDK 1.3 was released.
2002 J2SE with SDK 1.4 was released
2004 J2SE with JDK 5.0 (united of JDK 1.5) was released. This is
known as J2SE 5.0.

VI. JAVA FEATURES :

• Compile and interpreted


• Platform independent and portable
• Object oriented
• Robust and secure
• Distributed
• Familiar , simple and small
• Multi threaded and interactive
• High performance
• Dynamic and extensible
• Easy of development
• Scalability and performace
• Monitoring and manageability
• Desktop client
• Core XML support(Extensible Markup Language)
• Supplementary character support
• JDBC Row Set
VII. JAVA DIFFERS C AND C++ :

C, C++ use pointer concept, it read but java has not pointer concept.

JAVA AND C:

• Java is almost similar to C


• Java is object oriented language and has mechanism to define classes and objects.
• Java does not include the C unique statement keywords i.e. sizeof and typedef.
• Java does not contain the data types struct and union.
• Java doe not define he type modifier keywords auto, extern, and unsigned. register,
signed and unsigned.
• Java does not support an explicit pointer type.
• Java does not have a preprocessor and therefore we cannot use #define , #include and
#def, if statement.
• Java requires that the function within one arguments must be declared with empty
parenthesis and not with the void keyword as done in C.
• Java add new operator such as instance of and >>>.
• Java adds labeled break and continue statement.
• Java adds many features required for object oriented programming.

JAVA AND C++ :

• Java does not support operator overloading.


• Java doenot have template classes(generic programming) as in C++.
• Java does not support multiple inheritance of classes. This is accomplished using a new
features called “Interface”.
• Java does not support global variables. Every variable and method is declared with in a
class and forms part of that classes.
• Java does not use pointers.
• Java has replaced the destructor function with a finalise a function .
• There are no header file in java.

VIII. JAVA AND INTERNET :

SQL – Structured Query Language


RDBMS – Relational Database Management System
HTML – HyperText Markup Language
HTTP – HyperText Transfer Protocol

Protocol :
A protocol is a set of rules basically that is followed for communication with user and
computer.
TYPES :

HTTP – HyperText Transfer Protocol


FTP – File Transfer Protocol
SMTP – Simple Mail Transfer Protocol
POP – Post Office Protocol
IMAP – Internet Message Access Protocol.

For Webpage creation - JAVA.


For Web Page Designing – HTML .
Java applet program - web browser
Java and internet

- Java is strongly associated with the internet because of the first application program is
written in Java was hot Java.

- Web browsers to run applets on the internet.

- Internet users can use Java to create applet programs & run then locally using a Java-
enabled browser such as hot Java.

- Java applets have made the internet a true extension of the storage system of the local
computer.

IX. JAVA AND WWW :


- World wide web is a collection of information stored on internet computers.

- World wide web is an information retrieval system designed to be used in the


internet’s distributed environment.
- World wide web contains web pages that provide both information and controls.

- Web pages contain HTML tags that enable us to find retrieve, manipulate and
display documents world wide.

- Before Java, the world wide web was limited to the display of still images & texts.

- With the help of Java WWW is capable of supporting animation graphics, games and wide
rage special effects.

- Java communicates with a web page through a special tag called <applet>.

- Java user sends a request for an HTML document to the remote computers net
browser.

- The web-browser is a program that accepts a request, processes the request and sends the
required documents.

- The HTML document is returned to that user browser.

- The document contains the applet tag which identifies the applet. The corresponding
applet is transferred to the user computer.

- The Java enabled browser on the user's computer interprets the byte code and provide
output.
VIII. OVERVIEW OF JAVA:
IX. SIMPLE JAVA PROGRAM :

Syntax:

Package details ---------→ import [Link].*;

Class ClassName -------→ Class Sum

Data members; ---------→ int a,b,c;

User defined method; --------→ void display()

Public static void main(String args[])

Block of statements; --------→ [Link](“ welcome”);

}
X. STRUCTURE OF JAVA PROGRAM :
XI. JAVA TOKENS :
TYPES OF TOKENS:
Java Statements
A statement specifies an action in a Java program, such as assigning the sum of x
and y to z, printing a message to the standard output, writing data to a file, etc.

Statements in Java can be broadly classified into three categories:

• Declaration statement
• Expression statement
• Control flow statement

Declaration Statement
A declaration statement is used to declare a variable.

For example, int num;


int num2 = 100;
String str;

Expression Statement

An expression with a semicolon at the end is called an expression statement. For example,

/Increment and decrement expressions


num++;
++num;
num--;
--num;
//Assignment expressions
num = 100;
num *= 10;

//Method invocation expressions

[Link]("This is a statement");

someMethod(param1, param2);

Control Flow Statement

Sometimes want to execute a set of statements repeatedly for a number of times or as


long as a particular condition is true.

All of these are possible in Java using control flow statements. If block, while
loop and for loop statements are examples of control flow statements.

Java Virtual Machine

JVM is an engine that offers the Java Code or applications runtime environment. It
transforms bytecode Java into the language of computers. JVM (Java Run Environment) is a
component of JRE. It is a Java Virtual Machine.

• The compiler generates machine code for a specific scheme in other


programming languages. However, for a virtual machine known as Java Virtual
Machine, Java compiler generates code.
• First, the bytecode for Java code is generated. This bytecode is interpreted on
various computers
• Bytecode is an intermediate code between the host system and the source code of Java.
• JVM is accountable for memory space allocation.
JVM is an abstract machine (Java Virtual Machine). It is a specification that offers
runtime environment and allows the execution of java bytecode.

For many hardware and software platforms, JVMs are available (i.e. JVM depends on
the platform).

- JVM is the Java Virtual Machine – it actually executes Java ByteCode.

- JRE is the Java Runtime Environment – it contains a JVM, among other things, and is
what you need to run a Java program.

- JDK is the Java Development Kit – it is the JRE, but with javac (which is what you need
to compile Java source code) and has other programming tools added.

- Let's comprehend JVM's inner architecture. It includes classloader, region of memory,


engine of execution, etc.
Layers of JVM:
Constants, Variables, Data Types

Constants
Constants are fixed values does not changed during the Execution of program. there are two
types of Constants.

Integer Constants
Integer Constants refers to a Sequence of digits which Includes only negative or positive Values
and many other things.

1. An Integer Constant must have at Least one Digit.


2. it must not have a Decimal value.
3. it could be either positive or Negative.
4. if no sign is Specified then it should be treated as Positive.
5. No Spaces and Commas are allowed

Ex: 123 -321 654321

Real Constants
1. A Real Constant must have at Least one Digit.
2. it must have a Decimal value.
3. it could be either positive or Negative.
4. if no sign is Specified then it should be treated as Positive.
5. No Spaces and Commas are allowed in Name.
6. Like 251, 234.890 etc are Real Constants.
In The Exponential Form of Representation the Real Constant is Represented in the two
Parts The part before appearing e is called mantissa whereas the part following e is called
Exponent.
7. In Real Constant The Mantissa and Exponent Part should be Separated by letter e.
8. The Mantissa Part have may have either positive or Negative Sign.
9. Default Sign is Positive.
Character Constants
A Character is Single Alphabet a single digit or a Single Symbol that is enclosed within Single
inverted commas.
'S' ,'1' etc are Single Character Constants.

String Constants
String is a Sequence of Characters Enclosed between double Quotes. These Characters may be
digits ,Alphabets Like "Hello" , "1234" etc.

Backslash Character Constants


Java Also Supports Backslash Constants those are used in output methods For Example
\n is used for new line Character. These are also Called as escape Sequence or backslash
character Constant.

Ex:
\t For Tab ( Five Spaces in one Time )
\b Back Space etc.

Variables
A variable is a name given to a memory location. It is the basic unit of storage in a program.
• The value stored in a variable can be changed during program execution.
• A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
• In Java, all the variables must be declared before use.

A name can only be given to a memory location. It can be assigned values in two ways:
• Variable Initialization
• Assigning value by taking input

How to initialize variables?


datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable. value:
It is the initial value stored in the variable.

Examples:

float simpleInterest; //Declaring float variable


int time = 10, speed = 20; //Declaring and Initializing integer variable
char var = 'h'; // Declaring and Initializing character variable

Types of variables
There are three types of variables in Java:
• Local Variables
• Instance Variables
• Static Variables

1. Local Variable

A variable declared inside the body of the method is called local variable. To use this variable
only within that method and the other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2. Instance Variable

A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static.

It is called instance variable because its value is instance specific and is not shared among
instances.

3. Static variable

A variable which is declared as static is called static variable. It cannot be local. To create a
single copy of static variable and share among all the instances of the class. Memory allocation for
static variable happens only once when the class is loaded in the memory.
Example pgm:-
class Simple{
public static void main(String[] args)
{
int a=10;
int b=10;
int c=a+b;
[Link](c);
}
}

Data Types

Data types specify the size and type of values that can be stored.

1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
2. Non-primitive data types: The non-primitive data types include Classes, Strings, Interfaces, and
Arrays.

Java Primitive Data Types

Primitive data types are the building blocks of data manipulation. These are the most basic data
types available in Java language.

Boolean Data Type

The Boolean data type is used to store only two possible values: true and false. This data
type is used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.

Example: Boolean >

Byte Data Type

The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum
value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in place
of "int" data type.

Example: byte a = 10, byte b = -20

Short Data Type

The short data type is a 16-bit signed two's complement integer. Its value-range lies
between - 32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is
32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short data type
is 2 times smaller than an integer.

Example: short s = 10000, short r = -5000

Int Data Type

The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is
- 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there
is no problem about memory.

Example: int a = 100000, int b = -200000


Long Data Type

The long data type is a 64-bit two's complement integer. Its value-range lies between
- 9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807.
Its default value is 0. The long data type is used when you need a range of values more than those
provided by int.

Example: long a = 100000L, long b = -200000L

Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating [Link] value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in large
arrays of floating point numbers. The float data type should never be used for precise values, such
as currency. Its default value is 0.0F.
Example: float f1 = 234.5f

Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double data
type also should never be used for precise values, such as currency. Its default value is 0.0d.

Example: double d1 = 12.3

Char Data Type

The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000'
(or) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.

Example: char letterA = 'A'.

Operators and Expressions


Operators

An operator is a character that represents an action, for example + is an arithmetic operator that
represents addition.

The types of Operators those are supported by Java Language.

1. Assignment Operator
2. Arithmetic Operator
3. Relational or Conditional Operators
4. Logical Operators
5. Increment & Decrement Operators
6. Conditional or Ternary Operator
7. Special Operator

Assignment Operator
Assignment Operator (=) is used for Initializing a value to variable or we can say
that an assignment operator is used for Assigning a value to the variable.
Ex:
int a=10;

Example:

class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=20;
a+=4; // a=a+4 (a=10+4) b-=4;//b=b-4 (b=20-4)
[Link](a);
[Link](b);
}
}

Arithmetic Operators
The Arithmetic Operators are used for Performing the Mathematical Operations on
operands Like + , - , / , * , %

Operator Result
is Called as Modulus or Remainder operator
% Which gives us the Remainder after division.

+ For Addition

- for Subtraction

* For Multiplication
/ For Division

% For Modulus
Example:
class OperatorExample{
public static void main(String args[])
{
int a=10;
int b=5;
[Link](a+b); //15
[Link](a-b); //5
[Link](a*b); //50
[Link](a/b); //2
[Link](a%b); //0
}
}

Relational or Conditional Operators


The Relational Operators are used for Checking the Conditions or These operators are used for
Controlling the Flow of the Execution to First Check the Condition it Contains

Operator Result
< Less Than

> Greater Then

>= Greater then Equals to

<= Less Than Equals To

! boolean not
!= not equal to

Example:

class RelationalOperator
{
public static void main(String[] args)

int number1 = 5, number2 = 6;

if (number1 > number2)


{
[Link]("number1 is greater than number2.");}
else {
} [Link]("number2 is greater than number1.");
}
}
Logical Operators
The boolean logical operators shown here operate only on boolean operands. All of the
binary logical operators combine two boolean values to form a resultant boolean value.

Operator Result

& Logical AND


| Logical OR

^ Logical XOR (exclusive


OR)
|| short Circuit OR
&& Short Circuit AND

! Logical Unary Not

&= AND ASSIGNMENT


|= OR ASSIGNMENT

^= XOR ASSIGNMENT

== Equal To

!= Not Equal To
?: Termary if then else

Example:
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
[Link](a<b&&a++<c); //false && true = false
[Link](a); //10 because second condition is not checked
[Link](a<b&a++<c); //false && true = false
[Link](a); //11 because second condition is checked
}
}

Increment Decrement Operators

Increment/Decrement Operators is Counter Operator. These are two as: ++


(increment operator) and -- (decrement operator).
Increment operator are used for incrementing the value one by one. Similarly
decrement operator are used for decrementing the value one by one. These are further sub-
divided into two categories:

a) Prefix Increment / Decrement Operator


b) Postfix Increment / Decrement Operator

a) Prefix Operator:
In the Prefix increment operator, value will be increment and the incremented value will
be assigned to a variable. prefix decrement operator value will be decrement and then decremented
value be assigned to the variable. The general way is represented as:

++v;
--v;

b) Postfix Operator:
In the postfix increment operator, value will be assigned to a variable and then it
will be incremented. postfix decrement operator value will be assigned and then it will be
decremented. The general way is represented as:

v++;
v--;

Example:

class OperatorExample
{
public static void main(String args[])
{
Int x=10;
[Link](x++); //10 (11)
[Link](++x); //12
[Link](x--); //12 (11)
[Link](--x); //10
}
}
Conditional Operator

This operator is used to specify the value of Variable by first checking a condition of this
Operator Works Similar to if else :- In this First it checks the condition if it is true then it will
gives the result and if a condition will false then it also Gives Some Values to the Variables

This Operator Contains ? :

Ex:
Int A,B A=10 B=20
C=(A>B) ? 13 : 20

Example:

class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
[Link](min);
}
}

In this First ? Will Check Whether a Condition is true or not if it is true then it will gives the
value 13 to C or if Condition is False Then it will gives 20 the C Variable

Special Operators
Java Also Provides Some Special Operators Like Instance of For checking Whether
an Object is Instance of a Class or Whether an object is related to Class this will gives result
true or either False

Dot Operator
Dot Operator is used for Accessing the data and Member Function of class and This
is used by Object of Class An Object Communicates With the Member Functions of Class With
the Help of Dot Operator.
Java Expressions

An expression is a combination of operators, constants and variables.


An expression may consist of one or more operands, and zero or more operators
to produce a value.

Example:
a+b c

s-1/7*f
.
.
etc

Types of Expressions:

Expressions may be of the following types:

• Constant expressions: Constant Expressions consists of only constant


values. A constant value is one that doesn’t change.
Examples:
5, 10 + 5 / 6.0, 'x’
• Integral expressions: Integral Expressions are those which produce
integer results after implementing all the automatic and explicit type
conversions.
Examples:
x, x * y, x + int( 5.0) where x and y are integer variables.
• Floating expressions: Float Expressions are which produce floating
point results after implementing all the automatic and explicit type
conversions.
Examples:
x + y, 10.75 where x and y are floating point variables.
• Relational expressions: Relational Expressions yield results of type bool
which takes a value true or false. When arithmetic expressions are used on
either side of a relational operator, they will be evaluated first and then the
results compared. Relational expressions are also known as Boolean
expressions.
Examples:
x <= y, x + y > 2
• Logical expressions: Logical Expressions combine two or more relational
expressions and produces bool type results.
Examples:
x > y && x == 10, x == 10 || y == 5
• Pointer expressions: Pointer Expressions produce address values.
Examples:
&x, ptr, ptr++ where x is a variable and ptr is a pointer.
• Bitwise expressions: Bitwise Expressions are used to manipulate data at bit
level. They are basically used for testing or shifting bits.
Examples:
x << 3 shifts three bit position to left
y >> 1 shifts one bit position to right.
Shift operators are often used for multiplication and division by powers of two.

Decision Making and Branching


Java decision-making statements allow to make a decision, based upon the result
of a condition.
All the programs in Java have set of statements, which are executed sequentially
in the order in which they appear.
It happens when jumping of statements or repetition of certain calculations is not
necessary.
where programmers have to change the order of execution of statements based
on certain conditions which involve kind of decision-making statements.
The flowchart of Decision-making techniques

the decision making statements:

➢ if Statement
o if statement
o if-else statement
o else-if statement
➢ Conditional Operator
➢ switch statement

If Statement

If statements is used to control the program flow based on some condition, it's used
to execute block of statement if the expression evaluated to true; otherwise, it will get
skipped. This statement is the simplest way to modify the control flow of the program.
Syntax
if(test_expression)
{
statement 1;
statement 2;
...

}
Figure - Flowchart of if Statement:

Example:
public class Sample
{

public static void main(String args[])


{
int a=20, b=30;

if(b>a)
{
[Link]("b is greater");
}
}
}

Output:

b is greater

If Else Statements
If else statement is used to control the program flow based on some condition,
only the difference is: it's used to execute some block of statement if the expression is
evaluated to true, otherwise executes else block of statement.

Syntax:
if(test_ex
pression)
{
//execute your code
}
else
{
//execute your code
}

Figure - Flowchart of if-else Statement:

Example:
public class Sample
{
public static void main(String args[])
{
int a = 80, b = 30;

if (b & gt; a)
{
[Link]("b is greater");
}
Else
{
[Link]("a is greater");
}
}

Output:

a is greater

Else if Statements

else if statements in Java is like another if condition, it's used in the


program when if statement having multiple decisions.

Syntax:
if(test_ex
pression)
{
//execute your code
}
else if(test_expression n)
{
//execute your code
}
else
{
//execute your code

Figure - Flowchart of else if Statement:

Example:
public class Sample
{
public static void main(String
args[])
{
int a = 30, b = 30;

if (b > a)
{
[Link]("b is greater");
}
else if(a > b)
{
[Link]("a is greater");
}
Else
{
[Link]("Both are equal");
}
}

}
Ouptut:

Both are equal

Switch Statement:

Switch statement is used when we have multiple possibilities for the if statement.

Syntax:

switch(variable or expression)
{
case 1:
//execute your code
break;

case n:
//execute your code
break;

default:
//execute your
code
break;

Figure - Flowchart of switch Statement:


Example
public class Sample
{

public static void main(String args[])


{
int a = 5;

switch (a)
{
case 1:
[Link]("You chose One");
break;

case 2:
[Link]("You chose Two");
break;

case 3:
[Link]("You chose Three");
break;

case 4:
[Link]("You chose Four");
break;

case 5:
[Link]("You chose Five");
break;

default:
[Link]("Invalid Choice. Enter a no between 1 and
5"); break;
}
}

Output

You chose Five

Java Looping Statements


The process of repeatedly executing a collection of statement is called looping.
The statements get executed many numbers of times based on the condition. But if
the condition is given in such logic that the repetition continues any number of times
with no fixed condition to stop looping those statements, then this type of looping is
called infinite looping.

Java supports following types of loops:


• while loops
• do while loops
• for loops

Figure - Flowchart of Looping:

Java Loop Control Statements

Loop control statements are used to change the normal sequence of execution of the
loop.

statement Syntax description


break statement Break; Is used to terminate loop or
switch statements.
continue statement continue; Is used to suspend the
execution of current loop
iteration and transfer control to
the loop for the next iteration.
goto labelName; It transfers current
goto statement
labelName: statement; program execution
sequence to some other
part of the program.

Java while Loops

Java while loops statement allows to repeatedly run the same block of
statements until a condition is met.

while loop is the most basic loop in Java. It has one control condition and executes as
long the condition is true.
The condition of the loop is tested before the body of the loop is executed;
hence it is called anentry-controlled loop.
Syntax;
While (condition)
{
statement(s);

Incrementation;

Figure - Flowchart of while loop:

Example:
public class Sample
{

public static void main(String args[])


{
int n = 1, times = 5; /* local variable Initialization */

while (n <= times) /* while loops


execution */
{

[Link]("Java while loops:" + n);


n++;
}
}

Output

Java while loops:1


Java while loops:2
Java while loops:3
Java while loops:4
Java while loops:5

Java Do While Loops

Java do-while loops are very similar to the while loops, but it always
executes the block of statements at least once and furthermore as long as the condition
remains true This loop is an as exit controlled loop.
Syntax:
do
{
statement(s);

}while( condition );

Figure - Flowchart of the do-while loop:

Example
public class Sample
{
public static void main(String args[])
{
int n = 1, times = 0; /* local variable Initialization */

do /* do-while loops execution */


{
[Link]("Java do while loops:" + n);
n++;
} while (n <= times);
}

}
Output

Java do while loops:1

Java For Loops

Java for loops is very similar to Java while loops in that it continues to
process a block of code becomes false, and everything is defined in a single line.

Syntax;
for ( init; condition; increment )
{
statement(s);

Figure - Flowchart of for loop:

Example
public class Sample
{

public static void main(String args[])


{
int n = 1, times = 5; /* local variable Initialization */

for (n = 1; n <= times; n = n + 1) /* for loops


execution */
{
[Link]("Java for loops:"
+ n);
}
}

Output:
Java for loops:1
Java for loops:2
Java for loops:3
Java for loops:4
Java for loops:5

Jump statements.

The break statement

Using break we can leave a loop even if the condition for its end is not fulfilled. It can be
used to end an infinite loop, or to force it to end before its natural end.

For example, we are going to stop the count down before its natural end (maybe because
of an engine check failure?):

// break loop example

#include <iostream>

int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", "; if (n==3)
{
cout << "countdown aborted!";
break;
}
}
return 0;
}

Output:

10, 9, 8, 7, 6, 5, 4, 3,
countdown aborted!

The continue statement

The continuestatement causes the program to skip the rest of the loop in the current
iteration as if the end of the statement block had been reached, causing it to jump to the start of
the following iteration.

For example, we are going to skip the number 5 in our countdown:

// continue loop example

#include <iostream>
int main ()
{
for (int n=10; n>0; n--)
{
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}

Output:

10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!

The goto statement

goto allows to make an absolute jump to another point in the program. You should use
this feature with caution since its execution causes an unconditional jump ignoring any type of
nesting limitations. The destination point is identified by a label, which is then used as an
argument
for the goto statement. A label is made of a valid identifier followed by a colon (:).

Generally speaking, this instruction has no concrete use in structured or object oriented
programming aside from those that low-level programming find for it.

For example, here is our countdown loop using goto:

// goto loop example

#include <iostream>

int main ()
{
int n=10; loop:
cout << n << ", ";
n--;
if (n>0)
goto loop;
cout << "FIRE!\n";
return 0;
}

Output:

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
The exit function

exitis a function defined in the c stdlib library.

The purpose of exitis to terminate the current program with a specific exit code. Its prototype is:

Syntax:

void exit (int exitcode);

The exit code is used by some operating systems and may be used by calling programs. By
convention, an exit code of 0 means that the program finished normally and any other value means that
some error or unexpected results happened.
Classes, Objects and Methods

A Class Contains

1) Data Members or Simply Called As Variables


2) Member Functions or Simply Called as Functions

What is Object?
In real-world an entity that has state and its behavior is known as an object.

For Example:

• A Car is an object. It has states (name, color, model) and its behavior (changing gear,
applying brakes).
• A Pen is an object. Its name is Parker; color is silver etc. known as its state. It is used to
write, so writing is its behavior.

What is Class?

• A class is a template or blueprint that is used to create objects.


• Class representation of objects and the sets of operations that can be applied to such objects.
• A class consists of Data members and methods.

The primary purpose of a class is to hold data/information. This is achieved with attributes which
are also known as data members.
The member functions determine the behavior of the class, i.e. provide a definition
for supporting various operations on data held in the form of an object.

Defining a Class in Java

Syntax
public class class_name
{
Data
Members;
Methods;
}

Example:
public class
Car
{
public:
double color; // Color of a
car double model; // Model
of a car

• Private, Protected,Public is called visibility labels.


• The members that are declared private can be accessed only from within the class.
• Public members can be accessed from outside the class also.

Class Members

Data and Functions are members

Data Members and methods must be declared within the class definition.

Example
public class Cube
{
int length; // length is a data member of class Cube int breadth;
}
// breadth is a data member of class Cube int length ;
// Error redefinition of length

• A member cannot be re-declared within a class.


• No member can be added elsewhere other than in the class definition.

Adding Methods

A class has no life without methods. The objects created by such class cannot respond
to any message. Therefore it is necessary to add methods for manipulating the data contained
in the class. Methods are declared inside the class immediately after the variable declaration.
The general form of a method declaration is

Syntax:
type methodname (parameter-list)
{
method-body;
}

Example:
class varAccess
{
int x;
void method1( )
{
int y;
x = 10; // legal y = x; // legal
}
void method2( )
{
int z;
x = 5; //legal z = 10; //legal y = z; //illegal
}
}

Accessing Class Members

After creating objects, we are discussing about the accessing class members using
objects. Each objects containing its own set of variables, we should assign values to these
variables in order to use them in our program. Since we are outside the class, we cannot access
the instance variables and the methods directly. Thus, to access them, we use the concerned
object with the dot operator. The syntax is as follows:

Syntax:

Object_name.Variable_name;
Object_name.Method_name
(parameter_list);

The instance variable and method of Movie class may be accessed and assigned values
as follows:

Examples:

[Link] = 15;
[Link] = 150;
[Link] = 25;
[Link] = 250;

Example:

import [Link].*;
class Base
{
int a,b;
void get() //Definition of Methods
{
a = 100;
b = 200;
}
void sum() //Definition of another method
{
int c = a + b;
[Link]("Sum = "+c);
}
}
class CompleteClassProgram //class with main method
{
public static void main(String args[])
{
Base obj=new Base(); //creating object
[Link](); //Accessing Methods
[Link]();
}
}

Method Overloading

Methods are used in Java to describe the behavior of an object. Methods are a collection
of statements that are group together to operate. In Java, it is possible to create methods that have
the same name, but different argument lists in various definitions, i.e., method overloading is
possible in Java, which is one of the unique features of Object Oriented Programming (OOP). In
this chapter, we will learn about how method overloading is written and how it helps us within a
Java program.
There are different ways to overload a method in Java. They are:

1. Based on the number of parameters: In this case, the entire overloading concept depends
on the number of parameters that are placed within the parenthesis of the method.
2. Based on the data type of the parameter: With the arrangement of data type, within
the parameter, overloading of the method can take place.
3. Based on the sequence of data types in parameters: The method overloading also depends
on the ordering of data types of parameters within the method.
Syntax
public class Student {
public void add(int i, int j)
{
....
}
public void add(int i)
{
....
}
}

Example

class Multiply
{
void mul(int a, int b)
{
[Link]("Sum of two=" + (a * b));
}

void mul(int a, int b, int c)


{
[Link]("Sum of three=" + (a * b * c));
}
}
public class Polymorphism {
public static void main(String args[])
{ Multiply m = new Multiply(); [Link](6, 10);
[Link](10, 6, 5);
}
}
Output:
Sum of two=60 Sum of three=300

Advantage of Method Overloading

• It is used to perform a task efficiently with smartness in programming.


• It increases the readability of the program.
• The Method overloading allows methods that perform proximately related functions
to be accessed using a common name with slight variation in argument number or
types.
• They can also be implemented on constructors allowing different ways to initialize objects
of a class.

Constructor

Constructor is that whose name is Same as name of Variable and used for Initializing the
data members of Class and it gets Automatically called when an object of class is created But
Always Remember Some things about Constructor Like :-

Name of Constructor must be same as name of class


Have No Return Type Even Not Void
Automatically Called when an object of class is created

There are three types of Constructor as follows:-

• Default Constructor
• Parameterized Constructor
• Copy Constructor

Default Constructor
Default Constructor is also called as Empty Constructor which has no arguments and It is
Automatically called when we creates the object of class but Remember name of Constructor is
same as name of class.

Example:
import [Link].*;
class student
{
int a,b;
student( ) //Constructor
{
a = 100;
b = 200;
}
void sum()
{
int c = a + b;
[Link]("Sum = "+c);
}
}
class Constructor
{
public static void main(String args[])
{
student obj=new student();
[Link]();
}
}

Parameterized Constructor

This is Another type Constructor which has some Arguments and same name as class
name but it uses some Arguments So For this We have to create object of Class by passing some
Arguments at the time of creating object with the name of class.

Example
import [Link].*;
class student
{
int a,b;
student(int x, int y) //Parameterized Constructor
{
a = x; b = y;
}
int sum()
{
return(a+b);
}
}
class ParamConstructor
{
public static void main(String args[])
{
student obj=new student(40,80);
int sum= [Link]();
[Link]("Sum="+sum);
}
}

Copy Constructor

This is also Another type of Constructor. In this Constructor object of another Constructor
is passed As name Suggests you Copy means Copy values of another Class object This is used
for Copying the values of class object into an another object of class So For Calling Copy
Constructor

Example
import [Link].*;
class box
{
int h,w; //data members
box() // default constructor
{
h=10;
w=20;
}
box(int x, int y)
{
h=x;
w=y;
}
box(box obj) // Copy Constructor
{
h=obj.h;
w=obj.w;
}
void show() // Member Function
{
[Link]("\n\tHeight of Box is :\t"+h);
[Link]("\n\tWidth of Box is :\t"+w);
}
}
class CopyConstructor
{
public static void main(String args[])
{
box obj_box=new box(); //instance of default constructor
obj_box.show();

box obj_box1=new box(120,30); //Instance of Parameterized's Constructor


obj_box1.show();
box obj_box2=new box(obj_box1); //Instance of Copy Constructor
obj_box2.show();
}
}
Arrays, Strings and Vectors

1. Arrays
Array is a group og contiguous or related data items that share a common name.
Arrays have fixed length once they are declared their size cannot be changed. In JAVA
arrays are Objects Arrays can be declared and initialized.
Individual values are called elements. Arrays can be of any variable type.

e.g: Salary[5];

e.g. Creation of an array has three steps

1. Declaring the array


2. Creating memory locations
3. Putting values into memory locations.

Declaration of an Array

Syntax

type arrayname[];

type[] arrayname;

e.g.

int no[ ];

float[ ] per;

float marks[ ];

Creation of Arrays

array name = new type[size];

e.g.

no=new int[5];

per=new float[5];

Array Initialization

Type arrayname[ ]={ list of values};


Int no[ ]={10,20,30,40,50};

Array Length

We can get the length of an array by using


[Link].

e.g:

int var= [Link];

JAVA supports single dimentional,two dimentional ,multidimentional and variable size arrays.

Program to sort an array of integer numbers

import [Link].*;
class sort
{
public static void main(String args[])
{
int a[]={14,32,25,17,29};
int i,j,temp;
[Link](" elements before sorting are: ");
for(i=0;i<5;i++)
[Link]("\t"+a [i]);
for(i=0;i<5;i++)
for(j=0;j<4-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=tem p;
}
}
[Link](" elements after sorting are: ");
for(i=0;i<5;i++)

[Link]("\t"+a[i]);
}
}
Program to diagonal elements of a 3X3 matrix to zero

import [Link].*;

class diagonal
{
public static void main(String args[])
{
int i,j;
int a[][]=new int[3][3];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(i==j)
{
a[i][j]=0;
[Link](" "+a[i][j]);
}
else
{
a[i][j]=1;
[Link](" "+a[i][j]);
}
}
[Link]("\n");
}

2. Strings

A string is a sequence of characters. It is also called as array of characters. In JAVA


strings are implemented as object of String Class. It represent sequence of characters in
java by using a character array.

Char charAraay[ ] = new char[4];

charArrar[0] = ‘J’;

charArrar[1] = ‘A’;

charArrar[2] = ‘V’;

charArrar[3] = ‘A’;

How to declare and use string:


String are class objects and implemented using two classes namely String and

StringBuffer.

Syntax:

String stringName;
StringName= new String(“string”);
e.g.

String
firstname;
Firstname= new String(“Hari”);

How to declare array of strings

String arrayName[ ]= new String[3];

The above declaration will hold three strings in arrayname.

String Methods:
It defines number of methods that allows to perform string manipulation tasks.

Method - Tasks
1. s2=[Link]() – Converts the string s1 to all lowercase
2. s2=[Link]() – Converts the string s1 to all uppercase
3. s2=[Link](‘X’,’Y’) – Replace all appearances of X with Y
4. s2=[Link]() – Remove white spaces at the beginning and end of the string s1
5. [Link](s2) – Returns true if s1 is equal to s2
6. [Link]() – Returns true if s1=s2 ignoring the case of characters
7. [Link]() – Gives length of s1
8. [Link](n)- Gives nth character of s1
9. [Link](s2) – Returns negative if s1 < s2,positive if s1 > s2 otherwise zero
10. [Link](s2) – concatenates s1 and s2
11. [Link](n) – Gives substring starting from nth character
12. [Link](n,m) – Gives substring starting from nth character upto mth
character it does not include mth character
13. StringValueOf(p) – Crates a string object of the parameter p ( simple type or object)
14. [Link]() – Creates a string representation of the object p
15. [Link](‘X’) – Gives the position of the first occurrence of ‘X’ in the string s1
16. [Link](‘X’,n) – Gives the positon of ‘X’ that occurs after nth position in the string
s1
17. [Link](variable) – Converts the parameter value to string representation.

Program to sort an array of names

Class Stringsort
{
static String name[] ={“pritee”,”devi”,”dev”,”chins”,”rahul”};
public static void main(String args[])
{
Int size = [Link];
String temp= null;
for(int i=0;i<size;i++)

{
for(int j=i+1;j<size;j++)
{
if(name[j].compareTo(name[i]) < 0)
{
temp= name[i]; //swap the strings
name[i]= name[j];
name[j]= temp;
}
}
for(int i=0;i<size;i++)
{
[Link](name[i]);
}
}
}

StringBuffer and StringTokenizer

StringBuffer is a peer class of string. While string creates strings of fixed_length.


StringBuffer creates strings of fixed length that can be modified in terms of both length and
content. We can insert characters and substrings in the middle of a string, or append another
string to end.
Commonly used StringBuffer methods:

[Link](n,’X) – Modifies the nth character to ‘X’

[Link](s2) – Appends the string s2 to s1 at the end

[Link](n,s2) – Inserts the string s2 at the position n of the

string s1

[Link](n) – Sets the length of the string s1 to [Link] n<[Link]() s1 is truncated. If


n>[Link]() zeros are added to s1.

StringTokenizer

A sentence is made up of a number of words called tokens. Compilers also perform


tokenization. They breakup the statements into individual pieces like
keywords,identifiers,operators and other elements of a programming [Link]
tokenizer class is used to break the string into its component tokens. Tokens are separated
from one another by delimeters,while spaces,blank,tab,new line of carriage return.
}
}

3. Vector
The concept of variable arugments to methods is achieved in JAVA with the use of
Vector Class which is present in [Link] package. This class is used to create a generic
dynamic array known as vector which can hold objects of any type and any number. The
objects do not have to be [Link] can be easily implemented as vectors.
Vector v = new Vector(); // declaration without

size Vector v=new Vector(3); // declaration

with size Advantages of Vectors over Arrays

[Link] is convenient to use vectors to store objects

2.A vector can be used to store a list of objects that may vary in

size [Link] can add and delete objects from the list as and when

required

A major constraints of vectors is that we cannot directly store simple data type in a
vector we can only store objects.
We can convert simple types to objects using wrapper classes.

Important Vector methods are

[Link](item) – adds the item to the list at the

end [Link](5) – gives the name of the 5th

object [Link]() – gives the number of objects present

[Link](item) – removes the specified item from the list

[Link](n) – removes the item stored in the nth position of the

list [Link]() – removes all the elements in the list

[Link](array) – copies all items from list to array

[Link](item,n) – inserts the item at nth

position e.g.

Program to explain working with Vectors


import [Link].*;
Class TestVector
{
public static void main(String args[])
{
Vector list= new Vector();
int length=[Link];
for(int i=0;i<length;i++)
{
[Link](args[i]);
}
[Link](“CO BOL”,2);
int size = [Link]();
String listaray[] = new String[size];
[Link](listarray);
[Link](“List of Languages”);
for(int i=0;i<size;i++)
{
[Link](listarray[i]);
}
}
}

Wrapper Classes

Vectors can not handle primitive data types like int,float,long,double,char


[Link] data types can be converted into objects types by using wrapper classes
contained in the [Link] package.

Following are the data types and their corresponding wrapper class types.

Simple type Wrapper class


Boolean Boolean
Char Character
Double Double
Float Float
Int Integer
Long Long

Following are the conversation from primitive data types to object numbers using
constructor methods
Ingeger IntVal = new Integer(i) //primitive integer to Integer Object

Converting Object numbers to Primitive numbers using typeValue()

method Int I = [Link](); // Object to primitive integer

Converting numbers to Strings using to String() method

Str = [Link](i); //primitive integer to string


Converting String Object to Numeric Objects using the static method ValueOf()

IntVal = [Link](str); // Converts string to Integer Object

Converting Numeric String to Primitive Numbers Using

Parsing Methods int I = [Link](str);

e.g

Program how to use wrapper class


methods Class test
{
Public static void main(String args[])
{
try
{
DataInputStram in = new DataInputStram([Link]);
[Link](“ enter a no”);
String str=[Link]();
int a=[Link] nt(str);
}
catch(IOException e)
{
[Link](“ I/O Error”);
}
[Link](“\n the square of a number entered by the user is “+(a*a));
}
}

4. Interface : Multiple Inheritance

An interface is a reference type in Java. It is similar to class. It is a collection of


abstract methods. A class implements an interface, thereby inheriting the abstract
methods of the interface.
An interface is similar to a class in the following ways −
• An interface can contain any number of methods.
• An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
• The byte code of an interface appears in a .class file.
• Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.
However, an interface is different from a class in several ways, including −
• You cannot instantiate an interface.
• An interface does not contain any constructors.
• All of the methods in an interface are abstract.
• An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
• An interface is not extended by a class; it is implemented by a class.
• An interface can extend multiple interfaces.
Contents
Interfaces
Defining
Interface
Extending Interfaces
Implementing Interfaces

Declaring Interfaces

The interface keyword is used to declare an interface. Here is a simple example to declare an
interface
Following is an example of an interface
/* File name : [Link] */
import [Link].*;
// Any number of import statements

public interface NameOfInterface {


// Any number of final, static fields
// Any number of abstract method declarations\
}
Interfaces have the following properties −
• An interface is implicitly abstract. You do not need to use the abstract keyword
while declaring an interface.
• Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
• Methods in an interface are implicitly public.

Implementing Interfaces

When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the specific behaviors of the interface. If a class does not perform all the
behaviors of the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements
keyword appears in the class declaration following the extends portion of the declaration.
Example
/* File name : [Link] */
public class MammalInt implements Animal {

public void eat() {


[Link]("Mammal eats");
}

public void travel() {


[Link]("Mammal travels");
}

public int noOfLegs() {


return 0;
}

public static void main(String args[]) {


MammalInt m = new MammalInt();
[Link]();
[Link]();
}
}

When implementation interfaces, there are several rules −


• A class can implement more than one interface at a time.
• A class can extend only one class, but implement many interfaces.
• An interface can extend another interface, in a similar way as a class can extend
another class.
Extending Interfaces

An interface can extend another interface in the same way that a class can extend another
class. The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.

Example
// Filename: [Link]
public interface Sports {
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}

// Filename: [Link]
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}

// Filename: [Link]
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}

Extending Multiple Interfaces

A Java class can only extend one parent class. Multiple inheritance is not allowed.
Interfaces are not classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-
separated list.
For example, if the Hockey interface extended both Sports and Event, it would be declared
as −

Example

public interface Hockey extends Sports, Event

5. Packages: Putting Classes together


A package is a collection of related classes and interfaces.

Contents
➢ Benefits of Packages
➢ System Packages
➢ Creating Packages
➢ Using a Package
Benefits of Packages
• Classes contained in packages of other programs can be easily reused.
• Two classes in two different packages can have the same name. They can
be uniquely identified by [Link].
• Packages also provide a way for separating "design" from "coding".
• You can define classes inside a package that are not accessible by code
outside that package. You can also define class members that are only
exposed to other members of the same package.
In practical applications, we may have to build our own classes and use existing classes
libraries for designing use interfaces.
Java packages are classified into two types.

1. Java API package


2. User defined packages

Using Java API Packages


System Packages

Java API provides a large number of classes grouped into different packages according to
functionality. Most of the time in our programming we use the Java System Packages. The
following are the frequently used system packages, showing the functional breakdown.

The following are the brief description of Java System Packages and their Classes:

Lang means to language. Lang classes are used by java compiler itself and therefore
[Link] they are automatically imported. Classes that are required for primitive types, strings
main functions, threads and exceptions included in it.

[Link] Util stands for language utility. It include classes such as vectors, has tables random
numbers, date etc.

Input/Output support classes are included in it. They provide the facilities for the
[Link]
input and output of data.

Awt stands for abstract window toolkit. It is used for implementing graphical user
[Link] interface in the program. They include classes for windows, buttons, Menu ,
checkbocx etc.

[Link] Net stands for networking. Therefore the classes required for communicating with
local computers as well as with internet swervers are included in it.

[Link] This pacake includes the classes for creating and implementing applets.

Creating Packages

To create a package, simply include a package command as the first statement in a Java
source file. Any class declared within that file will belong to the specified package. If you omit
the package statement, the class names are put into a default package which has no name.

package first_name;
public class firstclass
{
}

The file should be stored as [Link] and should be located in a directorynamed


first_package. The compiled class file should aslo be stored in the directory that has the same
name as the package. Java also supports the concept of package hierarchy. This is done by
specifying multiple names in a package statement, separated by dots-package
[Link];

Store this package in a subdirectory named.

first_package\secondPackage.

Using a Package

Let us consider some simple program that will use classes from other packages. The listing
below shows a package named package1 containing a single class. Class Ademo.

package package1;
public class Ademo
{
public void show()
{
[Link]("Display the Class packclass1");
}
}

How to Import Package

To create an object of a class (bundled in a package), in your code, you have to use its fully
qualified name.

Example:

[Link] object = new [Link]();

But, it could become tedious to type the long dot-separated package path name for every
class you want to use. Instead, it is recommended you use the import statement.
Syntax

import packageName;

Once imported, you can use the class without mentioning its fully qualified name.

import [Link].*; // * signifies all classes in this package are impor


ted
import [Link] // here only the JFrame class is imported//Usage
JFrame f = new JFrame; // without fully qualified name.

Example:

package p3;
import p1.*; //imports classes only in package p1 and NOT in the sub-package
p2
class c3{
public void m3(){
[Link]("Method m3 of Class c3");
}
public static void main(String args[]){
c1 obj1 = new c1();
obj1.m1();
}
}
Example

import [Link];

public class PrintName


{
public static void main(String args[])
{
// Initializing the String variable
// with a value
String name = "GeeksforGeeks";

// Creating an instance of class MyClass in


// the package.
MyClass obj = new MyClass();

[Link](name);
}
}

1. Every class is part of some package.


2. If no package is specified, the classes in the file goes into a special unnamed package
(the same unnamed package for all files).
3. All classes/interfaces in a file are part of the same package. Multiple files can specify
the same package name.
4. If package name is specified, the file must be in a subdirectory called name (i.e.,
the directory name must match the package name).
5. We can access public classes in another (named) package using: package-
[Link]- name

6. Multithreaded Programming
What is Multithreading?

The process of executing multiple tasks (also called threads) simultaneously is called
multithreading. The primary purpose of multithreading is to provide simultaneous execution of
two or more parts of a program to make maximum use of CPU time. A multithreaded program
contains two or more parts that can run concurrently. It enables programmers to write in a way
where multiple activities can proceed simultaneously within a single application.

What is Multitasking?

It is the way of executing multiple tasks at a time executing them concurrently over a specified
period. Multitasking is done in two ways. These are:

1. Process-based multitasking: It is also called multiprocessing where each process has its address
in memory, i.e., each process allocates separate memory area.

2. Thread-based multitasking: This thread-based multitasking is also termed as multithreading


where threads share the same address space.

Thead Life Cycle


The time period between the creation and the destruction of the thread object is called the life
cycle of a thread. The five states in thread life cycle are:

1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
Following are the stages of the life cycle −
• New − A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
• Runnable − After a newly born thread is started, the thread becomes runnable. A thread
in this state is considered to be executing its task.
• Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
• Timed Waiting − A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that time
interval expires or when the event it is waiting for occurs.
• Terminated (Dead) − A runnable thread enters the terminated state when it completes its
task or otherwise terminates.

Thread Methods

The Thread Methods are used for Controlling the Behavior of the Executing threads Like
Sleeping , Suspend , Sleep all these are Methods, those are Stored Thread Class which is located
in the Java. Lang Package. And this class gets Automatically loaded When a Programs begins and
we don't have any need to add this Separately. The Thread Class provides followings Methods :-
The Thread class defines several methods that help manage [Link] table below displays the
same:

Method Meaning
getName() Obtain thread’s name
getPriority() Obtain thread’s priority
isAlive() Determine if a thread is still running
join() Wait for a thread to terminate
run() Entry point for the thread
Suspend a thread for a period of
sleep()
time
Start a thread by calling its run
start()
method

Main Thread

Every Time When we Make a Program of JAVA then this will make a Main Thread which
will makes of initialize the main Program . and in this all the other threads those are called a Child
Threads will also Executed. And when a Main thread is called this will first Execute all its child
Thread or First its child Threads those are also Called as statements will be Executed and then the
Main Thread will be Executed. For displaying the Properties of Current Running Threads ,we use
the currentThread Method. This Method will display.

1. Name of the Thread This will display the Name of Thread and the default is
main.
2. Priority of a Thread Refers to Preference given to a Thread which is 5 by
default and which is also called as value of Normal Priority.
3. Group of the Thread Which Controls the State or Name of Method where he
is Currently Executing Statements.

How to Create a Java Thread?

Java lets you create thread in following two ways:-

• By implementing the Runnable interface.


• By extending the Thread

Runnable Interface
The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable interface, a class need only implement a single method called run( ),
which is declared like this:

public void run()

Inside run( ), we will define the code that constitutes the new thread

Example:

1 public class MyClass implements Runnable {


2 public void run(){
3 [Link]("MyClass running");
4 }
5 }

Extending Java Thread


The second way to create a thread is to create a new class that extends Thread, then override the
run() method and then to create an instance of that class. The run() method is what is executed by
the thread after you call start(). Here is an example of creating a Java Thread subclass:

1 public class MyClass extends Thread {


2 public void run(){
3 [Link]("MyClass running");
4 }
5 }

Thread priorities

• Thread priorities are the integers which decide how one thread should be treated with respect
to the others.
• Thread priority decides when to switch from one running thread to another, process is called
context switching
• A thread can voluntarily release control and the highest priority thread that is ready to run
is given the CPU.
• A thread can be preempted by a higher priority thread no matter what the lower priority
thread is doing. Whenever a higher priority thread wants to run it does.
• To set the priority of the thread setPriority() method is used which is a method of the
class Thread Class.
• In place of defining the priority in integers, we can
use MIN_PRIORITY, NORM_PRIORITY or MAX_PRIORITY.
Inter-thread Communication
We have few methods through which java threads can communicate with each other. These
methods are wait(), notify(), notifyAll(). All these methods can only be called from within a
synchronized method.

1) To understand synchronization java has a concept of monitor. Monitor can be thought of as a box
which can hold only one thread. Once a thread enters the monitor all the other threads have to wait
until that thread exits the monitor.
2) wait() tells the calling thread to give up the monitor and go to sleep until some other thread enters
the same monitor and calls notify().
3) notify() wakes up the first thread that called wait() on the same object.
notifyAll() wakes up all the threads that called wait() on the same object. The highest priority
thread will run first.
UNIT – IV

MANAGING ERRORS AND EXCEPTIONS

Recognizing error types


Errors are almost unavoidable when programming. Just as when you are writing an essay and
sometimes make typos or misuse words, you will make occasional mistakes when
programming in Java. These mistakes can be referred to as bugs, errors, or exceptions.

classified into three main categories:

o syntax errors
o runtime errors
o logical errors

Identifying syntax errors


Syntax errors are the programming equivalent of spelling and grammar mistakes in
natural languages. Syntax errors include the following examples:

• Misspelled class, variable, or method names


• Misspelled keywords
• Missing semicolons
• Missing return type for methods
• Out of place or mismatched parentheses and brackets
• Undeclared or uninitialized variables
• Incorrect format of loops, methods, or other structures

In the following code example, see how many syntax errors you can spot:
public class errors {

public static vod main(String[] args) { age = 30;


int retirementFund = 10000; int
yearsInRetirement = 0; String name =
"David Johnson", for (int i = age; <= 65;
++){
recalculate(retirementFund,0.1);
}
int monthlyPension = retirementFund/yearsInRetirement/12
[Link](name + " will have $" + monthlyPension
+ " per month for retirement."];
}

public static recalculate(fundAmount, rate){ fundAmount =


fundAmount*(1+rate);
}
}
}
IDENTIFYING RUNTIME ERRORS
If you tried running the program after fixing all the syntax errors, you probably already found
your first runtime error. In the console you’ll find red text indicating there was an exception in
the thread main.

Exception is a Java class including many types of runtime problems. Java distinguishes
exceptions and errors: exceptions can—and should—be managed by the programmer, while
errors are serious problems that reasonable programs are not expected to handle.

Here, the word error is more generally applied.

Identifying logical errors


If you’ve run the code that you just fixed, did you notice anything strange? There
shouldn’t be any syntax or runtime errors, so your program should run normally.

Logical errors are perhaps the most difficult to spot, because there’s nothing to suggest
there’s an error unless you know what to expect and compare the actual results to the
expected results.

The error hint tells you that you cannot add a void to a string. But the recalculate
method returns a void. You will have to change this. Since the method is calculating a
double type, it makes sense to make the method return a double.

public static double recalculate(double fundAmount, double rate){ return


fundAmount*(1+rate); }

EXCEPTIONS

Exceptions are more specific to programming as they are events that disrupt the
execution of a program.

Exceptions can be indications that something went wrong, and they can happen
automatically as a result of something Java is unable to complete or can be explicitly thrown
when certain conditions are met.
The runtime system searches the call stack for a method that contains a block of code
that can handle the exception. This block of code is called an exception handler.

The exception handler chosen is said to catch the exception.


Try-catch-finally Statements
Exception handling is a process of identifying possible runtime errors that are likely to happen
and handle or solve this exception so that normal execution will continue. Java supports three
constructs for handling exceptions. They are

• try-catch-finally statements
• try-resource statement
• Multicatch statement

Try-catch-finally Syntax

Try
{
// statements that will possibly throw one or more
exceptions
}
catch(exception-type 1)
{
// handling code for exception-type1
}
catch(exception-type n)
{
// handling code for exception-type n.
}
finally
{
// statements to be executed after try block or catch block
}

Try block will contain statements that are likely to throw exceptions. If an
exception has occurred, control is transferred to any one of the catch blocks.

Catch block will contain statements that can solve this exception. Then execution will
continue with finally block.

finally block will be executed irrespective of exceptions. Also, there can be any
number of catch blocks for the given single try block.

ExceptionTest

// ExceptionTest. Java
import [Link].*;
import [Link].*;

public class ExceptionTest


{
public static void main(String[] args)
{
try
{
int a = [Link](args[0]); // user may enter other than int
int b = [Link](args[1]); // user may enter other than int

int sum = a / b; // infinity may happen if b is zero

int[] array = new int[2]; array[0] = a;


array[1] = b;
// beware, you try to access outside array size
array[2] = array[0] + array[1];
}
catch(NumberFormatException n)
{
[Link](“Please type only integers for a and b”);
}
catch(ArithmeticException n)
{
[Link](“Trying to divide by zero, ensure nonzero for b”);
}
catch(ArrayIndexOutOfBoundsException n) {
[Link](“Trying to access outside array index”);
}
finally
{
[Link] (“Think of all possible exceptions while designing your
code”);
}
}
}
Multicatch Statement
It is possible to catch multiple different exceptions in the same catch block. This is also
known as multicatch statement and is created using pipe character.

// [Link]
import [Link].*;
public class MultiCatch
{
public static void main(String[] args)
{
try
{
int a = [Link](args[0]); int b =
[Link](args[1]); int sum = a / b;
}
catch(NumberFormatException | ArithmeticException e )
{
[Link](“Enter only nonzero integers for a and b”);
}
}
}

Exception Hierarchy
All exception classes are subclasses of the [Link] class, which is a subclass
of the Throwable class. There is another subclass called Error which is derived from the
Throwable class. The Exception class has two main subclasses, IOException class and
RuntimeException class

User-defined Exceptions with throw and throws


Java developer can create their own exception class by extending Exception or
RuntimeException class. In order to display meaningful information about the exception,
toString() method can be overridden inside the user-defined exception class.

Throw Statement
The throw statement can be used to create an object of user-defined exception and used inside
try-catch block. For example, a school wants to check the age of a kid for possible admission
to its kinder garden programme.

Portion of Exception Hierarchy

Throws Statement
A method can use throws statement to indicate that it might throw the exception back to the
caller, so that the caller can catch this exception and take appropriate action.
//[Link] import
[Link].*;

public class UnderAgeExceptionTest1


{
public void checkAge(int age) throws UnderAgeException
{
if (age < 2)
throw new UnderAgeException(age); else
[Link](“Your child will be admitted to Kinder Garden in our
school”);
}

public static void main(String[] args)


{
UnderAgeExceptionTest1 u = new UnderAgeExceptionTest1(); Scanner sc = new
Scanner([Link]);

[Link](“What is your kid’s age ?: ”); int age =


[Link]();

try
{
[Link](age);
}
catch(UnderAgeException e)
{
[Link]([Link]());
}
}
}

Applet Programming

• An introduction is a special kind of Java program that a browser enabled with Java
technology can run by downloading from the Internet.
• An applet is typically embedded inside a web page and runs in the context of the
browser.
• An applet must be a subclass of the [Link] class, which provides the standard
interface between the applet and browser environment.
• An applet is an inherent part of a graphical user interface. It is a type of graphical
component that can be displayed in a window
• an applet is a rectangular area that can contain other components, such as buttons and
text boxes. It can display graphical elements such as images, rectangles and lines.
And it can respond to certain "events", such as when the user clicks on the applet
with a mouse.
• Applets created by the user locally are known as local applets, whereas applets
downloaded from the Internet from some remote machines and run in browser are
known as remote applets.
• The Applet class defined in the package [Link] is really only useful as a basis for
making subclasses.
• Applets are particularly well suited for providing functions in a web page which
requires more interactivity or animation that HTML can provide, such as graphical
game, complex editing or interactive data visualization. The end user is able to access
the functionality without leaving the browser.

APPLET VERSUS APPLICATION PROGRAMS


1. Applet has no main method whereas all stand-alone applications must have a main
method. Only some of the applets have main method.
2. Applets could be deployed easily on the web, while installation of Java application
is a cumbersome process.
3. An applet is an inherent part of a graphical user interface whereas an application
program is a part of character user interface.
4. Standalone application requires main method for the execution of the program. For
the execution of the applets certain methods are automatically called like init, paint,
etc.
5. One applet cannot communicate to another over communication link.
6. An Applet is a Windows-based program.

THE APPLET CLASS


The Applet class provides a standard interface between applets and their environment.
The Applet class is responsible for the overall execution of the applet as this class contains a
number of methods which control the life cycle of the applet. The hierarchy of Applet class
is as shown in

The most common methods of Applet class are listed in the table given below with a brief
description.

Method Signature Description


void destroy() Called by the browser or applet viewer to inform this applet
that it is being reclaimed and that it should destroy any
resources that it has allocated.
AppletContext Returns the context associated with the applet.
getAppletContext()
StringetAppletInfo() Returns a string that describes the applet.

void init() Called when an applet begins execution. It is the first method
called for any applet.
void resize(int width, int height) Resizes the applet according to the dimensions specified by
width and height.
void start() Called by the browser when an applet should start (or resume)
execution. It is automatically called
after init() when an applet first begins.

void stop() Called by the browser to suspend execution of the Applet.


Once stopped, an Applet is restarted when the browser calls
start.

WRITING THE FIRST APPLET

import [Link].*;
import [Link].*;
public class applet1 extends Applet
{
public void paint(Graphics g)
{
[Link]("Hello World!", 10, 30);
}

The above program must be saved in a file [Link] . After writing the program, compile
the program as follows:

javac [Link]

Coordinate system in

Java

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

Now the applet can be run locally using appletviewer tool

appletviewer [Link]
The message is displayed in a rectangle that is 300 pixels in width and 300 pixels in height.

LIFE CYCLE OF AN APPLET

A few methods are called from the birth of an applet to its death. The applet cycle
describes how these methods are called in order and how many times.
All applets have the following four methods:
public void init();
public void start();
public void stop();
public void destroy();

1. The init() method is called exactly once in an applet's life, when the applet is first
loaded. It is normally used to read PARAM tags, start downloading any other images
or media files and set up the user interface. Most applets have init() methods.

2. The start() method is called at least once in applet's life, when the applet is started
or restarted. In some cases it may be called more than once. Many applets that a
programmer writes will not have explicit start() methods and will merely inherit one
from their super class. A start () method is often used to start any threads the applet
will need while it runs.

3. The stop() method is called at least once in an applet's life, when the browser leaves
the page in which the applet is embedded. The applet's start () method will be called
at some later point when the browser returns to the page containing the applet. In
some cases the stop ( ) method may be called multiple times in an applet's life.

4. The destroy () method is called exactly once in an applet's life, just before the
browser unloads the applet. This method is generally used to perform any final
cleanup. For example, an applet that stores state on the server might send some data
back to the server before it is terminated. Many applets will not have explicit destroy
methods and just inherit one from their super class.

Example : Applet life cycle

import [Link].*;
public class lifecycle extends Applet
{
public void init()
{
//Display the statement at the bottom of the Window
show Status("The applet is initializing...");
//pause for a period of time
for (int i = 1; i < 1000000000; i++) ;
}
public void start()
{
showStatus("The applet is starting....");
for (int i = 1; i < 1000000000; i++) ;
}
public void stop()
{
showStatus("The applet is stopping....");
for (int i = 1; i < 1000000000; i++) ;
}
public void destroy()
{
showStatus("The applet is being destroyed..."); for
(int i = 1; i < 1000000000; i++) ;
}
}

//File name: [Link]

<html>
<APPLET>
<applet code ="lifecycle" height=200 width=200>
</APPLET>
</html>

APPLET TAG AND APPLET PARAMETERS

The <APPLET> tag is used to add a Java applet to a web page. The <APPLET> tag is
responsible for starting the execution of applet. This tag must have a matching </APPLET>.
A required modifier named CODE gives the name of the compiled class file that
contains the applet. HEIGHTand WIDTHmodifiers are required to specify the size of the
applet.

The general syntax for <APPLET>tag is shown as follows:

<APPLET [CODEBASE = codebaseURL]CODE = appletFile


[ALT = alternateText][ARCHIVE = archiveList][NAME = appletInstanceName] WIDTH =
pixel HEIGHT = pixels [ALIGN = alignment][VSPACE = pixels][HSPACE = pixels] >
[<PARAM NAME = AttributeName VALUE = AttributeValue>] [<PARAM
NAME = AttributeName2 VALUE = AttributeValue>]
.........
[HTML Displayed in the absence of Java]
</APPLET>

The square brackets contain options. Some of the options are explained below:

CODEBASE:

This attribute gives the URL of the directory that contains the class file. The HTML
document's URL directory is used as the CODEBASE if this attribute is not specified. It is an
optional attribute.

CODE:

This required attribute denotes the class files for the applet.

ALT:

A short text message can be assigned to this tag and same will be displayed where the
browser cannot run Java applets for whatever reason.

ARCHIVE:

If an applet uses a lot of .class files, it is a good idea to collect all the .class files into a
single .zip or .jar file. Zip and jar files are archive files which hold a number of smaller files.
The Java development system is probably capable of creating them in some way. If class
files are in an archive, the name of the archive file has to be specified in an ARCHIVE
modifier.

VSPACE and HSPACE:

These optional attributes specify the number of pixels above and below the applet
(VSPACE) and on each side of the applet (HSPACE).

NAME:

This optional attribute specifies a name for the applet instance, which makes it possible
for applets on the same page to find (and communicate with) each other. To obtain an applet
by name, getApplet(), method defined by the AppletContext interface can be used.

ALIGN:
This optional attribute specifies the alignment of the applet. The possible values of this
attribute are left, right, top, texttop, middle, absmiddle, baseline, bottom and absbottom.

PARM and VALUE:

This tag is the only way to specify an applet-specify attribute. Applets access their
attribute with the getParameter()method. This is discussed in the next section.

PASSING PARAMETER TO APPLET


Parameters can be passed to applets from the HTML file. The parameter can then be
retrieved in the applet class file and used. To pass a parameter to the applet, the PARAM tag
can be used in the HTML. Using this tag, the name of the parameter and its value can be
defined. The programmer can pass as many parameters as needed. The syntax of using
parameters is given below:
<PARAM NAME = parameter_name value = parameter_value>

For example, for passing a parameter name txt with value "hello" will be defined as:

<PARAM NAME = txt value = "hello">


In the applet code the parameter can be retrieved as:
String text = getParameter ("txt");

If parameter has no value, null will be returned as shown in the following example.

import
[Link];
import [Link].*;
public class appletparam extends Applet
{
String str, alter = null;
public void init()
{
//Get the value for the parameter alter =
getParameter("Txt");
str = (alter == null) ? "String is empty" : alter;
}
public void paint(Graphics g)
{
//Display the variable on the the screen
[Link](str, 15, 50);
}
}

/*html file
<html>
<applet code = "appletparam" width=200 height = 100>
<PARAM NAME =Txt value = "Welcome Applet">
</applet>
<html>
*/
THE PAINT, UPDATE AND REPAINT METHOD

The Paint Method


The paint method is defined by the AWT component class. The paint() method is called
by the system when the applet needs to be drawn. In a subclass of Applet, the paint() method
can be redefined to draw various graphical elements such as rectangles, lines and text on the
applet. The definition of this method must have the form as given below:
public void paint(Graphics g)
{
//draw some stuff }
}

The Update Method


This method is called when the applet has requested that a portion of its window be
redrawn. The default version of update()first fills an applet with the default background
color and then
calls paint().
public void update(Graphics g)
{
//redisplay your window, here
}
public void paint(Graphics g)
{
update(g);
}

The Repaint Method


The repaint()method is defined by the AWT. It causes the AWT run-time system to
execute a call to the applet's update()method, which, in its default implementation, calls
paint(). The method is a member function of the Component class.

The method has four overloaded forms:


void repaint()
This form of method causes the whole of the window to be repainted.

public void repaint(long tm)


public void repaint(int x, int y, int w, int h)

GRAPHICS PROGRAMMING

The Graphics Class

• A graphics context is an object belonging to the Graphics class. Instance methods are
provided in this class for drawing shapes, text and images.
• The Graphics class is an abstract class, which means that it is impossible to create a
graphics context directly, with a constructor.
• There are two ways to get a graphics context for drawing on a component:
• first of all, of course, when a component's paint () method is called, the parameter to that
method is a graphics context for drawing on the component.
• Second, to make it possible to draw on a component from outside its paint() method,
every component has an instance method called getGraphics().
• This method is a function that returns a graphics context for the component.

g = [Link]();

Drawing Lines and Rectangles

For drawing lines, the Graphics class provides the method as:
void drawLine(int x1, int y1, int x2, int y2)

The method draws a line from (x1, y1) to (x2, y2). It can be used as:
[Link](10,10,50,10);

For drawing rectangle, the Graphics class provides method as:


void drawRect(int top, int left, int width, int bottom);

For example, [Link](20, 20, 120, 50);

The method draws a rectangle whose top left coordinate is given as (20, 20), width 120
and height 50.

The following is another example:


int w = [Link]().width-1; int h =
[Link]().height-1; [Link](0, 0, w,
h);
Remember that getSize(). width is the width of the applet and getSize().height is the
height. The upper left-hand corner of the applet starts at (0, 0) not at (1, 1). This means that a
100 by 200 pixel applet includes the points with x coordinates between 0 to 99, not between 0
and 100. Similarly, the y coordinates are between 0 and 199 inclusive, not 0 and 200.

There is no separate drawSquare() method. A square is just a rectangle with equal length
sides, so to draw a square call drawRect() and pass the same number for both the height and
width argument.

A rounded rectangle can also be drown. For this purpose, there is method
drawRoundRect . The signature is:

void drawRoundRect(int top,int left,int width,int height, int arcWidth,int arcHeight)

Drawing Ovals and Circles


Java has methods to draw outlined and filled ovals. As one would probably guess, these
methods are called drawOval() and fillOval(), respectively. As one might not guess they take
identical arguments to drawRect() and fillRect(), which is given as follows.

public void drawOval(int left,int top,int width,int height); public void fillOval(int left, int
top, int width, int height);

This is as shown in the picture:

For example, to draw a circle at centre (x, y) of radius r the following will be written:
[Link](x-r, y-r, 2*r, 2*r);

The signatures are as follows:


public void drawArc(int left,int top,int width,int height, int startAngle, int stopAngle)
public void fillArc(int left,int top,int top,int width,int height,
int startAngle, int stopAngle)

Drawing Polygon
Polygons are defined by their corners. The polygon seen and created here lie in a 2-D plane.
The basic constructor for the Polygon class is
public Polygon(int[] xpoints, int[]ypoints, int npoints)

where xpoint is an array that contains the x coordinate of the polygon and ypoints is an array
that contains the y coordinate. Both should have the length npoints. Thus to construct a 3-4-5
right triangle with the right angle on the origin one would type:

int[]xpoint = {0,3,0};
int[]ypoint =(0,0,4};
Polygon myTriangle = new Polygon(xpoints, ypoints, 3};

To actually draw the polygon [Link]'s drawPolygon(Polygon


p)method is used within the paint()method like this:

[Link](myTriangle);

The arrays and number of points can be passed directly to the drawPolygon() method if so
preferred:

[Link](xpoints, ypoints, [Link]);

There is also an overhead fillPolygon() method. The syntax is exactly as one expects:

[Link](myTriangle); [Link](xpoints, ypoints,


[Link]);

Java automatically closes the polygons it draws. That is, it draws polygons that look like the
one on the right rather than on the left.

If the polygons are not wanted to be closed, a polyline can be drawn instead with the
drawPolyline()method of the Graphicsclass.

public abstract void drawPolyline(int[]xPoints, int[] yPoints, int nPoints)

Graphics Programming

Using Color
Java is designed to work with the RGB color system. An RGB color is specified by three
numbers that give the level of red, green and blue, respectively, in the color. A color in Java is
an object of the class, Color . A new color can be constructed by specifying its red, blue and
green components. For example,

Color myColor = new Color(r, g, b);

There are two constructors that can be called in this way. In the one that is commonly used
r , g and b are integers in the range 0 to 255 . In the other, they are numbers of type float in
the range 0.0Fto 1.0F. Often, constructing new colors can be avoided altogether, since
the Colorclass defines several named constants representing common colors:

The static color name may be in whole lowercase; for example, [Link] may be written as
Color. BLACK.
Programming Example

import [Link].*;
import [Link].*;
public class shapes extends Applet
{
public void paint(Graphics g)
{
[Link]([Link]);
setBackground([Link]);
[Link](10, 10, 100, 100);
[Link]([Link]);
[Link](20, 20, 120, 80);
[Link]([Link]);
[Link](200, 20, 100, 50);
[Link](200, 100, 80, 60, 10, 20);
[Link]([Link]);
[Link](100, 150, 80, 80, 0, 120);
[Link](130, 240, 80, 80);
}
}
/*[Link]
<html>
<applet code="shapes" width =200 height = 100>
</applet>
</html>
*/

Example:

<html>
<applet code="[Link]" width =200 height = 100>
</applet>
</html>

*/
import [Link].*; import
[Link].*; import
[Link].*;
public class applet3 extends Applet
{
public void paint(Graphics g)
{
[Link]([Link]); [Link](20,
20, 80, 80);
[Link]([Link]);
[Link](40, 40, 90, 90);
[Link](); [Link](100, 60,
80, 90);
}
}

Output:

You might also like