Java Programming Concepts for 4th Sem
Java Programming Concepts for 4th Sem
PROGRAMMING IN JAVA
UNIT-I
Introduction to OOPS: Paradigms of Programming Languages – Basic concepts of Object-Oriented Programming
– Differences between Procedure Oriented Programming and Object-Oriented programming - Benefits of OOPs –
Application of OOPs. Java: History – Java features – Java Environment – JDK – API. Introduction to Java:
Types of java program – Creating and Executing a Java program – Java Tokens- Java Virtual Machine (JVM) –
Command Line Arguments –Comments in Java program.
INTRODUCTION TO OOPS:
The Object-Oriented programming paradigm plays an important role in human-computer interface. It has
different components that take real world objects and perform actions on them, making live interactions between
man and the machine. Following are the components of OOPS −
⮚ This paradigm describes a real-life system where interactions are among real objects.
⮚ It models applications as a group of related objects that interact with each other.
⮚ The programming entity is modelled as a class that signifies the collection of related real-world objects.
⮚ Programming starts with the concept of real-world objects and classes.
⮚ The application is divided into numerous packages.
⮚ A package is a collection of classes.
⮚ A class is an encapsulated group of similar real-world objects.
Classes:
A class is a collection of objects. It is generic in nature. All objects of a class have the same
characteristics and interact with one another. A class has two components. They are:
● The data members
● The member functions
While data members are the features of the real world entity the user tries to represent,
member functions act on data members to use them. For e.g., if furniture is a class, then chair
is an object.
Furniture Chair;
Other e.g.,
Flower rose;
Data abstraction and Encapsulation:
Data abstraction is the phenomenon of revealing only the important features of an object,
and not considering the unimportant details. After abstracting those important details/features,
they are bounded by functions. This process is called data encapsulation. Data encapsulation
restricts the direct access of data by program or the external programming entities.
For e.g.,
Furniture chair;
Chair is an object, whose main features are:
1. a seat, (2) three or four legs, (3) a back rester. So, this is data abstraction.
The other details hidden are if it is made of steel/ iron/ wood/ plastic, color of the chair,
etc.
If the function called get details () will enable the program to get the details of the shape of
the chair, it is called data encapsulation. This is because only the function has the rights to
access the data.
Inheritance:
Inheritance is the process by which objects of one class acquire the properties of another
class. It is possible by inheriting hierarchy.
Inheritance implements one of the major advantages of OOPs called reusability.
Reusability is the concept of using the same code with or without changes to configure another
object.
Polymorphism:
It is the ability to take more than one form. A function can have a different set of arguments
with the same label; this is function overloading. An operator can perform an added function;
this is called the operator overloading. For e.g.,
int add(int,int);
void add(s1,s2);
int add(int, int, float);
int add(float, float);
In the first function, the function add (int, int) adds two integer numbers. In the second
function, the function add(s1, s2) adds two strings. This is operator overloading.
The first function add (int, int) adds two integers and the third function add (int, int, float)
adds three values. This is function overloading.
Dynamic Binding:
Binding refers to the process of linking segments of code to be executed, when the
procedure containing the segment of code is called. This is said to be static or dynamic in nature.
If the procedure call invokes the correct segment of code at the compilation time, it is static
binding. If the procedure call invokes the correct segment of code at the run time, it is dynamic
binding. (i.e., the program will not know which procedure is going to be called until the
particular instant of execution comes).
Message Passing:
The creation of objects, by default, supports the communication of objects. A message from
one object will invoke the procedure in another object, so as to produce a desired result.
Message passing involves specifying the name of the object, the name of the function
(message), and the information to be sent.
return 0;
}
Output: Output:
Enter two integers: Enter two integers:
12 12
11 11
12+11=23 12+11=23
Benefits of OOPS:
▪ Modularity for easier troubleshooting
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627
Application of oops:
o Real time systems
o Client server systems
o Hypertext and hypermedia
o Object oriented database
o Neural networks and parallel programming
o AI Expert systems
o Simulation and modelling systems
o Office automation systems
o CIM/CAD/CAM Systems
o Computer aided designs
JAVA EVOLUTION
Java History
Java is a general-purpose, object-oriented programming language developed by Sun Microsystems of the USA in
1991.
Originally called Oak by James Gosling. Java was designed for the development of software for consumer
electronic devices like TVs, VCR and Other electronic machines.
The goal had a strong impact on the development team to make the language simple, portable and reliable.
Table 1.4.1.a shows important milestones in the development of Java.
Year Development
1990 Sun Microsystems decided to develop special software that could be used to
manipulate consumer electronic devices. A term of Sun Microsystems
programmers headed by James Gosling was formed to undertake this task.
1991 After exploring the possibility of using the most popular object-oriented
language C++, 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 list 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. The Green Project team came up
with the idea of developing Web applets (tiny programs) using the new language
that could run on all types of computers connected to the Internet.
1994 The team developed a Web browser called “HotJave” to locate and run applet
programs on Internet. HotJava demonstrated the power of the new language, thus
making it instantly popular among the Internet users.
1995 Oak was renamed “Java”, due to some legal snags. Java is just a name and is not an
acronym. Many popular companies including Netscape and Microsoft announced
their support for Java.
Java established itself not only as a leader for Internet programming but also as a
1996 general-purpose object-oriented programming language. Sun releases Java
Development Kit 1.0
1997 Sun releases Java Development Kit 1.1 (JDK 1.1)
1998 Sun releases 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)
⮚ Java requires that the functions with no arguments must be declared with
empty parenthesis and not with the void keyword as done in C
⮚ Java adds new operators such as instanceof and >>>
⮚ Java adds labeled break and continue statements
⮚ Java adds many features required for object-oriented programming
1. The user sends request for HTML document to remote computer’ Web Server. The
Web Server is a program that accepts request, processes the request, and sends the
required document.
2. The HTML document is returned to the user’s browser. The document contains the
APPLET tag, which identifies the applet.
3. The applet byte code is transferred to the user’s computer.
4. The Java-enabled browser on the user’s computer interprets the byte codes and
provides output.
5. The user may have further interaction with the applet but with no further downloading
from the provider’s Web server.
Web Browsers
Web browsers are used to navigate through the information found on the net. They
allow us to retrieve the information spread across the Internet and display it using HTML.
Web browsers are
⮚ Hot Java
⮚ Netscape Navigator
⮚ Internet Explorer
Hardware And Software Requirements
Java is currently supported on Windows 95, Windows NT, Windows XP, Sun
Solaris, Macintosh and UNIX machines.
The minimum hardware and software requirements for Windows 95 version of Java
are
⮚ IBM-compatible 486 system
⮚ Minimum of 8 MB memory
⮚ Windows 95 software
⮚ A Windows-compatible sound card, if necessary
⮚ A hard drive
⮚ A CD-ROM drives
⮚ A Microsoft-compatible mouse
Java Support Systems
Systems to support Java for delivering information on the Internet as shown
below.
document.
⮚ Java Code - Java code is used for defining Java applets.
⮚ Byte Code - Compiled code and transferred to the user
Computer
Java Environment
Java Environment includes a large number of development tools known as Java
Development Kit (JDK) and classes and methods known as Java Standard
Library (JSL) or Application Programming Interface (API).
To create a Java program, we need to create a source code file using a text editor.
The source code compiled using the Java compiler javac and executed using the Java
interpreter java. The tools used to build and run application programs are shown in Fig.
/*
*Simple and More Of Java Program
* This code compute summation of two numbers
*/
class SimpleProgram
{
public static void main(String args[])
{
int a = 5, b = 5; // Declaration and initialization
int c; // Simple declaration
c = a + b;
[Link](“Summation of two numbers” + c);
}
}
program
Program is the simplest of all Java programs. Let us discuss the program line
by line and understand unique features that constitute a Java program.
The first line
class SimpleProgram
declares a class, Java is a pure object-oriented language and everything must be placed
inside a class. class is a keyword and SimpleProgram is a Java identifier that specifies
the name of the class to be defined.
Every class definition in Java begins with an opening brace “{“ and ends with a matching
closing brace “}”.
The third line
public static void main(String args[])
defines a method name main. This is the starting point for the interpreter to begin the
execution of the program. A Java application can have any number of classes but only
one of them must include a main method to initiate the execution. This line contains a
public keyword as an access modifier, static keyword, which declares this method
belongs to the entire class and not part of any object and void states that the main method
does not return any value.
String args[] declares a parameter named args, which contains any array of objects of
the class type String.
The statement
int a = 5 , b = 5;
declares variable x and y and initializes it to the value 5 and the statement int c;
merely declares a variable c. All of them have been declared as int type variables.
The executable statement in the program is
[Link](“Summation of two numbers: ” + c);
The println method is a member of the out object, which is a static data member of
System class. This line prints the result on the screen as
Summation of two numbers: 10
Here, the operator + acts as the concatenation operator of two strings. The value
of c is converted into string before concatenation. The method println always appends a
new line character to the end of the string. Every Java Program must end with a semicolon
( ; ).
In Java, the single-line comments begin with // and end at the end of the line as
shown on the lines of the declaration a, b and c. The multi-line comments by starting with
/* and end with a */ as shown at the beginning of the program.
Suggested
Documentation Section
Package Statement
Import Statements
Optional
Interface Statements
Class Definitions
Example:
Package student;
Package statement is optional.
Import statements
Interface statement
An interface is like a class but a group of method declarations. This is also an
optional section and is used only when we wish to implement the multiple inheritance
features in the program.
Class definition
A java program may contain multiple class definitions. Classes are the primary
and essential elements of a Java program.
Main Method class
A Java stand-alone program requires a main method as its starting point; this class
is the essential part of a Java program. The main method creates objects of various classes
and establishes communications between them. On reaching the end of main, the program
terminates and control passes back to the operating system.
JAVA TOKENS
Smallest individual units in a program are known as tokens. The smallest units of
the program are the characters used to write Java tokens. Java language includes five types
of tokens. They are:
⮚ Reserved Keywords
⮚ Identifiers
⮚ Literals
⮚ Operators
⮚ Separators
Reserved Keywords
Java language has reserved 50 words as keywords. Table 1.5.5.a list these
keywords. Keywords, combined with operators and separators according to syntax, form
the definition of the Java language. All keywords are to be written in lower-case letters.
Since keywords have specific meaning in Java, we cannot use them as names for variables,
classes, methods and so on.
Identifiers
Identifiers are programmer-designed tokens. They are used for naming classes,
methods, variables, objects, labels, packages and interfaces in a program.
Literals
Literals in Java are a sequence of characters (digit, letters, and other characters)
that represent constant value to be stored in variables. Java language specifies five types
of literals. They are:
⮚ Integer literals
⮚ Floating-point literals
⮚ Character literals
⮚ String literals
⮚ Boolean literals
Operators
An operator is a symbol that takes one or more arguments and operates on them
to produce a result.
Separators
Separators are symbols used to indicate where groups of code are divided and
arranged. Table lists separators and their functions.
Name Purpose
Parentheses ( ) Used to enclose parameters in method definition and invocation, also used
for defining precedence in expression, containing expressions for
flow control, and surrounding cast types.
Brackets [ ] Used to declare array types and for dereferencing array values.
JAVA STATEMENTS
The statements in Java are like sentences in natural language. Java
implements several types of statements in Fig
class SimpleProgramTest
{
public static void main(String args[])
{
[Link](“Welcome to Java” );
}
}
The virtual machine code is not machine specific. The machine specific code is
generated by the Java interpreter by acting as an intermediary between the virtual machine
and real machine as shown in Fig. 1.5.8.b.
The above program shows the use of command line arguments. Compile and
run the program with the command line as follows.
count = [Link];
The output of the program as:
No. of arguments = 4
1: BASIC
2: FORTRAN
3: C++
4: JAVA
PROGRAMMING IN JAVA
UNIT-II
Elements: Constants – Variables – Data types - Scope of variables – Type casting – Operators: Special
operators –Expressions – Evaluation of Expressions, Decision making and branching statements-
Decision making and Looping–break – labeled loop – continue Statement. Arrays: One Dimensional
Array – Creating an array – Array processing –Multidimensional Array – Vectors – Array List –
Advantages of Array List over Array Wrapper classes.
CONSTANTS:
Constants in Java refer to fixed values that do not change during the execution of a program. Types of
constant are as shown in Fig
Java Constants
Numeric Constants
Integer Constants
A whole number is called integer constants. An integer constant refers to a sequence of digits. There are
three types of integers, namely, decimal, octal and hexadecimal integer.
Decimal integers consist of a set of digits, 0 through 9, preceded by optional minus sign. Valid examples
are:
String constants
A string constant is a sequence of characters enclosed between double quotes. The characters may be
alphabets, digits special characters and blank spaces.
Constants meanings
‘ \ b’ back space
‘\f’ form feed
‘ \ n’ new line
‘ \r’ carriage return
‘ \ t’ horizontal tab
‘ \ ‘’ single quote
‘ \ “’ double quote
‘ \ \’ back slash
Symbolic constants
We often use certain unique constants in a program. These constants may appear repeatedly in a number
of places in the program. For example of such a constant is 3.142 representing the value of the
mathematical constant “pi”. We face two problems in the subsequent use of program. They are:
VARIABLES
A variable is an identifier that denotes a storage location used to store a data value. A variable may take
different values at different times during the execution of the program. Variable names may consist of
alphabets, digits, the underscore ( _) and dollar characters, with following conditions.
Integer
byte long
short int
Fig.2.3.3.b Integer Data types
We must use a byte variable to handle smaller number. This improves the speed of execution of the
program. We can make integers long by appending the letter L or l at the end of the number.
Example: 123L or 123l.
float double
Fig.2.3.3.d Floating-point data types
The float type values are single-precision numbers while the double types represent double-precision
numbers. Table 2.3.3.e gives the size of these two types.
Table 2.3.3.e Type And Size Of Floating Point
Type Size
float 4 bytes
double 8 bytes
Floating point numbers are treated as double-precision quantities. To force
them to be in single-precision mode, we must append f or F to the numbers.
Example:
1.23f 7.56923e5F
Double-precision types are used when we need greater precision in storage of floating point numbers. All
mathematical functions such as sin, cos and sqrt return double type values.
Character Type
In order to store character constants in memory, Java provided a character data type called char. The char
type assumes a size of 2 bytes but it can hold only a single character.
Boolean Type
Boolean type is used when we want to test a particular condition during the execution of the program.
There are only two values that a Boolean type can type: true or false. Boolean type denoted by the
keyword boolean and uses only one bit of storage. The words true and false cannot be used as the
identifier.
Declaration Of Variables
In Java, variables are the names of the storage locations. A variable must be declared before it is used in
the program. A variable can be used to store a value of any data type. After designing the variable names,
we must declare them to the complier. Declaration does three things:
It tells the compiler what the variable name is
It specifies what type of data the variable will hold.
The place of declaration decides the scope of the variables. The general form of declaration of a variable
is:
type variable1, variable2,……, variableN;
Variables are separated by commas. A declaration statement must end with a semicolon. Some valid
declarations are:
rollno = 1;
c1 = ‘ x ‘;
Another method to assign a value to a variable at the time of its declaration as
type variablename = value;
For Example:
int rollno = 1;
float average = 68.66;
The process of giving initial values to variables is known as the initialization. The following are valid
Java statements:
float x, y, z; // declares three float variables
int m = 3, n = 6; // declares and initializes two Int variables
line. We may display on next line by printing a new line character as follows:
[Link](“ \n “);
For Example:
[Link](“Hai ”); [Link](“ \n “);
[Link](“Java ! “);
will display the output in two lines as
Hai Java !
The println( ) method takes the information provided and displays it on a line followed by a line feed .
For Example, the statements
[Link](“Hai ”); [Link](“Java ! “);
Scope of variables
Java variables are classified into three kinds
Instance variables: Instance variables are created when the objects are instantiated.
Class variables: Class variables are global to a class and belong to the entire set of objects that class
creates.
Local variables: Variables declared and used inside the methods are called local variables.
Type Casting
We need to store a value of one type into a variable of another type. In such situation, we must cast the
value to be stored by proceeding it with the type name in parentheses. The syntax is:
type variable1 = ( type ) variable2;
The process of converting one data type to another is called casting. Examples:
int m = 50;
byte n = ( byte ) m;
long c = ( long ) m;
Four integer types can be cast to any other type except Boolean. Similarly, the float and double can be
cast to any other type except Boolean. Casting to smaller type can result in a loss of data. Casting a floating
point value to an integer will result in a loss of the fractional part. Table 2.3.8.a. lists those casts, which
are guaranteed to result in no loss of information
Automatic Conversion
For some types, it is possible to assign a value of one type to a variable of a different type without a cast.
Java does the conversion of the assigned value automatically. This is known as automatic type conversion.
For example, int is large enough to hold a byte value. Therefore,
byte b = 75;
int a = b;
are valid statements.
The process of assigning a smaller type to a larger one is known as widening or promotion and that of
assigning a larger type to a smaller one is known as narrowing.
Arithmetic Operators
Java provides all the basic arithmetic operators are listed in Table 2.4.2.a. The operators +, -, * and / all
work the same way as they do in other languages. These can operate on any built-in numeric data type of
Java. We cannot use these operators on Boolean type. The unary minus operator, in effect, multiplies its
single operand by -1. Therefore, a number preceded by a minus sign changes its sign.
Table: Arithmetic Operators
Operator Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Modulo division(Remainder)
a-b a+b
a*b a/b
a%b -a+b
Integer Arithmetic
When both the operands in single arithmetic expression such as a + b are integers, the expressions is called
an integer expression, and the operation is called integer arithmetic. Integer arithmetic yields an integer
value. In above examples if a and b are integers the a =2 and b = 2 we have the following results:
a–b = 0
a+b = 4
a*b = 4
a/b = 1 (decimal part truncated)
a%b = 0 (remainder of integer division)
For modulo division ( % ), the sign of the result is always the sign of the first operand.
Real arithmetic
An arithmetic operation involving only real operands is called real arithmetic. A real operand may
assume values either in decimal or exponential notation. The floating-point modulus operator returns the
floating-point equivalent of an integer division. What this means is that the division is carried out with
both floating-point operands, but the resulting divisor is treated as an integer, resulting in a floating-point
remainder.
Mixed-mode Arithmetic
When one of the operand is real and the other is integer, the expression is called a mixed-mode arithmetic
expression. If either operand is of the real type, then the other operand is converted to real and the real
arithmetic is performed. The result will be a real. Thus
16 / 5.0 produce the result 3.1
Whereas
16 / 5 produce the result 1
Relational Operators
We often compare two quantities, and depending on their relation, take certain decisions. For example,
we may compare the age of two persons, or the price of two items, and so on. These comparisons can be
done with the help of relational operators. Java supports six relational operators as shown in Table
Table Relational Operators
Operator Meaning
< is less than
<= is less than equal
A simple relational expression contains only one relational operator and is of the following form:
ae -1 relational operator ae – 2
When arithmetic expressions are used on either side of a relational operator, the arithmetic expressions
will be evaluated first and then the results compared. That is, arithmetic operators have a higher priority
over relational operators.
Logical Operators
Java has three logical operators as shown in Table. The logical operators && and || are used when we
want to form compound conditions by combining two or more relations. Example:
a > b && x = = 10
An expression combines two or more relational expression is called as logical expression or compound
relational expression. Logical expression also yields a value of true or false.
Assignment Operators
Assignment operators are used to assign the value of an expression to a variable. The form
v op= exp;
Where v is a variable, exp is an expression and op is a java binary operator. The operator op= is known
as the shorthand assignment operator.
a =a-1 a-=1
a = a * ( n + 1) a*=n+1
a =a %b a%=b
a = a / ( n + 1) a/=n+1
x = (a > b) ? a : b;
In this example , the value of x is the value of b.
Arithmetic Expressions
An arithmetic expression is a combination of variables, constants, and operators
.Example of Java expression are shown in Table2.4.10.a.
Table2.4.10.a
Expressions
ab-c a*b-c
ab a*b/c
c
Evaluation Of Expressions
Expressions are evaluated using assignment statement of the form
variable = expression;
variable is any valid Java variable name. When the statement is encountered, the expression is evaluated
first and the result then replaces the previous value of the variable on the left-hand side.
Examples of evaluation statements are l = x*y-z ;
m = y/z*x ;
The blank space around an operator is optional.
2.4.12 Precedence Of Arithmetic Operators
An arithmetic expression without any parentheses will be evaluated from left to right using the rules of
precedence of operators. There are two distinct priority levels in Java:
High priority * / % Low priority + -
The basic evaluation procedure includes two left-to-right passes through the expression. During the first
pass, the high priority operators are applied and second pass, the low priority operators are applied.
Consider the following evaluation statement:
x=a-b/3
When a = 9 and b = 6, the statement becomes
x=9–6/3
and evaluated as
First pass
x = 9 – 2 ( 6 / 3 evaluated )
Second pass
x=7 ( 9 - 2 evaluated )
Introducing parentheses into expression can change the order of evaluation. Parentheses may be nested,
and in such cases, the expression will proceed out from innermost set of parentheses. Every opening
parenthesis has a matching closing one. Parentheses allow us to change the order of priority.
Java permits mixing of constants and variables of different types in an expression, but during evaluation
it adheres to very strict rules of type conversion. If the operands are of different types, the ‘lower’ type is
automatically converted to the higher type before the operation proceeds. The
result is of the higher type. Table 2.4.13.a provides a reference chart for type conversion.
Table 2.4.13.a Automatic Type Conversion Chart
char byte short int long float double
char int int int int long float double
byte int int int int long float double
short int int int int long float double
int int int int int long float double
long long long long long long float double
float float float float float float float double
Double double double double double double double double
The final result of an expression is converted to the type of the variable on the left of the assignment sigh
before assigning the value to it. The following changes are occurs in final assignment.
float to int causes truncation of the fractional part.
double to float causes rounding of digits.
long to int causes dropping of the excess higher order bits.
Casting a Value
We need to store a value of one type into a variable of another type. In such situation, we must cast the
value to be stored by proceed it with the type name in parentheses. The general form of a cast is:
( type_name ) expression
Where type_name is one of the standard data types. The expression may be constant, variable or an
expression.
Examples of casts and their actions are
X = ( int ) 7.5 7.5 is converted to integer by truncation
A = ( int ) 21.3 / ( int )4.5 Evaluated as 21/4 and the result would be 5
of precedence are evaluated from left to right or from right to left, depending on level. This is known as
the associativity property of an operator. Table 2.4.14.a provides a complete list of operators, their
precedence levels, and their rules of association.
Unit Questions
Explain basic concepts of Object oriented programming.
What are the benefits of OOP? List a few areas of applications of OOP technology.
Explain features of Java.
What are the differences between Java & C and C++ & Java
Describe the structure of a typical Java program
What is a Token? List the various types of Tokens supported by Java.
What is Separators? Describe the various separators used in Java.
Explain Java virtual machine?
What are command line arguments? How are they useful?
Enumerate the rules for creating identifiers in Java.
if (test expression)
It allows the computer to evaluate the expression first and then, based on the value of expression is ‘true’
or ‘false’, it transfers the control to a particular statement
The ‘statement-block’ may be single or group of statements. If the test expression is true, the statement-
block will be executed; otherwise the execution will to the statement-x. (See Fig 2.5.2.b)
Entry
Example
if (age<18)
{
[Link](“The person is not eligible for vote”);
}
if ( test expression)
{
statement-block1;
}
else
{
statement-block2;
}
statement-x;
If the test expression is true, the statement-block1 will be executed; otherwise, the statement-block2 will
be executed, not both. In both the cases, the control is transferred to the statement-x.
{
[Link](“The person is not eligible for vote”);
}
else
{
If the test expression1 is false, the statement-block3 will be executed; otherwise it continues to perform
the second test. If test expression2 is true, the statement-block1 will be executed; other wise the statement-
block2 will be executed and then control is transferred to the statement-x.
Example
class biggest
{
public static void main(String args[])
{
int a=10,b=20,c=30; [Link](“Largest no. is:”); if (a>b)
{
if (a>c)
{
[Link](“a is largest no.”);
}
else
{
[Link](“c is largest no.”);
} }
else
{
if (c>b)
{
[Link](“c is largest no.”);
}
else
{
[Link](“b is largest no.”);
}
}
}
}
This construct is known as the else if ladder. The test conditions are evaluated from the top, downwards.
As soon as true test-condition is found, the statement associated with it is executed and control is
transferred to the statement-x. When all test n conditions become false, then the else containing default-
statement will be executed.
Example
if (marks>79) Grade=”Honours”;
else if(marks>59)
Grade=”first class”;
else if(marks>49)
Grade=”second class”; else if(marks>39)
Grade=”third class”; else
grade=”fail”;
case value-1:
case value-2:
block-1 break;
When the switch is executed, the value of expression is compared with the values value-1, value-2,...........
if a case is found then the block of statements that follows the case are executed.
The break statement at the end of each block signals the end of the particular block and control is
transferred to the statement-x.
The default is an optional case. When the value of expression not match with any of the case, the default
case will be executed. If default statement not present, no action takes place when all matches fail and the
control goes to the statement-x. (See Fig.2.5.6.a)
EXAMPLE:
Index=marks/10;
Switch (index)
{
Case 10:
Case 9:
Case 8:
Grade=”honours”;
Break;
Case 7:
Case 6:
Grade=”first class”;
Break;
Case 5:
Grade=”second class”;
Break;
Case 4:
Grade=”third class”;
Break;
Default:
Grade= “fail”;
Break;
}
DECISION MAKING WITH LOOPING
Introduction
The process of repeatedly executing a block of statements is known as looping. The statements in block
may be executed any number of times, from zero to infinite number is called an infinite loop. The program
loop consists of two segments are
Body of the loop
Control statement (tests certain conditions and then directs the repeated execution of the statements in the
body of the loop)
A Control structure may be classified either into two types are
Entry-controlled loop: The control conditions are tested before the start of the loop execution. If conditions
are not satisfied, the body of the loop will not be executed.
Exit-controlled loop: The test is performed at the end of the body of the loop and therefore body is
executed unconditionally for the first time.
{
Body of the loop
}
The while is an entry-controlled loop statement. The test condition is evaluated and if the condition is true,
then the body of the loop is executed. After execution of the body, the test condition is once again
evaluated and if it is true, the body is executed once again. These processes of repeated execution of the
body continue until the test condition finally becomes false and the control is transferred out of the loop.
On exit, the program continues with the statement immediately after the body of the loop.
Example
class total
{
public static void main(String args[])
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627
{
int sum,n; sum=0; n=1;
while (n<=5)
{
sum=sum+n; n++;
}
[Link]("sum="+sum);
}
}
O/P is:sum= 15
The Do Statement
The general form is
Initialization; do
{
O/P is : sum=15.
p = 1;
for (n = 0 ; n<17; ++n) can be rewritten as
for (p =1, n = 0 ; n<17; ++n)
Increment section may also have more than one part. For example
for (n = 0, m = 50 ; n<17; ++n, --m)
The test condition may have any compound relation and testing need not be limited only to the control
variable.
Example class total
{
public void static void main(String args[])
{
int sum,i;
sum=0; i=1;
for(i=1;i<=5;i++)
{
sum=sum+i;
}
[Link](“sum=”+sum);
}
}
o/p is :sum=15.
Nesting of loops, that is one for statement within another for statement, is allowed in java
.For example
Jump In Loops
Java permits a jump from one statement to the end or beginning of a loop as well as jump out of a loop.
int x,i=1,n=5,sum=0;
while(i<=n)
{
x=[Link]([Link]()); if (x<0)
break; sum=sum+x; i++;
}
[Link]("sum is"+sum);
}
}
O/P is: C:\jdk1.4\bin>java brea
BREAK:
The Java break statement is used to break loop or switch statement. It breaks the current flow of the
program at specified condition. In case of inner loop, it breaks only inner loop. We can use Java break
statement in all types of loops such as for loop, while loop and do-while loop.
Syntax:
Jump-statement;
break;
Example:
[Link]
Output:
1
2
3
4
LABELLED LOOP:
A label is a valid variable name that denotes the name of the loop to where the control of execution should
jump. To label a loop, place the label before the loop with a colon at the end. Therefore, a loop with the
label is called a labelled loop.
In layman terms, we can say that label is nothing but to provide a name to a loop. It is a good habit to
label a loop when using a nested loop. We can also use labels with continue and break statements.
for loop
while loop
for Loop
Labeling a for loop is useful when we want to break or continue a specific for loop according to
requirement. If we put a break statement inside an inner for loop, the compiler will jump out from the
inner loop and continue with the outer loop again.
What if we need to jump out from the outer loop using the break statement given inside the inner loop?
The answer is, we should define the label along with the colon(:) sign before the loop.
Syntax:
labelname:
for(initialization; condition; incr/decr)
{
//functionality of the loop
}
[Link]
}
}
Output:
123456789
123456789
123456789
123456789
123456789
labelName:
while ( ... )
{
//statements to execute
}
[Link]
} //end of while
} //end of main
}
Output:
Example:
loop1: for (int i=0;i<=10; i++)
{
loop2: while(x<100)
{
Y = i*x;
if(y>500)
break loop1;
}}
CONTINUE STATEMENTS:
The continue statement is used in loop control structure when you need to jump to the next iteration of
the loop immediately. It can be used with for loop or while loop.
The Java continue statement is used to continue the loop. It continues the current flow of the program and
skips the remaining code at the specified condition. In case of an inner loop, it continues the inner loop
only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.
Example:
public class Continue Example
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
[Link] (i);
}
}
}
ARRAYS
∙ An array is a group of contiguous or related data items that share a common name.
∙ A particular value is indicated by writing a number called index number or subscript in brackets
after the array name.
∙ Example: salary [10], It represent the salary of the 10th employee.
∙ Two types of Arrays are available
(i) One-Dimensional Array
(ii) Multi-Dimensional Array
Creating An Array
∙ Creation of an array involves three steps.
Declare the array.
Create memory locations.
Put values into the memory location.
Declaration of Arrays
∙ Arrays in java can be declared in two forms.
Form1: type array_name[];
Form2: type[] array_name;
Example: int number[]; float[] marks;
Creation of Arrays
Array length:
∙ The length of the array can be determined using length.
e.g., int num[]=new int[5]; int size=[Link];
//size=5
Two Dimensional Arrays
∙ In java, a table of items can be defined using two dimensional arrays.
∙ We can create a two-dimensional array as int myarray[][]; myarray=new int[3][4];
(Or) int myarray[][]=new int[3][4];
∙ This will create a table that can store 12 integer values, four across and three down.
∙ The value can be initialized by following their declaration with a list of initial values
enclosed in braces.
E.g., int table[2][3]={0,0,0,1,1,1};
(OR)
int table[][]={ {1, 2, 3}, {9, 8, 7} };
It initializes the element of the first row to zero and second row to one.
The initialization is done row by row.
VECTORS
For achieving the concepts of variable arguments to methods in Java through the use of the Vector
class contained in the [Link] package. This class can be used to create a generic dynamic array
known as vector that can hold objects of any type and any number. Vector are created like arrays
as
Vector intVect = new Vector( ); // declaring without size Vector list = new Vector( ); // declaring
with size
Vectors possess a number of advantages over arrays.
It is convenient to use vectors to store objects.
A vector can be used to store a list of objects that may vary in size.
We can add and delete objects from the list as and when required. A major condition in using
vectors is that we cannot directly store simple data type in a vector; we can only store objects.
Therefore, we need to convert simple type to objects by using wrapper classes. The vector class
supports a number of methods that can be used to manipulate the vectors created as listed in
Table3.5.5 a.
Example
import [Link].*; import [Link].*; class vect
{
public static void main(String args[]) throws IOException
{
Vector v=new Vector(); [Link]("cat"); [Link]("rat"); [Link]("snake");
[Link]("Goat"); [Link]("dog"); int len=[Link]();
String s[]=new String [len]; [Link](s); [Link]("Result is:"); for(int
i=0;i<len;i++)
{
[Link](s[i]);
}
}
}
Result is: catrat snake Goat dog
Array list
Java Array List class uses a dynamic array for storing the elements. It is like an array, but there is no size
limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. It
is found in the [Link] package. It is like the Vector in C++.
The Array List in Java can have the duplicate elements also. It implements the List interface so we can
use all the methods of the List interface here. The Array List maintains the insertion order internally.
Illustration:
Array and Array List are most used data types while developing any java applications. Both are used to store group of
objects. In this post I have tried to list down the advantages of using Array List over Arrays. Before discussing the
advantages of Array List, let’s see what the drawbacks of arrays are.
Arrays are of fixed length. You cannot change the size of the arrays once they are created.
You cannot accommodate an extra element in an array after they are created.
Memory is allocated to an array during its creation only, much before the actual elements are added to it.
Because of these drawbacks, use of arrays are less preferred. Instead of arrays, you can use Array List class which
addresses all these drawbacks. Here are some advantages of using Array List over arrays.
1) You can define Array List as re-sizable array. Size of the Array List is not fixed. Array List can grow and shrink
dynamically.
3) Array List class has many methods to manipulate the stored objects.
Array List class has methods to perform solo modifications ( add(), remove()… ), bulk modifications ( add All(),
remove All(), retain All()… ), searching( index Of(), last Index Of() ) and iterations( iterator() ).
4) If generics are not used, Array List can hold any type of objects.
5) Many are of the assumption that multiple insertion and removal operations on Array List will decrease the
performance of an application. But, there will be no significant change in the performance of an application if you use
Array List instead of arrays. Below example shows time taken to add 1000 string elements to Array List and array.
6) You can traverse an Array List in both the directions – forward and backward using List Iterator.
7) Array List can hold multiple null elements.
WRAPPER CLASSES
Vectors cannot handle primitive data type like int, float, long, char, and double. Primitive data
types may be converted into object by using the wrapper classes contained in the [Link]
package are listed in the following tables.
Table Wrapper Classes for Converting Simple Types
Simple type Wrapper Class
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
Table Converting Primitive Numbers to Object Numbers Using Constructor Methods
Constructor Calling Conversion Action
Integer IntVal = new Integer (i); Primitive integer to Integer
object
Table Converting String Object to Numeric objects Using the Static Method ValueOf()
Method Calling Conversion Action
IntValue = [Link](str) Converts string to integer
object
FloatVal = Float..ValueOf(str) Converts string to float object
DoubleVal = [Link](str) Converts string to double
object
LongVal = [Link](str) Converts string to long object
Note: parseInt() and parseLong() methods throws a NumberFormatException if the value of the
str does not represent an integer.
UNIT – III
Class and objects: Defining a class – Methods – Creating objects – accessing class members –
Constructors – Method overloading – Static members –Nesting of Methods – this keyword –
Command line input. Inheritance: Defining inheritance –types of inheritance– Overriding
methods – Final variables and methods – Final classes – Final methods -Abstract methods and
classes – Visibility Control- Interfaces: Defining interface – Extending interface - Implementing
Interface - Accessing interface variables. Strings: String Array String Methods – String Buffer
Class
Defining a Class
A class is a user-defined data type with a template that serves to define its
properties. Once the class type has been defined, we can create variables of that
type using declarations. In java these variables are called as instances of classes,
which are the actual objects.
The general form of a class definition is:
Class class name [extends superclass name]
{
[Fields declaration;]
[Methods declaration;]
}
Inside the square brackets is optional. For example
Class empty
{}
Because the body is empty, this class does not contain any properties and
cannot do anything. Class name and superclass name are any valid identifier.
The keyword extends indicates that the properties of the superclass name class
are executed to the class name class (is known as inheritance).
Field declaration
By placing data fields inside the body of the class definition are called
instance variables because they are created whenever an object of the class is
instantiated.
Example:
class Sample
{
int a, b;
}
The class Sample contains two integer type instance variables (are also
called as member variables)
Methods Declaration
A class with only data fields has no life. Methods are declared inside the
body of the class but immediately after the declaration of instance variables. The
general form of a method declaration is
type methodname (parameter-list)
{
method-body;
}
Method declarations have four basic parts:
The name of the method (methodname) is a valid identifier.
The type of the value the method returns (type). This could be simple data
type such as int as well as any type. It could even be void type, if the
method does not return any value.
A list of parameters (parameter-list) is always enclosed in parentheses.
This list contains variable names and types of all values we want to give to
the method as input.
Example:
(int m, float a, float b) // Three parameters
( ) //Empty list
Example:
class Rectangle
{
int length;
int width;
void getData(int x,int y)
{
length=x;
width=y;
}
}
Here getData method which performs operations on the data such as
length & width data members.
Creating Objects
Creating an object is also referred to as instantiating an object. Object in
Java created using new operators. The new operator creates an object of the
specified class and returns a reference to that object. Here is an example of
creating an object of type Rectangle.
Rectangle rect1; //declare
rect1=new Rectangle ();
//instantiate
Accessing Class Members
In an outside the class, we cannot access the instance variables and the
methods directly. For this, we must use the concerned object and dot operator as
[Link] = value;
[Link] (parameter-list);
Where object name - is the name of the object
Variable name - is the name of the instance variable inside object that we
wish to access
Method name - is the method that we wish to call
Parameter-list - is a comma separated list of ‘actual values” that must
match in type and number with the parameter list of the
method name declared in the class.
Example
Class Rectangle
{
int l,w;
void get(int x,int y)
{
l=x;
w=y;
}
int rectarea()
{
int area=l*w;
return(area);
}
public static void main(String args[])
{
Rectangle r=new Rectangle();
[Link](15,10);
int result=[Link]();
}
O/P is:
[Link](“Area of Rectangle is”+result);
}
C:\jdk1.4\bin>java Rectangle
Area of Rectangle is150
CONSTRUCTORS
Java supports a special type of method is called a constructor,that enables an
object to initialize itself when it is created.
Rules for forming the constructors are
Constructors have the same name as the class.
They do not specify a return type, not even void. This is because they
return the instance of the class itself.
Example
class Rectangle
{
__________
__________
}
O/P is:
intl,w;Rectangle(intx,inty)
{
l=x;w=y;
}
int rectarea()
{
int area=l*w;
return(area);
}
public static void main(String args[])
{
Rectangle r=new Rectangle(15,10);int
result=[Link]();
[Link](“Area of Rectangle is”+result);
}
C:\jdk1.4\bin>java Rectangle
METHODS OVERLOADING
In Java, it is possible to create methods that have same name, but different
parameter lists and different definitions is called method overloading. When we
call a method in an object, java matches up the method name first and then the
number and type of parameters to decide which one of the definitions to execute
is known as polymorphism.
class Rectangle
{
int l,w;
void get()
{
l=20;
w=12;
}
void get(int x,int y)
{
l=x;
w=y;
}
int rectarea()
{
int area=l*w;
return(area);
}
public static void main(String args[])
{
STATIC MEMBERS
We want to define a member that is common to all the objects accessed
without using a particular object. That is, the member belongs to the class as a
whole rather than the objects created from the class. Such members can be
defined as
static int count;
static int mix(int x, int y);
The members are declared as static are called as static members. The
static variables and static methods are often referred to as class variable and class
methods.
Static methods have several restrictions:
They can only call other static methods
They can only access static data.
They cannot refer to this or super in any way
Example
class mathod
{
static float mul(float x,float y)
{
return(x*y);
}
static float divide(float x,float y)
{
return(x/y);
}
}
class mathmain
{
public static void main(String args[])
{
float a=[Link](4.0f,5.0f);
float b=[Link](4.5f,2.2f);
[Link]("a="+a);
[Link]("b="+b);
}
}
O/P is:
C:\jdk1.4\bin>java mathmain
a=20.0
b=2.0454545
NESTING OF METHODS
A method can be called by using only its name in another method of the
same class is known as nesting of methods.
Example
class nesting
{
int a,b;
nesting()
{
a=10;
b=20;
}
int large()
{
if(a>b)
{
return(a);
}
else
{
return(b);
}
}
void display()
{
int big=large();
[Link](“The biggest no. is”+big);
}
public static void main(String args[])
{
nesting n=new nesting();
[Link]();
}
}
O/P is: The biggest no. is20
INHERITANCE:
Extending a Class
The mechanism of deriving a new class (subclass or derived class or child
class) from an old class (base or super or parent class) is called inheritance.
Syntax:
The inheritance allows subclasses to inherit all the variables and methods
of their parent classes.
Inheritance may take different forms:
Single inheritance (only one super class)
Multiple inheritance (several super classes)
Hierarchical inheritance (one super class, many subclasses)
Multilevel inheritance (derived from derived class)
These form inheritance are shown in Fig.3.4.1.a. Java does not directly
implement multiple inheritance. However, this concept is implemented using a
secondary inheritance path in the form of interfaces.
Example:
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
Output:
Programmer salary is: 40000.0
Fig.3.4.1.a
Forms of Inheritance
Single
inheritance:
When a class
inherits another class,
it is known as a single inheritance.
Example:
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}
Output:
Barking….
Eating……
Multilevel inheritance:
When there is a chain of inheritance, it is known as multilevel inheritance.
Example:
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}}
Output:
Weeping….
Barking…..
Eating…..
Hierarchical inheritance:
When two or more classes inherits a single class, it is known as hierarchical
inheritance.
Example:
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}}
Output:
Meowing….
Eating……
Multiple inheritance:
In multiple inheritance, a single subclass extends from multiple superclasses.
Example:
class A{
void msg(){[Link]("Hello");}
}
class B{
void msg(){[Link]("Welcome");}
}
class C extends A,B{//suppose if it were
Output:
Compile time error
Hybrid inheritance:
Example:
Class c
{
Public void disp ()
{
[Link](“c”);
}
}
Class A extends C
{
Public void disp ()
{
[Link](“A”);
}
}
Class B extends C
{
Public void disp ()
{
[Link](“B”);
}
}
Class D extends A
{
Public void disp ()
{
[Link](“D”);
}
Public static void main(string args[])
{
D obj =new D ();
[Link] ();
}
}
Output:
D
OVERRIDING METHODS
We want an object to respond to the same method but have different
behavior when that method is called. That means, we should override the method
defined in the superclass. This is possible by defining a method in the subclass
that has the same name, same arguments and same return type as a method in the
superclass. Then, when that method called, the method defined in the subclass is
invoked and executed instead of the one in the superclass. This is known as
overriding.
Example
class parentoverride
{
public void show()
{
[Link]("show method in Base class");
changed. Final variables, behave like class variables and they do not take any
space on individual objects of the class.
FINAL CLASSES
A class that cannot be sub-classed is called a final class. Declaring a class
final prevents any unwanted extensions to the class.
Examples:
final class Aclass { --------- }
final class Bclass extends Someclass { ---------- }
Any attempt to inherit these classes will cause an error.
FINALIZER METHODS
In Java run-time is an automatic garbage collecting system. It
automatically free ups the memory resources used by the objects. But object may
hold other non-object resources such a file descriptors or window system fonts.
The garbage collector cannot free these resources. In order to free these resources
we must use a finalize() method and it can be added to any class.
ABSTRACT METHODS AND CLASSES
Abstract method is a method that must always be redefined in a subclass,
thus making overriding compulsory. This is done by using the modifier keyword
abstract in the method definition.
Example:
abstract class shape
{
abstract void draw( );
}
When a class contains one or more abstract methods, it should also
declared abstract as in the example.
While using abstract classes, we must satisfy the following conditions:
VISIBILITY CONTROL
In inheritance inherit all the members of a class by a subclass using the
keyword extends. The variables and methods of class are visible everywhere in
the program we want to restrict the access to certain variables and methods from
outside the class. We can achieve this in Java by visibility modifiers or access
modifiers to the instance variables and methods. Java provides three types
modifiers: public, private and protected. Table 3.4.7.a shows the visibility
provided by various modifiers.
Table 3.4.7.a Visibility of Field in a Class
Access
Modifier
Access Public Protected Friendly Private Private
location (default) protected
Subclass in
Yes Yes Yes Yes No
same package
Other classes
in same Yes Yes Yes No No
package
Subclass in
Yes Yes No Yes No
other package
Non-Subclass
in other Yes No No No No
package
INTERFACE:
Introduction
Classes in Java cannot have more than one superclass. For instance a
definition like
class A extends B extends C
{
}
is not permitted in Java. Java provides alternate approaches known as interfaces
to support the concept of multiple inheritance. Although a Java class cannot be a
subclass of more than one superclass, it can implement more than one interface.
Defining Interfaces
The general form of an interface definition is:
interface interfaceName
{
variable declaration;
methods declaration;
}
Where interface – is the keyword
interfaceName – is any valid Java variable
Variables are declared as
Static final type VariableName = Value;
Methods declaration will contain only a list of methods without any body
statements.
Example:
return-type methodName1( parameter_list);
interface sports
{
static final int sptmark=70;
void display();
}
Extending Interfaces
Like classes, interface can also extend. The new interface will inherit all
the members of the superinterface. The general form of an interface is
interface name2 extends name1
{
body of name2
}
Example
interface student extends sports
{
static final int cobol=50;
static final int dbms=60;
void display2();
}
Implementing Interfaces
Interfaces are used as “superclasses whose properties are inherited by
classes. It is therefore necessary to create a class that inherits the given interface.
The general form is
class classname implements interfacename
{
body of classname
}
Here the class classname “implements” the interface interfacename. The
more general form is
class classname extends superclass
implements interfacename1,interfacename1, ………
{
body of classname
}
Here the class can extend another class while implementing interfaces.
When more than one interface, they are separated by a comma. The
implementation of interfaces can take various forms as shown in Fig. 3.6.4.a.
Example
class student
{
int regno; String name;
public void get(int r,String n)
{
regno=r;name=n;
}
public void display1()
{
[Link]("Register no.:"+regno);[Link]("Name .:"+name);
}
}
interface mark
{
static final int cobol=70;static final int sport=60;public void display2();
}
class multiple extends student implements mark
{
int total;
public void display2()
{
total=cobol+sport; [Link]("cobol mark is:"+cobol);
[Link]("sport mark is:"+sport); [Link]("Total is:"+total);
}
public static void main(String args[])
{
multiple m=new multiple();[Link](100,"kumar"); m.display1();
m.display2();
}
O/P is:
Register no.:100 Name .:kumarcobol mark is:70 sport mark is:60 Total is:130
chararray[ ] = ‘a’;
chararray[ ] = ‘i’;
In Java strings are class objects and implanted using two classes, namely
String and StringBuffer. A Java string is an instantiated object of the String class.
Strings may be declared and created as
String stringName;
stringName = new String(“string”);
Example:
String firstName;
firstName = new String (“Harshinni”);
Like arrays, it is possible to get the length of string using the lengthmethod
of the string class.
int m = [Link]( );
Java string can be concatenated using + operator.
Example:
String fullName = name1 + name2; // name1 and name2
containingstring constants
Example
class strin
{
public static void main(String args[])
{
String s1,s2,s3; s1="computer";
s2=[Link]();
[Link]("convert lowercase to uppercase letters "+s2);
s1="COMPUTER";
s2=[Link]();
[Link]("convert uppercase to lowercase letters "+s2);s1="computer";
int length=[Link]();
[Link]("Length of string constant in s1 object is "+length);
s1="computer";
s2=" science"; s3=[Link](s2);
[Link]("concatenation of two strings is "+s3);char c=[Link](2);
[Link]("Extract character from s2 object is "+c);if ([Link](s2))
{
[Link]("two strins are equals");
}
else
{
[Link]("two strings are not equals");
}
}
}
O/P is:
C:\jdk1.4\bin>java strin
convert lowercase to uppercase letters COMPUTER convert uppercase to lowercase
letters computer Length of string constant in s1 object is 8 concatenation of two
strings iscomputer science Extract character from s2 object is c two strings are not
equals
StringBuffer Class
StringBuffer creates strings of flexible length that can be modified both
length and content. We can insert characters and substring in the middle of a string,
or append another string to the end. Table 3.4.2 lists some of the methods that are
used in string manipulations.
Table 3.4.2 Commonly Used StringBuffer Methods
Method Call Task performed
[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 [Link](n) Sets the length of the string s1 to n. If n <
[Link]() s1 is [Link] n>[Link] ( ) zeros are added tos1.
class strbuf
{
public static void main(String args[])
{
StringBuffer s1=new StringBuffer("computer"); StringBuffer s2=new
StringBuffer(" department");[Link](s2);
[Link](s1);[Link](3,'u'); [Link](s2);
[Link](9,"science ");[Link](s1);
}
}
O/P is: C:\jdk1.4\bin>java strbufcomputer department deuartment
UNIT – IV
Packages: Java API Packages – System Packages – Naming Conventions –Creating &
Accessing a Package – Adding-Class to a Package – Hiding Classes. Exception
Handling: Limitations of Error handling – Advantages of Exception Handling - Types of
Errors – Basics of Exception Handling – try blocks – throwing an exception – catching an
exception –Finally statement. Multithreading: Creating Threads – Life of a Thread –
Defining & Running-Thread – Thread Methods – Thread Priority – Synchronization –
Implementing Runnable interface – Thread Scheduling.
PACKAGES:
To use the classes and or interfaces from another program without physically
copying them into the program is done by Java package. Actually, packages are the group
of classes and interfaces. The grouping is done according to functionality. Packages are
containers for the classes.
The classes contained in the packages of other programs can be easily reused.
It is possible to create classes with the same name in different packages. Thus, it
Packages hide their classes from other programs and other packages.
Packages are used to protect the classes, data and methods in a larger way than on a
class-to-class basis.
It contains the classes that support language. This package is the default package and they are
automatically imported. It includes classes of primitive data types, strings, threads and
exceptions, main functions.
This package consists of classes that are used forinput and output operations.
This package consists of utility classes such as vectors, random numbers, date etc.,
This package is useful to create GUI (Graphical User Interface) applications.
This package consists of classes for creating, implementing and executing applets.
[Link] This package contains classes for networking.
The main package in the Java is “java”. This “java” packages contains several packages.
Example:
[Link].*;
java
lang awt
Excepti
on
This is done by using the package name containing the class and then appending the
class name to it using dot (.) operator.
Examples:
[Link] [Link]
By using import keyword.
This statement must appear at the top of the program, before any class declaration.
This is used to use a same class in number of places in the program or to use number of
classes contained in the package.
Examples:
[Link];
[Link];
Naming Conventions
Packages can be named using the standard java naming rules. The rules may be followed
(not a compulsory) while naming the packages are
The first letter of the packages name should be a lowercase letters. It is used to
distinguish a class name from the package name. Usually, class name begins with uppercase
letter.
Example:
[Link](a,b);
Every package name should be unique. In some case, giving the same name to
different packages is unavoidable. In this, case domain name is added with the package name.
Example:
[Link] [Link]
Creating Packages
The general form for creating user-defined package is package packagename; // package
declarationpublic class Classname // class definition
{
----------------- // body of the class
}
where
package , public & class - are the keywords
package name & class name - are the any valid user-defined package name &class name
The steps are used in the creation of a package are
Where
md- is a make directory (DOS command) used to create directory subdirectory-
is the name of the directory, which is same as package name.
Accessing a Packages
The import statement is used to access a particular class in a package or all classes in a
[Link] general forms is
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627
where
import – is the keyword is used to import classes from package. package1,
package2, package3 & Classname- are the any valid user- defined
package name &
class name.
Example
}
}
Hiding Classes
It is possible to hide some of classes from outside of the packages by declaring the
classes as “not public“. The classes declaring as “not public“ can be used only in the same
package, not possible to access the outside of the packages is called as Hiding classes.
Exceptions
An exception is a condition that is caused by a run-time error in the program. When the java
interpreter encounters an error such as dividing an integer by zero, it creates an exception object
and throws it. If the exception object is not caught and handled properly, the interpreter will
display an error message and will stop the program execution. If you want to the program to
continue with execution of the remaining code then we try to catch the exception object thrown by
the error condition and then display an appropriate message for taking corrective actions. This task
is known as exception handling. Some common exceptions listed out in the Table 4.3.3.a. The
following tasks are usedto handling the errors.
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective action (Handle the exception) The error handling code
basically consists of two segments.
To detect errors and to throw exceptions
To catch exception and to take appropriate actions.
Types Of Errors
Errors may be classified into two types.
Compile-time errors
Run-time errors
Compile-Time Errors:
All syntax errors will be detected and displayed by Java compiler is called as compile-time
errors. Most of the compile-time errors are due to typing mistakes. Sometimes, a single error may
be the source of multiple errors. For example, use of an undeclared variable in a number of places
will cause a series of errors of type “ undefined variable”. The some common compile-time errors
are
Missing semicolons.
Missing (or mismatch) of the brackets in classes and methods.
Misspelling of identifiers and keywords.
Missing double quotes in strings.
Use of undeclared variables
Incompatible types in assignment / initialization
Bad references to objects
Use of = in place of = =operator and etc.,
Whenever the compiler displays, these kinds of error, it will not create the .class file. It is therefore
compulsory to correct all the errors before we can successfully compile and run the program.
Run-Time Errors:
A program may compile successfully creating the .class file but may not run properly. Such
programs may produce wrong results due to wrong logic or stop the program execution due to
errors like
Dividing an integer by zero.
Accessing an element that is out of the bounds of an array.
Trying to store a value into array of an incompatible class or type.
Try
{
statement; // generates an exception
}
catch ( Exception-type e)
{
statement; // processes the exception
The try block can have one or more statements that could generate an
in the block are skipped and execution jumps to the catch block that is placed next to
the try block. The catch block can have one or more statements that are necessary to
process the exception.
Example;
Example
class myexception extends Exception
{
O/p is:
caught my ExceptionNumber is too small I am always here
finally
{
[Link]("I am always here");
}}}
O/p is:
caught my ExceptionNumber is too small I am always here
finally
{
[Link]("I am always here");
}}}
O/p is:
You associate exception handlers with a try block by providing one or more catch blocks
directly after the try block. No code can be between the end of the try block and the beginning
of the first catch block.
try {
Each catch block is an exception handler that handles the type of exception indicated by its
argument. The argument type, ExceptionType, declares the type of exception that the handler
can handle and must be the name of a class that inherits from the Throwable class. The
handler can refer to the exception with name.
The catch block contains code that is executed if and when the exception handler is invoked.
The runtime system invokes the exception handler when the handler is the first one in the call
stack whose Exception Type matches the type of the exception thrown. The system considers
it a match if the thrown object can legally be assigned to the exception handler's argument.
The following are two exception handlers for the write List method:
try {
} catch (IndexOutOfBoundsException e) {
[Link]("IndexOutOfBoundsException: " + [Link]());
} catch (IOException e) {
[Link]("Caught IOException: " + [Link]());
}
Exception handlers can do more than just print error messages or halt the program. They can
do error recovery, prompt the user to make a decision, or propagate the error up to a higher-
level handler using chained exceptions, as described in the Chained Exceptions section.
Finally statement:
Java finally block is a block used to execute important code such as closing the connection,
etc.
Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception
occurs or not.
o finally block in Java can be used to put "cleanup" code such as closing a file, closing connection,
etc.
o The important statements to be printed can be placed in the finally block.
MULTITHREADED PROGRAMMING:
Introduction
A thread is small unit of program that is used to perform a particular task. Thus a process
can contain multiple threads. Each thread is used to perform a specific task, which is executed
simultaneously with other threads.
class ABC
{
-------------- Beginning
} End
Advantages of Multithreading:
Multithreading is used to write very efficient programs.
Maximum use of CPU time ie., the idle time CPU is reduced.
The time required to perform a context switch from one thread to anotheris less.
Multithreading require less overheads.
Multithreading reduces the complexity of large program.
The resources required for a threads are less than the resources required bya process.
Some Java platform supports the concept of “time slicing”. In time slicing, every thread
receives a small portion of CPU time, which is called a “quantum”. After the time period is over,
even if the thread has not finished its execution, the thread is given no more time to continue and
next thread of equal priority takes the charge of the CPU time. This is the work of Java
[Link] Threads
Creating threads in Java is simple. Threads are implemented in the form of objects that
contain a method called run ( ). The general form of run ( ) method is
public void run ( )
{
--------------------
--------------------(statements for implementing thread)
--------------------
}
The run ( ) method contains the entire body of the thread an it will be invoked by an object
of the concerned thread.
A new thread can be created in two ways.
By creating a thread class.
Create a class that extends Thread class and override its run ( ) method with the code
required by the thread.
start stop
suspend resume
sleep notify stop
wait
16
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627
Newborn
start stop
g runnable suspendedresume
17
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627
It has been made to sleep. We can put a thread to sleep for a specified
time period using the method sleep (time) where time is in milliseconds. The
thread will return to the runnable state when the specified time is elapsed. For
example, the statement sleep (1000), is block a thread for 1000 milliseconds.
(See Fig 4.4.5)
sleep(time)
The thread will be blocked until certain condition occurs by suing wait ( )
method. The notify ( ) method is used to schedule thread to run again. (See
Fig.4.4.6)
wait
g runnable waitingnotify
Fig. 4.4.6 Relinquishing control using wait ( ) method
Blocked state
A thread is in blocked state, if it is being prevented from the runnable and
running state. This happened when thread is suspended, sleeping, or waiting in
order to satisfy certain requirements. While a thread is in the blocked state, the
scheduler will simply skip over it and no CPU time is allotted, until a thread re-
18
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627
enters the runnable and running state it will not perform any operation. A
blocked thread is considered as “not runnable” but not dead.
Dead state
A thread is dead when it finishes its execution (natural death) or is
stopped (killed) by another thread (premature death). A thread can be killed as
soon as it born, or while it is running, or even when it is blocked state.
Example
/*MULTITHREAD PROGRAM*/
import [Link].*;import [Link].*;
class fact extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
{
int f=1;
for(int j=1;j<=i;j++)
{
f=f*j;
}
[Link](i+" Factorial is "+f);if(i==7)
{
try
{
sleep(5000);
}
catch(Exception e)
{}
}
19
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627
}
}
}
class prime extends Thread
{
public void run()
{
int flag=0;
for(int i=3;i<=20;i++)
{
for(int j=2;j<i;j++)
{
if(i%j==0)
{
[Link](i+" Not prime number ");flag=0;
break;
}
else
{
flag=1;
}
}
if(flag==1)
[Link](i+" Prime number");if(i==10)
{
stop();
}
}
}
}
class fib extends Thread
20
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627
{
public void run()
{
int a=-1,b=1,c,k; for(k=1;k<=10;k++)
{
c=a+b;a=b; b=c;
[Link]("Fibnoacci no is "+c);if(k==4)
{
yield();
}
}
}
}
class multi
{
public static void main(String args[])
{
fact f=new fact(); prime p=new prime();fib fi=new fib(); [Link]();
[Link]();
[Link]();
}
}
O/P is :
1 Factorial is 1
2 Factorial is 2
3 Factorial is 6
4 Factorial is 24
5 Factorial is 120
6 Factorial is 720
7 Factorial is 5040
3 Prime number
21
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627
22
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627
statements
Thread Priority
Each thread created has a priority attached to it. The scheduler allocates
time according to these priorities. The thread scheduler to decide when each
thread should be allowed to run uses thread priorities. A higher priority can
preempt the lower priority thread, thus taking the processor’s time. The priority
of the thread can be set by the method setPriority ( ). The general form is
[Link](int Number);
Where
ThreadObjectName - is the name of the thread object.
IntNumber - is an integer value (from 1 to 10) to
which the
thread’s priority is set.
The Thread class defines several priority constants areMIN_PRIORITY =
1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
The default setting of a thread priority value is NORM_PRIORITY.
Synchronization
All the threads in a program share the same memory space. So it is
possible for two threads to access the same variable and methods in an object.
Problems may occur when two or more threads accessing the same data
concurrently. The Java enables us to overcome this problem using a technique is
called as synchronization.
The keyword synchronized is used in the code to enable synchronization.
The word ‘synchronized’ can be used along with a method or within a block.
synchronized void update ( )
{
-------------- // code here is synchronized
23
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627
}
When declaring a method as synchronized, Java creates a “monitor” and
hands it over to the thread that calls the method first time. As long as the thread
contains the monitor, no other thread can enter the synchronized section of
code.
After the work is over, the thread will hand over the monitor to the next
thread that is ready to use the same resource.
To mark block of code as synchronized as shown below:
synchronized (lock object)
{
-------------- // code here is synchronized
}
When two or more threads are waiting to gain control of a resources,
due to some reasons, the condition on which waiting threads to gain control not
happened. This situation is known as deadlock.
For example, assume that the thread X must access MethodA before it
can release MethodB, but the thread Y cannot release MethodA until it gets
hold of MethodB. This is the problem to arises the dead lock.
Thread X
synchronized MethodB ( )
{
synchronized MethodA ( )
{
-------------- // code here is synchronized
}
}
Thread Y
synchronized MethodA
{
24
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627
synchronized MethodB ( )
{
-------------- // code here is synchronized
}
}
Implementing The Runnable Interface
The Runnable interface declares the run ( ) method that is required for
implementing threads in our program. To do this, we must perform the
following steps:
Declare the class as implementing Runnable interface.
Implement the run ( ) method.
Create a thread by defining an object.
Call the thread’s start ( ) method to run thread.
Example
class xrun implements Runnable
{
public void run()
{
for(int i=1;i<=6; i++)
{
[Link]("\nThreadX:"+i);
}
[Link]("End of Threadx");
}
}
class runnabletest
{
public static void main(String args[])
{
xrun runobject=new xrun();
25
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627
26
Downloaded by Saro Saro (sarojini1341@[Link])
lOMoARcPSD|50662627
UNIT – V
I/O Streams: File – Streams – Advantages - The stream classes – Byte streams –
Character streams. Applets: Introduction – Applet Life cycle – Creating & Executing
an Applet –Applet tags in HTML – Parameter tag – Aligning the display - Graphics
Class: Drawing and filling lines – Rectangles – Polygon – Circles – Arcs – Line
Graphs – Drawing Bar charts AWT Components and Even Handlers: Abstract
window tool kit – Event Handlers – Event Listeners – AWT Controls and Event
Handling: Labels – Text Component – Action Event – Buttons – Check Boxes – Item
Event – Choice– Scrollbars – Layout Managers- Input Events – Menus.
The data is lost either when variable goes out of scope or when
the program is terminated.
It is difficult to handle large amount of data using variables and
arrays.
We can overcome these problems by storing data on secondary storage
devices such as floppy disks or hard disks. The data is stored in these devices
using the concept of files.
Java supports many features for managing input and output of data using
files. Reading and writing of data in a file can be done at the level of bytes or
characters or fields. Java also provides capabilities to read and write class object
directly. The process of reading and writing objects is called object serialization.
0 0 0 0 0 0 0 0
J o h n
Field(4 Characters)
Name Field
Marks
Field Roll No. Field
Fig. 4.6.1.a Data representation in Java files
Concepts Of Streams
In file processing, input refers to the flow of data into a program and
output means the flow of data out of a program. Input to a program may come
from key board, the mouse, the memory, the disk or another program and output
from a program may go to the screen, the printer, memory, the disk, or another
program (See Fig 4.6.2.a).
Java uses the concept of streams to represent the ordered sequence of data.
A stream presents a uniform, easy-to-use, object-oriented interface between the
program and the input/output devices.
Sources Destinations
Screen
Keyboard
Mouse Printer
Java
Memory Memory
Program
Disk Disk
Network Network
Stream Classes
The [Link] package contains a large number of stream classes that provide
capabilities for processing all types of data. These classes may be categorized
into two groups based on the data type on which type operate.
Byte stream classes that provide support for handling I/O operations on
bytes.
Character stream classes that provide support for managing I/O
operations on characters.
Fig. 4.6.3.a shows how stream classes are grouped based on their functions.
Java
Stream Classes
Object
Input Stream
FileInputStream
SequenceInputStream
PipeInputStream ObjectInputStream
ByteArrayInputStream StringBufferInputStream
FilterInputStream
BufferedInputStream PushBackInputStream
DataInputStream
DataInput
Object
OutputStream
FileOutputStream ObjectOutputStream
PipedOutputStream ByteArrayOutputStream
FilterOutputStream
BufferedOutputStream PushbackOutputStream
DataOutputStream
DataOutput
Method Description
write( ) Writes a byte to the output stream
write(byte b[ ]) Writes all bytes in the array b to the output
stream
write(byte b[ ], int n, int m) Writes m bytes from array b starting from nth
byte
close( ) Closes the output stream
flush( ) Flushes the output stream
Object
Reader
BufferedReader StringReader
CharArrayReader PipeReader
InputstreamReader FilterReader
FileReader PushBackReader
Object
Reader
OutputStreamWriter
File Writer
Using Stream
All the classes are known as I/O classes, not all of them are used for
reading and writing operations only. Some perform operations such as buffering,
filtering, data conversion, counting and concatenation while carrying out I/O
tasks.
Other Useful I/O Classes
The [Link] package supports many other classes for performing certain
specialized functions. They include among others:
Random Access File
StreamTokenizer
The RandomAccessFile enables us to read and write bytes, text and Java
data types to any location in a file (when used with appropriate access
permissions). This class extends object class and implements DataInput and
DataOutput interfaces as shown in Fig.4.6.7.a. This forces the
RandomAccessFile to implement the methods described in both these
interfaces.
The class StreamTokenizer, a subclass of object can be used for breaking
up a stream of text from an input text file into meaningful pieces called tokens.
The behaviour of the StreamTokenizer class is similar to that of the
StringTokenizer (class of [Link] package) that breaks a string into its
component tokens.
Object
Interface Interface
DataInput DataOutput
RandomAccessFile
Creation Of Files
To create and use a disk file, it is necessary to decide the following about
the file and its intended purpose:
Suitable name for the file
Data type to be stored
Purpose (reading, writing, or updating)
Method of creating the file
A filename is unique string of characters that helps identify a file on the
disk. The length of a filename and characters allowed are dependent on the OS on
which the Java program is executed. A filename may contain two parts, a primary
name and an optional period with extension.
Examples:
[Link] salary
[Link] [Link]
Inventory [Link]
Data type is important to decide the type of file stream classes to be used
for handling the data. We should decide whether the data to be handled is in the
form of characters, bytes or primitive type.
The purpose of using a file must also be decided before using it. For
example, we should know whether the file is created for reading only, or writing
only, or both the operations.
For using a file, it must be opened first. This is done by creating a file
stream and then linking it to the filename. A file stream can be defined using the
classes of Reader/Input Stream for reading data and Writer/Output Stream
for writing data. The common stream classes used for various I/O operation are
given in Table. 4.6.10.a.
}
catch(IOException e)
{
[Link](e);
[Link](-1);
}
// Read character
int b;
try
{
FileReader fr=new FileReader("[Link]");
while((b=[Link]())!=-1)
{
[Link]((char)b);
}
[Link]();
}
catch(IOException e)
{
[Link](e);
[Link](-1);
}
}
}
C:\>java wrcharacters
ale m
^Z
salem
[Link](e);
[Link](-1);
}
// Read operation
int b;
try
{
FileInputStream fis=new FileInputStream("[Link]");
while((b=[Link]())!=-1)
{
[Link]((char)b);
}
[Link]();
}
catch(IOException e)
{
[Link](e);
[Link](-1);
}
}
}
O/P is:
C:\>javac [Link]
C:\>java writebyte
DELHI
MADRAS
APPLET PROGRAMMING
Introduction
Applet are small Java programs that are primarily used in Internet
computing. They can be transported over the Internet from one computer to
another computer and run suing Applet Viewer or any Web Browser. It can
perform arithmetic operations, display graphics, play sounds, accept user input,
create animation, and play interactive games. Java applet when run, it can
produce graphics, sound and moving images.
Local applets
An applet developed locally and stored in a local system is known as local
applet. The local system does not require the Internet connection.
Remote applets
Remote applet is developed by some one else and stored on a remote
computer connected to the Internet. We can download the remote applet onto our
system via the Internet and run it as shown in Fig.5.3.2.
independently. They are run from a web page using HTML tag.
Applets cannot read from or write to the files in the local computer.
Applets cannot communicate with other servers on the network.
Applets cannot run any program the local computer.
Applets are restricted from using libraries from other language such
as C or C++.
Graphics class
The paint( ) method of the applet class, when it is called actually display
the results of the applet program on the screen. The output may be text, graphics,
or sound. The paint( ) method require graphics object as an argument is declared
by the Graphics class. The general form of paint( ) method is
public void paint (Graphics g)
This requires that the applet program import the [Link] that contains the
Graphics class.
The general form of building applet program is
import [Link].*;
import [Link].*;
}
The appletclassname is the main class for the applet. When the applet is
loaded, Java creates an instance of this class, and then a series of Applet class
methods are called on that instance to execute the program.
}
Running state
Applet enters the running state when the system calls the start( ) method
of applet class. This occurs automatically after the applet is initialized. Starting
can also occur if the applet is already in ‘stopped’ (idle) state. For example we
may leave the web page temporarily to another page and return back to the page.
This again starts the applet running. The start( ) method may be called more than
once. We may override the start( ) method to create a thread to control the
applet.
public void start( )
{
----------------- (Action)
----------------- (Action)
}
Dead or Destroyed state
An applet is said to be dead when it is removed from memory. This
occurs automatically by invoking the destroy() method when we quit the
browser. Destroying stage occurs only once in the applet’s lifecycle. If the applet
has created any resources, like threads, we may override the destroy() method to
clean up these resources.
public void destroy( )
{
----------------- (Action)
}
Display State
Applet moves to the display state whenever it has to perform some output
operations on the screen. This happened immediately after the applet enters into
the running state. The paint( ) method is called to display the output. We must
override paint( ) method if we want to be displayed on the screen.
public void paint ( Graphics g)
{
----------------- (Display statements)
Move to the directory containing the source code and type the following
command:
javac [Link]
The compiled output file called [Link] is placed in the same
directory as the source.
If any error message is received, then we must check and correct the
errors, and compile the applet program again
Applet Tag
We have included a pair of <APPLET….> and </APPLET> tags in the
body section of HTML tags. The <APPLET….> tag supplies the name of the
applet to be loaded and tells the browser how much space applet requires. The
ellipsis in the tag<APPLET..> indicates that it contains certain attributes that
must be specified. The minimum requirement of <APPLET….> tag specifies
three things.
Name of the applet
Width of the applet (in pixels)
Height of the applet (in pixels)
The general form of APPLET tag is
<APPLET
CODE = [Link]
WIDTH = (in pixels)
HEIGHT = (in pixels)
>
</APPLET>
Adding Applet To Html File
Adding applet to a HTML document, we should follow the following steps:
Insert an <APPLET>tag at an appropriate place in the web
page.
Specify the name of the applet’s .class file.
If the .class file not in the current directory, use the codebase
parameter to specify
o The relative path if file on the local system, or
o The URL of the directory containing the file, if it is on a
remote system.
Specify the space required for display of the applet in terms of
width and height in pixels.
Add any user-defined parameters using <PARAM>tags.
>
[ <PARAM NAME = name1 VALUE = value1 >]
[ <PARAM NAME = name2 VALUE = value2 >]
Example
//paramapplet applet program
import [Link].*;
import [Link].*;
public class paramapplet extends Applet
{
String s;
public void init()
{
s=getParameter("str");
if(s==null)
s="Java";
s="Hello"+s;
}
public void paint(Graphics g)
{
[Link](s,20,200);
}
}
The html file for paramapplet applet program
<html>
<head>
<body>
<applet code=[Link] width=400 height=400>
<param name="str" value="applet">
</applet>
</body>
</html>
O/P is:
}
}
<html>
<body>
<applet code=[Link] width=300 height=400>
</applet>
</body>
</html>
import [Link].*;
import [Link].*;
import [Link].*;
public class fun1 extends Applet implements ActionListener
{
Label l1,l2,l3;
TextField t1,t2,t3;
Button b1;
public void init()
{
l1=new Label("enter a");
l2=new Label("enter b");
l3=new Label("result");
t1=new TextField(15);
t2=new TextField(15);
t3=new TextField(10);
b1=new Button("ADD");
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
String s=[Link]();
int a,b,c;
float d;
a=[Link]([Link]());
b=[Link]([Link]());
if([Link]("ADD"))
{
c=a+b;
[Link]([Link](c));
}
}
}
<html>
<body>
<applet code="[Link]" width=400 height=400>
</applet>
</body>
</html>
GRAPHICS PROGRAMMING
Introduction
Java Applet has its own area of the screen known as canvas, where it
creates its display. The size of an applet’s space is decided by the attributes of the
<APPLET…> tag. We can write Java applets that draw lines, figures, images,
and text in different fonts and styles.
A Java applet draws graphical image inside its space using the coordinate
system as shown in Fig.4.5.2.a. Java, coordinate system has the origin (0,0) in the
upper-left corner. The positive x values are to the right, and positive y values are
to the bottom. The values of coordinates x and y are in pixels.
The Graphics Class
Java‘s Graphics class includes methods for drawing many different types
of shapes, from simple lines to polygons to text in a variety of fonts. To draw a
shape on the screen, we may call one of the methods available in the Graphics
class. Table shows the commonly used drawing methods available in the
Graphics class. All the drawing methods have arguments representing end points,
corners, or starting locations of a shape as values in the applet’s coordinate
system. To draw a shape, we only need to use the appropriate method with the
required arguments.
Table Drawing methods of the Graphics class
Method Description
clearRect ( ) Erases a rectangular area of the canvas.
copyArea ( ) Copies a rectangular area of the canvas to another
area.
drawArc ( ) Draws a hollow arc.
drawLine ( ) Draws a straight line.
drawOval ( ) Draws a hollow oval.
drawPolygon ( ) Draws a hollow polygon
drawRect ( ) Draws a hollow rectangle.
drawRoundRect ( ) Draws a hollow rectangle with rounded corner.
drawstring ( ) Displays a text string.
( x, y) width height
top left corner
Rectangle
The drawRect ( ) method draws only the outline of a box. We can draw a
solid box using the method fillRect ( ) method. This also takes four parameters,
the first two represent the x and y coordinates of the top left corner of the
rectangle, and remaining two represent width and height of the rectangle. The
general form is
[Link](x, y, width, height);
Example:
[Link](20, 60, 30 , 20);
( x, y ) width height
starting point
Filled Rectangle
We can also draw rounded edges rectangles, using the methods
drawRoundRect ( ) and fillRoundRect ( ). These two methods are same as
drawRect ( ) and fillRect ( ) methods except that they take extra two arguments
representing the width and height of the angle of [Link] general forms are
[Link](x, y, width, height , width of angle of corner,
height of angle of corner);
[Link](x, y, width, height, width of angle of corner,
height of angle of corner);
Example:
[Link](20, 60, 30 , 20, 10, 10);
Rounded Rectangle
[Link](20, 60, 30 , 20, 10, 10);
(20, 20)
height (120)
width(160)
height (120)
width(160)
We can draw an object using a color object as follows.
[Link]([Link]);
After setting the color, all drawing operations will occur in that color.
Drawing Arcs
The drawArc ( ) method is used to draw arcs. The drawArc ( ) method
takes six arguments, the first four are the same as the arguments of drawOval ( )
method and last two represent the starting angle of the arc and the number of
degrees around the arc.
In drawing arcs, java actually formulates the arc as an oval and then draws
only a part of it as dictated by last two arguments. Java consider the 3 O’ clock
position as zero degree position and degree increase in anti-clockwise direction
as shown in Fig.4.5.5.a. So, to draw an arc from 12.00 O’ clock position to 6.00
O’ clock position, the starting angle would be 90 o, and the sweep angle would be
180o.
90 o
35 o
180 o
180 o 0o
-135 o
270 o
Fig.4.5.5.a Arc as a part of an oval Fig.4.5.5.b Drawing an ac in
clockwise
{
public void paint(Graphics g)
{
[Link](10,10,50,50);
[Link](10,60,40,30);
[Link](60,10,30,80);
[Link](20,110,60,30,5,5);
[Link](20,110,60,30,10,10);
[Link](20,20,200,120);
[Link]([Link]);
[Link](70,30,100,100);
[Link](60,125,80,40,180,180);
}
<html>
<body>
<applet code=[Link] width=400 height=600>
</applet>
</body>
</html>
O/P is:
Drawing Polygons
Polygons are shapes with many sides. The drawPolygon ( ) method is
used to draw a polygon. This method takes three arguments:
An array of integers containing x coordinates.
An array of integers containing y coordinates.
An integer for the total number of points.
It is obvious that x and y arrays should be of the equal size and we must repeat
the first point at the end of the array for closing the polygon.
We can also draw a filled polygon by using the fillPolygon ( ) method.
Second, way of calling the methods drawPolygon ( ) and fillPolygon ( ) is
to use a Polygon object. The Polygon class enables us treat the polygon as an
object. This approach involves the following steps.
Defining x coordinate values as an array.
Defining y coordinate values as an array.
Defining the number of points n.
Creating a Polygon object and initializing it with the above x, y
and n values.
Calling the method drawPolygon ( ) or fillPolygon ( ) with the
Polygon object as argument.
The Polygon class is useful to add points to the Polygon.
We first create an empty polygon and then add points to it one another.
Finally call drawPolygon ( ) method using the poly object as an argument to
complete the process of drawing the polygon.
Example
import [Link].*;
import [Link].*;
public class poly extends Applet
{
int x1[]={20,120,220,20};
int y1[]={20,120,20,20};
int n1=4;
int x2[]={120,220,220,120};
int y2[]={120,20,220,120};
int n2=4;
public void paint(Graphics g)
{
[Link](x1,y1,n1);
[Link](x2,y2,n2);
}
}
<html>
<body>
<applet code=[Link] width=400 height=400>
</applet>
</body>
</html>
O/P is:
Line Graphs
We can design applets to draw line graphs to illustrate graphically the
relationship between two variables.
Using Control Loops In Applet
We can use all control structures in an applet.
Drawing Bar Charts
Applets can be designed to display bar charts, which are commonly used
in comparative of data.
The method getParameter( ) is used to fetch the data values from the
HTML file. The getParameter( ) returns only string values and therefore we use
the wrapper class method parseInt to convert strings to integer values.
Example
import [Link].*;
import [Link].*;
public class barchart extends Applet
{
int n=0;
String label[];
int value[];
public void init()
{
try
{
n=[Link](getParameter("columns"));
label=new String[n];
value=new int[n];
label[0]=getParameter("label1");
label[1]=getParameter("label2");
label[2]=getParameter("label3");
label[3]=getParameter("label4");
value[0]=[Link](getParameter("c1"));
value[1]=[Link](getParameter("c2"));
value[2]=[Link](getParameter("c3"));
value[3]=[Link](getParameter("c4"));
}
catch(NumberFormatException e)
{}
}
public void paint(Graphics g)
{
for(int i=0;i<n;i++)
{
[Link]([Link]);
[Link](label[i],20,i*50+20);
[Link](50,i*50+10,value[i],40);
}
}
}
<html>
<body>
<applet code=[Link] width=500 height=500>
<param name="colums" value="4">
<param name="c1" value="110">
<param name="c2" value="150">
<param name="c3" value="100">
<param name="c4" value="170">
<param name="label1" value="91">
<param name="label2" value="92">
<param name="label3" value="93">
<param name="label4" value="94">
</applet>
</body>
</html>
O/P is:
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI)
or windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according to
the view of operating system. AWT is heavy weight i.e. its components are using the
resources of underlying operating system (OS).
The [Link] package provides classes for AWT API such as Text Field, Label, Text Area
Radio Button, Check Box, Choice, List etc.
The AWT tutorial will help the user to understand Java GUI programming in simple and easy
steps.
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In Java
AWT, there are classes for each component as shown in above diagram. In order to place
every component in a particular position on a screen, we need to add them to a container.
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such
as Frame, Dialog and Panel.
It is basically a screen where the where the components are placed at their specific locations.
Thus it contains and controls the layout of components
Registration Methods
For registering the component with the Listener, many classes provide the registration
methods. For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
1. Within class
2. Other class
3. Anonymous class
//create components
tf=new TextField();
[Link](60,50,170,20);
Button b=new Button("click me");
[Link](100,120,80,30);
//register listener
[Link](this);//passing current instance
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the
above example that sets the position of the component it may be button, textfield etc.