Java Notes
Java Notes
UNIT II: Constants, Variables, Data Types - Operators and Expressions – Decision
Making and Branching: if, if...else, nested if, switch, ? : Operator - Decision Making and
Looping: while, do, for – Jumps in Loops - Labeled Loops – Classes, Objects and
Methods.
UNIT III: Arrays, Strings and Vectors – Interfaces: Multiple Inheritance – Packages:
Putting Classes together – Multithreaded Programming.
UNIT V: Managing Input / Output Files in Java : Concepts of Streams- Stream Classes –
Byte Stream classes – Character stream classes – Using streams – I/O Classes – File Class
– I/O exceptions – Creation of files – Reading / Writing characters, Byte-Handling
Primitive data Types – Random Access Files.
TEXTBOOK:
1. Programming with Java – A Primer - E. Balagurusamy, 3rd Edition, TMH.
REFERENCE BOOKS:
1. The Complete Reference Java 2 - Patrick Naughton & Hebert Schildt, 3rd Edition, TMH
2. Programming with Java – John R. Hubbard, 2nd Edition, TMH.
UNIT -I
It is based upon objects(having both data and methods) that aims to incorporate the
advantages of modularity and reusability, objects, which are usually instances of classes, are used
to interact with one another to design applications and computer programs.
• Data
• Method()
• Object
• Class
Method() : user can done a task from the object is called method. It defined as function.
Object that provides a way of module programs by creating partitioned memory area for both
data and functions that can be used as templates for creating modules on demand.
Object:
Object is real time entity which consists of methods and properties to make a particular
type of data.
Class:
A class is a group of objects. It determines how an object will behave and what the object
will contain.
Method Method
Dat
a
Method
Method
II. OOPS concept in Java:
1. Object
2. Class
3. Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
1. Object:
Object is real time entity which consists of methods and properties to make a particular
type of data.
2. Class:
A class is a group of objects. It determines how an object will behave and what the object
will contain.
3. Abstraction:
[Link]:
Encapsulation is packing or combine the properties and method into a single components.
5. Inheritance :
Inheritance is a mechanism where in a now class is derived from an existing. It has parent
class and child class. Parent class is also called base class. Child class is also called derived
class.
• Single inheritance
• Multiple inheritance
• Multilevel inheritance
• Hybrid inheritance
• Hierarchical inheritance
• Multipath inheritance
6. Polymorphism:
Polymorphism is the ability of an object to take on many forms. It allows the same
function to act differently in different classes.
Types of polymorphism
When a type of the object is determined at a compiled time(by the compiler), it is known
as static binding.
Compile time:
Run time:
• When a program syntactically correct that the program was executed in the
computer system.
• That time only the memory was allocated that dynamic memory allocation.
• It is implementation of polymorphism
Dynamic Binding:
Binding refer to the linking of a procedure call to the code to be excuted in response to
the call.
Message communications
Basic steps.
E.g: [Link](name);
Employee – is an object
Salary – is a message
Name – is an information
III. BENEFITS or ADVANTAGES OF OOPS:
OOPs offers several benefits to both program designer and the user.
Object orientation contribute to the solution of many problems associated with the
development and quality of the software product.
• Through inheritance we can eliminate redundant code and extend the use of existing
classes.
• It is possible to have multiple objects to co-exist without any interference.
• Object-oriented systems can be easily upgraded from small to large system.
• Software complexity can be easily managed.
• Reusability
• Scalability
• Maintainability
• Safe and secure
• Easily accessible
• Robust
• Mobile development
• Applet
• User friendly
• Flexibility.
Applications:
Java Evolution
Java History
The history of Java is very interesting. Java was originally designed for interactive
television, but it was too advanced technology for the digital cable television industry at the time.
The history of Java starts with the Green Team. Java team members (also known as Green Team),
initiated this project to develop a language for digital devices such as set-top boxes, televisions,
etc. However, it was suited for internet programming. Later, Java technology was incorporated by
Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented,
Interpreted, and Dynamic". Java was developed by James Gosling, who is known as the father of
Java, in 1995. James Gosling and his team members started the project in the early '90s.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc.
There are given significant points that describe the history of Java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991. The small team of sun engineers called Green Team.
2) Initially designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
7) Why had they chosen java name for Java language? The team gathered to choose a new
name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They
wanted something that reflected the essence of the technology: revolutionary, dynamic, lively,
cool, unique, and easy to spell and fun to say.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java
was so unique, most of the team members preferred Java than other names.
8) Java is an island of Indonesia where the first coffee was produced (called java coffee). It is
a kind of espresso bean. Java name was chosen by James Gosling while having coffee near
his office.
9) Notice that Java is just a name, not an acronym.
10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 released in(January 23, 1996). After the first release of Java, there have been
many additional features added to the language. Now Java is being used in Windows
applications, Web applications, enterprise applications, mobile applications, cards, etc.
Each new version adds the new features in Java.
Java Version History
Many java versions have been released till now. The current stable release of Java is Java SE 10.
V. JAVA EVOLUTION :
YEAR DEVELOPMENT
1990 Sun Microsystems decided to develop special software that
could be used to manipulate consumer electronic devices.
Ateam of sun micro systems programmers headed by James
Goastling was formed to under take this task.
1991 The team announced a new language named “Oak”.
1992 The team known as green project team by sun demonstrated
the application of their new language to control a tut of home
appliances using a hand held device with a tiny touch
sensitive screen.
1993 The world wide web (www) appeared on the internet and
transformed the text based internet into a graphical rich
environment.
1994 The team developed a web browser called “Hot Java” to
locate and run applet programs on internet.
1995 Oak was renamed “Java” many popular companies including
netscape and Microsoft announced their support to Java.
1996 Sun released java development kit 1.0
1999 Sun releases java development kit 1.1(JDK 1.1)
1998 Sun release the Java 2 with version 1.2 of the software
development kit (SDK 1.2)
1999 Sun releases Java 2 platform standard edition (J2SE) and
Enterprise Edition (J2EE)
2000 J2SE with SDK 1.3 was released.
2002 J2SE with SDK 1.4 was released
2004 J2SE with JDK 5.0 (united of JDK 1.5) was released. This is
known as J2SE 5.0.
C, C++ use pointer concept, it read but java has not pointer concept.
JAVA AND C:
Protocol :
A protocol is a set of rules basically that is followed for communication with user and
computer.
TYPES :
- Java is strongly associated with the internet because of the first application program is
written in Java was hot Java.
- Internet users can use Java to create applet programs & run then locally using a Java-
enabled browser such as hot Java.
- Java applets have made the internet a true extension of the storage system of the local
computer.
- Web pages contain HTML tags that enable us to find retrieve, manipulate and
display documents world wide.
- Before Java, the world wide web was limited to the display of still images & texts.
- With the help of Java WWW is capable of supporting animation graphics, games and wide
rage special effects.
- Java communicates with a web page through a special tag called <applet>.
- Java user sends a request for an HTML document to the remote computers net
browser.
- The web-browser is a program that accepts a request, processes the request and sends the
required documents.
- The document contains the applet tag which identifies the applet. The corresponding
applet is transferred to the user computer.
- The Java enabled browser on the user's computer interprets the byte code and provide
output.
VIII. OVERVIEW OF JAVA:
IX. SIMPLE JAVA PROGRAM :
Syntax:
}
X. STRUCTURE OF JAVA PROGRAM :
XI. JAVA TOKENS :
TYPES OF TOKENS:
Java Statements
A statement specifies an action in a Java program, such as assigning the sum of x
and y to z, printing a message to the standard output, writing data to a file, etc.
• Declaration statement
• Expression statement
• Control flow statement
Declaration Statement
A declaration statement is used to declare a variable.
Expression Statement
An expression with a semicolon at the end is called an expression statement. For example,
[Link]("This is a statement");
someMethod(param1, param2);
All of these are possible in Java using control flow statements. If block, while
loop and for loop statements are examples of control flow statements.
JVM is an engine that offers the Java Code or applications runtime environment. It
transforms bytecode Java into the language of computers. JVM (Java Run Environment) is a
component of JRE. It is a Java Virtual Machine.
For many hardware and software platforms, JVMs are available (i.e. JVM depends on
the platform).
- JRE is the Java Runtime Environment – it contains a JVM, among other things, and is
what you need to run a Java program.
- JDK is the Java Development Kit – it is the JRE, but with javac (which is what you need
to compile Java source code) and has other programming tools added.
Constants
Constants are fixed values does not changed during the Execution of program. there are two
types of Constants.
Integer Constants
Integer Constants refers to a Sequence of digits which Includes only negative or positive Values
and many other things.
Real Constants
1. A Real Constant must have at Least one Digit.
2. it must have a Decimal value.
3. it could be either positive or Negative.
4. if no sign is Specified then it should be treated as Positive.
5. No Spaces and Commas are allowed in Name.
6. Like 251, 234.890 etc are Real Constants.
In The Exponential Form of Representation the Real Constant is Represented in the two
Parts The part before appearing e is called mantissa whereas the part following e is called
Exponent.
7. In Real Constant The Mantissa and Exponent Part should be Separated by letter e.
8. The Mantissa Part have may have either positive or Negative Sign.
9. Default Sign is Positive.
Character Constants
A Character is Single Alphabet a single digit or a Single Symbol that is enclosed within Single
inverted commas.
'S' ,'1' etc are Single Character Constants.
String Constants
String is a Sequence of Characters Enclosed between double Quotes. These Characters may be
digits ,Alphabets Like "Hello" , "1234" etc.
Ex:
\t For Tab ( Five Spaces in one Time )
\b Back Space etc.
Variables
A variable is a name given to a memory location. It is the basic unit of storage in a program.
• The value stored in a variable can be changed during program execution.
• A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
• In Java, all the variables must be declared before use.
A name can only be given to a memory location. It can be assigned values in two ways:
• Variable Initialization
• Assigning value by taking input
Examples:
Types of variables
There are three types of variables in Java:
• Local Variables
• Instance Variables
• Static Variables
1. Local Variable
A variable declared inside the body of the method is called local variable. To use this variable
only within that method and the other methods in the class aren't even aware that the variable exists.
2. Instance Variable
A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static.
It is called instance variable because its value is instance specific and is not shared among
instances.
3. Static variable
A variable which is declared as static is called static variable. It cannot be local. To create a
single copy of static variable and share among all the instances of the class. Memory allocation for
static variable happens only once when the class is loaded in the memory.
Example pgm:-
class Simple{
public static void main(String[] args)
{
int a=10;
int b=10;
int c=a+b;
[Link](c);
}
}
Data Types
Data types specify the size and type of values that can be stored.
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
2. Non-primitive data types: The non-primitive data types include Classes, Strings, Interfaces, and
Arrays.
Primitive data types are the building blocks of data manipulation. These are the most basic data
types available in Java language.
The Boolean data type is used to store only two possible values: true and false. This data
type is used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum
value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in place
of "int" data type.
The short data type is a 16-bit signed two's complement integer. Its value-range lies
between - 32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is
32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type
is 2 times smaller than an integer.
The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is
- 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there
is no problem about memory.
The long data type is a 64-bit two's complement integer. Its value-range lies between
- 9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807.
Its default value is 0. The long data type is used when you need a range of values more than those
provided by int.
The float data type is a single-precision 32-bit IEEE 754 floating [Link] value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in large
arrays of floating point numbers. The float data type should never be used for precise values, such
as currency. Its default value is 0.0F.
Example: float f1 = 234.5f
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double data
type also should never be used for precise values, such as currency. Its default value is 0.0d.
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000'
(or) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
An operator is a character that represents an action, for example + is an arithmetic operator that
represents addition.
1. Assignment Operator
2. Arithmetic Operator
3. Relational or Conditional Operators
4. Logical Operators
5. Increment & Decrement Operators
6. Conditional or Ternary Operator
7. Special Operator
Assignment Operator
Assignment Operator (=) is used for Initializing a value to variable or we can say
that an assignment operator is used for Assigning a value to the variable.
Ex:
int a=10;
Example:
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=20;
a+=4; // a=a+4 (a=10+4) b-=4;//b=b-4 (b=20-4)
[Link](a);
[Link](b);
}
}
Arithmetic Operators
The Arithmetic Operators are used for Performing the Mathematical Operations on
operands Like + , - , / , * , %
Operator Result
is Called as Modulus or Remainder operator
% Which gives us the Remainder after division.
+ For Addition
- for Subtraction
* For Multiplication
/ For Division
% For Modulus
Example:
class OperatorExample{
public static void main(String args[])
{
int a=10;
int b=5;
[Link](a+b); //15
[Link](a-b); //5
[Link](a*b); //50
[Link](a/b); //2
[Link](a%b); //0
}
}
Operator Result
< Less Than
! boolean not
!= not equal to
Example:
class RelationalOperator
{
public static void main(String[] args)
Operator Result
^= XOR ASSIGNMENT
== Equal To
!= Not Equal To
?: Termary if then else
Example:
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
[Link](a<b&&a++<c); //false && true = false
[Link](a); //10 because second condition is not checked
[Link](a<b&a++<c); //false && true = false
[Link](a); //11 because second condition is checked
}
}
a) Prefix Operator:
In the Prefix increment operator, value will be increment and the incremented value will
be assigned to a variable. prefix decrement operator value will be decrement and then decremented
value be assigned to the variable. The general way is represented as:
++v;
--v;
b) Postfix Operator:
In the postfix increment operator, value will be assigned to a variable and then it
will be incremented. postfix decrement operator value will be assigned and then it will be
decremented. The general way is represented as:
v++;
v--;
Example:
class OperatorExample
{
public static void main(String args[])
{
Int x=10;
[Link](x++); //10 (11)
[Link](++x); //12
[Link](x--); //12 (11)
[Link](--x); //10
}
}
Conditional Operator
This operator is used to specify the value of Variable by first checking a condition of this
Operator Works Similar to if else :- In this First it checks the condition if it is true then it will
gives the result and if a condition will false then it also Gives Some Values to the Variables
Ex:
Int A,B A=10 B=20
C=(A>B) ? 13 : 20
Example:
class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
[Link](min);
}
}
In this First ? Will Check Whether a Condition is true or not if it is true then it will gives the
value 13 to C or if Condition is False Then it will gives 20 the C Variable
Special Operators
Java Also Provides Some Special Operators Like Instance of For checking Whether
an Object is Instance of a Class or Whether an object is related to Class this will gives result
true or either False
Dot Operator
Dot Operator is used for Accessing the data and Member Function of class and This
is used by Object of Class An Object Communicates With the Member Functions of Class With
the Help of Dot Operator.
Java Expressions
Example:
a+b c
s-1/7*f
.
.
etc
Types of Expressions:
➢ if Statement
o if statement
o if-else statement
o else-if statement
➢ Conditional Operator
➢ switch statement
If Statement
If statements is used to control the program flow based on some condition, it's used
to execute block of statement if the expression evaluated to true; otherwise, it will get
skipped. This statement is the simplest way to modify the control flow of the program.
Syntax
if(test_expression)
{
statement 1;
statement 2;
...
}
Figure - Flowchart of if Statement:
Example:
public class Sample
{
if(b>a)
{
[Link]("b is greater");
}
}
}
Output:
b is greater
If Else Statements
If else statement is used to control the program flow based on some condition,
only the difference is: it's used to execute some block of statement if the expression is
evaluated to true, otherwise executes else block of statement.
Syntax:
if(test_ex
pression)
{
//execute your code
}
else
{
//execute your code
}
Example:
public class Sample
{
public static void main(String args[])
{
int a = 80, b = 30;
if (b & gt; a)
{
[Link]("b is greater");
}
Else
{
[Link]("a is greater");
}
}
Output:
a is greater
Else if Statements
Syntax:
if(test_ex
pression)
{
//execute your code
}
else if(test_expression n)
{
//execute your code
}
else
{
//execute your code
Example:
public class Sample
{
public static void main(String
args[])
{
int a = 30, b = 30;
if (b > a)
{
[Link]("b is greater");
}
else if(a > b)
{
[Link]("a is greater");
}
Else
{
[Link]("Both are equal");
}
}
}
Ouptut:
Switch Statement:
Switch statement is used when we have multiple possibilities for the if statement.
Syntax:
switch(variable or expression)
{
case 1:
//execute your code
break;
case n:
//execute your code
break;
default:
//execute your
code
break;
switch (a)
{
case 1:
[Link]("You chose One");
break;
case 2:
[Link]("You chose Two");
break;
case 3:
[Link]("You chose Three");
break;
case 4:
[Link]("You chose Four");
break;
case 5:
[Link]("You chose Five");
break;
default:
[Link]("Invalid Choice. Enter a no between 1 and
5"); break;
}
}
Output
Loop control statements are used to change the normal sequence of execution of the
loop.
Java while loops statement allows to repeatedly run the same block of
statements until a condition is met.
while loop is the most basic loop in Java. It has one control condition and executes as
long the condition is true.
The condition of the loop is tested before the body of the loop is executed;
hence it is called anentry-controlled loop.
Syntax;
While (condition)
{
statement(s);
Incrementation;
Example:
public class Sample
{
Output
Java do-while loops are very similar to the while loops, but it always
executes the block of statements at least once and furthermore as long as the condition
remains true This loop is an as exit controlled loop.
Syntax:
do
{
statement(s);
}while( condition );
Example
public class Sample
{
public static void main(String args[])
{
int n = 1, times = 0; /* local variable Initialization */
}
Output
Java for loops is very similar to Java while loops in that it continues to
process a block of code becomes false, and everything is defined in a single line.
Syntax;
for ( init; condition; increment )
{
statement(s);
Example
public class Sample
{
Output:
Java for loops:1
Java for loops:2
Java for loops:3
Java for loops:4
Java for loops:5
Jump statements.
Using break we can leave a loop even if the condition for its end is not fulfilled. It can be
used to end an infinite loop, or to force it to end before its natural end.
For example, we are going to stop the count down before its natural end (maybe because
of an engine check failure?):
#include <iostream>
int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", "; if (n==3)
{
cout << "countdown aborted!";
break;
}
}
return 0;
}
Output:
10, 9, 8, 7, 6, 5, 4, 3,
countdown aborted!
The continuestatement causes the program to skip the rest of the loop in the current
iteration as if the end of the statement block had been reached, causing it to jump to the start of
the following iteration.
#include <iostream>
int main ()
{
for (int n=10; n>0; n--)
{
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}
Output:
10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
goto allows to make an absolute jump to another point in the program. You should use
this feature with caution since its execution causes an unconditional jump ignoring any type of
nesting limitations. The destination point is identified by a label, which is then used as an
argument
for the goto statement. A label is made of a valid identifier followed by a colon (:).
Generally speaking, this instruction has no concrete use in structured or object oriented
programming aside from those that low-level programming find for it.
#include <iostream>
int main ()
{
int n=10; loop:
cout << n << ", ";
n--;
if (n>0)
goto loop;
cout << "FIRE!\n";
return 0;
}
Output:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
The exit function
The purpose of exitis to terminate the current program with a specific exit code. Its prototype is:
Syntax:
The exit code is used by some operating systems and may be used by calling programs. By
convention, an exit code of 0 means that the program finished normally and any other value means that
some error or unexpected results happened.
Classes, Objects and Methods
A Class Contains
What is Object?
In real-world an entity that has state and its behavior is known as an object.
For Example:
• A Car is an object. It has states (name, color, model) and its behavior (changing gear,
applying brakes).
• A Pen is an object. Its name is Parker; color is silver etc. known as its state. It is used to
write, so writing is its behavior.
What is Class?
The primary purpose of a class is to hold data/information. This is achieved with attributes which
are also known as data members.
The member functions determine the behavior of the class, i.e. provide a definition
for supporting various operations on data held in the form of an object.
Syntax
public class class_name
{
Data
Members;
Methods;
}
Example:
public class
Car
{
public:
double color; // Color of a
car double model; // Model
of a car
Class Members
Data Members and methods must be declared within the class definition.
Example
public class Cube
{
int length; // length is a data member of class Cube int breadth;
}
// breadth is a data member of class Cube int length ;
// Error redefinition of length
Adding Methods
A class has no life without methods. The objects created by such class cannot respond
to any message. Therefore it is necessary to add methods for manipulating the data contained
in the class. Methods are declared inside the class immediately after the variable declaration.
The general form of a method declaration is
Syntax:
type methodname (parameter-list)
{
method-body;
}
Example:
class varAccess
{
int x;
void method1( )
{
int y;
x = 10; // legal y = x; // legal
}
void method2( )
{
int z;
x = 5; //legal z = 10; //legal y = z; //illegal
}
}
After creating objects, we are discussing about the accessing class members using
objects. Each objects containing its own set of variables, we should assign values to these
variables in order to use them in our program. Since we are outside the class, we cannot access
the instance variables and the methods directly. Thus, to access them, we use the concerned
object with the dot operator. The syntax is as follows:
Syntax:
Object_name.Variable_name;
Object_name.Method_name
(parameter_list);
The instance variable and method of Movie class may be accessed and assigned values
as follows:
Examples:
[Link] = 15;
[Link] = 150;
[Link] = 25;
[Link] = 250;
Example:
import [Link].*;
class Base
{
int a,b;
void get() //Definition of Methods
{
a = 100;
b = 200;
}
void sum() //Definition of another method
{
int c = a + b;
[Link]("Sum = "+c);
}
}
class CompleteClassProgram //class with main method
{
public static void main(String args[])
{
Base obj=new Base(); //creating object
[Link](); //Accessing Methods
[Link]();
}
}
Method Overloading
Methods are used in Java to describe the behavior of an object. Methods are a collection
of statements that are group together to operate. In Java, it is possible to create methods that have
the same name, but different argument lists in various definitions, i.e., method overloading is
possible in Java, which is one of the unique features of Object Oriented Programming (OOP). In
this chapter, we will learn about how method overloading is written and how it helps us within a
Java program.
There are different ways to overload a method in Java. They are:
1. Based on the number of parameters: In this case, the entire overloading concept depends
on the number of parameters that are placed within the parenthesis of the method.
2. Based on the data type of the parameter: With the arrangement of data type, within
the parameter, overloading of the method can take place.
3. Based on the sequence of data types in parameters: The method overloading also depends
on the ordering of data types of parameters within the method.
Syntax
public class Student {
public void add(int i, int j)
{
....
}
public void add(int i)
{
....
}
}
Example
class Multiply
{
void mul(int a, int b)
{
[Link]("Sum of two=" + (a * b));
}
Constructor
Constructor is that whose name is Same as name of Variable and used for Initializing the
data members of Class and it gets Automatically called when an object of class is created But
Always Remember Some things about Constructor Like :-
• Default Constructor
• Parameterized Constructor
• Copy Constructor
Default Constructor
Default Constructor is also called as Empty Constructor which has no arguments and It is
Automatically called when we creates the object of class but Remember name of Constructor is
same as name of class.
Example:
import [Link].*;
class student
{
int a,b;
student( ) //Constructor
{
a = 100;
b = 200;
}
void sum()
{
int c = a + b;
[Link]("Sum = "+c);
}
}
class Constructor
{
public static void main(String args[])
{
student obj=new student();
[Link]();
}
}
Parameterized Constructor
This is Another type Constructor which has some Arguments and same name as class
name but it uses some Arguments So For this We have to create object of Class by passing some
Arguments at the time of creating object with the name of class.
Example
import [Link].*;
class student
{
int a,b;
student(int x, int y) //Parameterized Constructor
{
a = x; b = y;
}
int sum()
{
return(a+b);
}
}
class ParamConstructor
{
public static void main(String args[])
{
student obj=new student(40,80);
int sum= [Link]();
[Link]("Sum="+sum);
}
}
Copy Constructor
This is also Another type of Constructor. In this Constructor object of another Constructor
is passed As name Suggests you Copy means Copy values of another Class object This is used
for Copying the values of class object into an another object of class So For Calling Copy
Constructor
Example
import [Link].*;
class box
{
int h,w; //data members
box() // default constructor
{
h=10;
w=20;
}
box(int x, int y)
{
h=x;
w=y;
}
box(box obj) // Copy Constructor
{
h=obj.h;
w=obj.w;
}
void show() // Member Function
{
[Link]("\n\tHeight of Box is :\t"+h);
[Link]("\n\tWidth of Box is :\t"+w);
}
}
class CopyConstructor
{
public static void main(String args[])
{
box obj_box=new box(); //instance of default constructor
obj_box.show();
1. Arrays
Array is a group og contiguous or related data items that share a common name.
Arrays have fixed length once they are declared their size cannot be changed. In JAVA
arrays are Objects Arrays can be declared and initialized.
Individual values are called elements. Arrays can be of any variable type.
e.g: Salary[5];
Declaration of an Array
Syntax
type arrayname[];
type[] arrayname;
e.g.
int no[ ];
float[ ] per;
float marks[ ];
Creation of Arrays
e.g.
no=new int[5];
per=new float[5];
Array Initialization
Array Length
e.g:
JAVA supports single dimentional,two dimentional ,multidimentional and variable size arrays.
import [Link].*;
class sort
{
public static void main(String args[])
{
int a[]={14,32,25,17,29};
int i,j,temp;
[Link](" elements before sorting are: ");
for(i=0;i<5;i++)
[Link]("\t"+a [i]);
for(i=0;i<5;i++)
for(j=0;j<4-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=tem p;
}
}
[Link](" elements after sorting are: ");
for(i=0;i<5;i++)
[Link]("\t"+a[i]);
}
}
Program to diagonal elements of a 3X3 matrix to zero
import [Link].*;
class diagonal
{
public static void main(String args[])
{
int i,j;
int a[][]=new int[3][3];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(i==j)
{
a[i][j]=0;
[Link](" "+a[i][j]);
}
else
{
a[i][j]=1;
[Link](" "+a[i][j]);
}
}
[Link]("\n");
}
2. Strings
charArrar[0] = ‘J’;
charArrar[1] = ‘A’;
charArrar[2] = ‘V’;
charArrar[3] = ‘A’;
StringBuffer.
Syntax:
String stringName;
StringName= new String(“string”);
e.g.
String
firstname;
Firstname= new String(“Hari”);
String Methods:
It defines number of methods that allows to perform string manipulation tasks.
Method - Tasks
1. s2=[Link]() – Converts the string s1 to all lowercase
2. s2=[Link]() – Converts the string s1 to all uppercase
3. s2=[Link](‘X’,’Y’) – Replace all appearances of X with Y
4. s2=[Link]() – Remove white spaces at the beginning and end of the string s1
5. [Link](s2) – Returns true if s1 is equal to s2
6. [Link]() – Returns true if s1=s2 ignoring the case of characters
7. [Link]() – Gives length of s1
8. [Link](n)- Gives nth character of s1
9. [Link](s2) – Returns negative if s1 < s2,positive if s1 > s2 otherwise zero
10. [Link](s2) – concatenates s1 and s2
11. [Link](n) – Gives substring starting from nth character
12. [Link](n,m) – Gives substring starting from nth character upto mth
character it does not include mth character
13. StringValueOf(p) – Crates a string object of the parameter p ( simple type or object)
14. [Link]() – Creates a string representation of the object p
15. [Link](‘X’) – Gives the position of the first occurrence of ‘X’ in the string s1
16. [Link](‘X’,n) – Gives the positon of ‘X’ that occurs after nth position in the string
s1
17. [Link](variable) – Converts the parameter value to string representation.
Class Stringsort
{
static String name[] ={“pritee”,”devi”,”dev”,”chins”,”rahul”};
public static void main(String args[])
{
Int size = [Link];
String temp= null;
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(name[j].compareTo(name[i]) < 0)
{
temp= name[i]; //swap the strings
name[i]= name[j];
name[j]= temp;
}
}
for(int i=0;i<size;i++)
{
[Link](name[i]);
}
}
}
string s1
StringTokenizer
3. Vector
The concept of variable arugments to methods is achieved in JAVA with the use of
Vector Class which is present in [Link] package. This class is used to create a generic
dynamic array known as vector which can hold objects of any type and any number. The
objects do not have to be [Link] can be easily implemented as vectors.
Vector v = new Vector(); // declaration without
2.A vector can be used to store a list of objects that may vary in
size [Link] can add and delete objects from the list as and when
required
A major constraints of vectors is that we cannot directly store simple data type in a
vector we can only store objects.
We can convert simple types to objects using wrapper classes.
position e.g.
Wrapper Classes
Following are the data types and their corresponding wrapper class types.
Following are the conversation from primitive data types to object numbers using
constructor methods
Ingeger IntVal = new Integer(i) //primitive integer to Integer Object
e.g
Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface
Following is an example of an interface
/* File name : [Link] */
import [Link].*;
// Any number of import statements
Implementing Interfaces
When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the specific behaviors of the interface. If a class does not perform all the
behaviors of the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements
keyword appears in the class declaration following the extends portion of the declaration.
Example
/* File name : [Link] */
public class MammalInt implements Animal {
An interface can extend another interface in the same way that a class can extend another
class. The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.
Example
// Filename: [Link]
public interface Sports {
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
// Filename: [Link]
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
// Filename: [Link]
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
A Java class can only extend one parent class. Multiple inheritance is not allowed.
Interfaces are not classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-
separated list.
For example, if the Hockey interface extended both Sports and Event, it would be declared
as −
Example
Contents
➢ Benefits of Packages
➢ System Packages
➢ Creating Packages
➢ Using a Package
Benefits of Packages
• Classes contained in packages of other programs can be easily reused.
• Two classes in two different packages can have the same name. They can
be uniquely identified by [Link].
• Packages also provide a way for separating "design" from "coding".
• You can define classes inside a package that are not accessible by code
outside that package. You can also define class members that are only
exposed to other members of the same package.
In practical applications, we may have to build our own classes and use existing classes
libraries for designing use interfaces.
Java packages are classified into two types.
Java API provides a large number of classes grouped into different packages according to
functionality. Most of the time in our programming we use the Java System Packages. The
following are the frequently used system packages, showing the functional breakdown.
The following are the brief description of Java System Packages and their Classes:
Lang means to language. Lang classes are used by java compiler itself and therefore
[Link] they are automatically imported. Classes that are required for primitive types, strings
main functions, threads and exceptions included in it.
[Link] Util stands for language utility. It include classes such as vectors, has tables random
numbers, date etc.
Input/Output support classes are included in it. They provide the facilities for the
[Link]
input and output of data.
Awt stands for abstract window toolkit. It is used for implementing graphical user
[Link] interface in the program. They include classes for windows, buttons, Menu ,
checkbocx etc.
[Link] Net stands for networking. Therefore the classes required for communicating with
local computers as well as with internet swervers are included in it.
[Link] This pacake includes the classes for creating and implementing applets.
Creating Packages
To create a package, simply include a package command as the first statement in a Java
source file. Any class declared within that file will belong to the specified package. If you omit
the package statement, the class names are put into a default package which has no name.
package first_name;
public class firstclass
{
}
first_package\secondPackage.
Using a Package
Let us consider some simple program that will use classes from other packages. The listing
below shows a package named package1 containing a single class. Class Ademo.
package package1;
public class Ademo
{
public void show()
{
[Link]("Display the Class packclass1");
}
}
To create an object of a class (bundled in a package), in your code, you have to use its fully
qualified name.
Example:
But, it could become tedious to type the long dot-separated package path name for every
class you want to use. Instead, it is recommended you use the import statement.
Syntax
import packageName;
Once imported, you can use the class without mentioning its fully qualified name.
Example:
package p3;
import p1.*; //imports classes only in package p1 and NOT in the sub-package
p2
class c3{
public void m3(){
[Link]("Method m3 of Class c3");
}
public static void main(String args[]){
c1 obj1 = new c1();
obj1.m1();
}
}
Example
import [Link];
[Link](name);
}
}
6. Multithreaded Programming
What is Multithreading?
The process of executing multiple tasks (also called threads) simultaneously is called
multithreading. The primary purpose of multithreading is to provide simultaneous execution of
two or more parts of a program to make maximum use of CPU time. A multithreaded program
contains two or more parts that can run concurrently. It enables programmers to write in a way
where multiple activities can proceed simultaneously within a single application.
What is Multitasking?
It is the way of executing multiple tasks at a time executing them concurrently over a specified
period. Multitasking is done in two ways. These are:
1. Process-based multitasking: It is also called multiprocessing where each process has its address
in memory, i.e., each process allocates separate memory area.
1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
Following are the stages of the life cycle −
• New − A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
• Runnable − After a newly born thread is started, the thread becomes runnable. A thread
in this state is considered to be executing its task.
• Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
• Timed Waiting − A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that time
interval expires or when the event it is waiting for occurs.
• Terminated (Dead) − A runnable thread enters the terminated state when it completes its
task or otherwise terminates.
Thread Methods
The Thread Methods are used for Controlling the Behavior of the Executing threads Like
Sleeping , Suspend , Sleep all these are Methods, those are Stored Thread Class which is located
in the Java. Lang Package. And this class gets Automatically loaded When a Programs begins and
we don't have any need to add this Separately. The Thread Class provides followings Methods :-
The Thread class defines several methods that help manage [Link] table below displays the
same:
Method Meaning
getName() Obtain thread’s name
getPriority() Obtain thread’s priority
isAlive() Determine if a thread is still running
join() Wait for a thread to terminate
run() Entry point for the thread
Suspend a thread for a period of
sleep()
time
Start a thread by calling its run
start()
method
Main Thread
Every Time When we Make a Program of JAVA then this will make a Main Thread which
will makes of initialize the main Program . and in this all the other threads those are called a Child
Threads will also Executed. And when a Main thread is called this will first Execute all its child
Thread or First its child Threads those are also Called as statements will be Executed and then the
Main Thread will be Executed. For displaying the Properties of Current Running Threads ,we use
the currentThread Method. This Method will display.
1. Name of the Thread This will display the Name of Thread and the default is
main.
2. Priority of a Thread Refers to Preference given to a Thread which is 5 by
default and which is also called as value of Normal Priority.
3. Group of the Thread Which Controls the State or Name of Method where he
is Currently Executing Statements.
Runnable Interface
The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable interface, a class need only implement a single method called run( ),
which is declared like this:
Inside run( ), we will define the code that constitutes the new thread
Example:
Thread priorities
• Thread priorities are the integers which decide how one thread should be treated with respect
to the others.
• Thread priority decides when to switch from one running thread to another, process is called
context switching
• A thread can voluntarily release control and the highest priority thread that is ready to run
is given the CPU.
• A thread can be preempted by a higher priority thread no matter what the lower priority
thread is doing. Whenever a higher priority thread wants to run it does.
• To set the priority of the thread setPriority() method is used which is a method of the
class Thread Class.
• In place of defining the priority in integers, we can
use MIN_PRIORITY, NORM_PRIORITY or MAX_PRIORITY.
Inter-thread Communication
We have few methods through which java threads can communicate with each other. These
methods are wait(), notify(), notifyAll(). All these methods can only be called from within a
synchronized method.
1) To understand synchronization java has a concept of monitor. Monitor can be thought of as a box
which can hold only one thread. Once a thread enters the monitor all the other threads have to wait
until that thread exits the monitor.
2) wait() tells the calling thread to give up the monitor and go to sleep until some other thread enters
the same monitor and calls notify().
3) notify() wakes up the first thread that called wait() on the same object.
notifyAll() wakes up all the threads that called wait() on the same object. The highest priority
thread will run first.
UNIT – IV
o syntax errors
o runtime errors
o logical errors
In the following code example, see how many syntax errors you can spot:
public class errors {
Exception is a Java class including many types of runtime problems. Java distinguishes
exceptions and errors: exceptions can—and should—be managed by the programmer, while
errors are serious problems that reasonable programs are not expected to handle.
Logical errors are perhaps the most difficult to spot, because there’s nothing to suggest
there’s an error unless you know what to expect and compare the actual results to the
expected results.
The error hint tells you that you cannot add a void to a string. But the recalculate
method returns a void. You will have to change this. Since the method is calculating a
double type, it makes sense to make the method return a double.
EXCEPTIONS
Exceptions are more specific to programming as they are events that disrupt the
execution of a program.
Exceptions can be indications that something went wrong, and they can happen
automatically as a result of something Java is unable to complete or can be explicitly thrown
when certain conditions are met.
The runtime system searches the call stack for a method that contains a block of code
that can handle the exception. This block of code is called an exception handler.
• try-catch-finally statements
• try-resource statement
• Multicatch statement
•
Try-catch-finally Syntax
Try
{
// statements that will possibly throw one or more
exceptions
}
catch(exception-type 1)
{
// handling code for exception-type1
}
catch(exception-type n)
{
// handling code for exception-type n.
}
finally
{
// statements to be executed after try block or catch block
}
Try block will contain statements that are likely to throw exceptions. If an
exception has occurred, control is transferred to any one of the catch blocks.
Catch block will contain statements that can solve this exception. Then execution will
continue with finally block.
finally block will be executed irrespective of exceptions. Also, there can be any
number of catch blocks for the given single try block.
ExceptionTest
// ExceptionTest. Java
import [Link].*;
import [Link].*;
// [Link]
import [Link].*;
public class MultiCatch
{
public static void main(String[] args)
{
try
{
int a = [Link](args[0]); int b =
[Link](args[1]); int sum = a / b;
}
catch(NumberFormatException | ArithmeticException e )
{
[Link](“Enter only nonzero integers for a and b”);
}
}
}
Exception Hierarchy
All exception classes are subclasses of the [Link] class, which is a subclass
of the Throwable class. There is another subclass called Error which is derived from the
Throwable class. The Exception class has two main subclasses, IOException class and
RuntimeException class
Throw Statement
The throw statement can be used to create an object of user-defined exception and used inside
try-catch block. For example, a school wants to check the age of a kid for possible admission
to its kinder garden programme.
Throws Statement
A method can use throws statement to indicate that it might throw the exception back to the
caller, so that the caller can catch this exception and take appropriate action.
//[Link] import
[Link].*;
try
{
[Link](age);
}
catch(UnderAgeException e)
{
[Link]([Link]());
}
}
}
Applet Programming
• An introduction is a special kind of Java program that a browser enabled with Java
technology can run by downloading from the Internet.
• An applet is typically embedded inside a web page and runs in the context of the
browser.
• An applet must be a subclass of the [Link] class, which provides the standard
interface between the applet and browser environment.
• An applet is an inherent part of a graphical user interface. It is a type of graphical
component that can be displayed in a window
• an applet is a rectangular area that can contain other components, such as buttons and
text boxes. It can display graphical elements such as images, rectangles and lines.
And it can respond to certain "events", such as when the user clicks on the applet
with a mouse.
• Applets created by the user locally are known as local applets, whereas applets
downloaded from the Internet from some remote machines and run in browser are
known as remote applets.
• The Applet class defined in the package [Link] is really only useful as a basis for
making subclasses.
• Applets are particularly well suited for providing functions in a web page which
requires more interactivity or animation that HTML can provide, such as graphical
game, complex editing or interactive data visualization. The end user is able to access
the functionality without leaving the browser.
The most common methods of Applet class are listed in the table given below with a brief
description.
void init() Called when an applet begins execution. It is the first method
called for any applet.
void resize(int width, int height) Resizes the applet according to the dimensions specified by
width and height.
void start() Called by the browser when an applet should start (or resume)
execution. It is automatically called
after init() when an applet first begins.
import [Link].*;
import [Link].*;
public class applet1 extends Applet
{
public void paint(Graphics g)
{
[Link]("Hello World!", 10, 30);
}
The above program must be saved in a file [Link] . After writing the program, compile
the program as follows:
javac [Link]
Coordinate system in
Java
<html>
<applet code ="[Link]" height=300 width =300>
</applet>
</html>
appletviewer [Link]
The message is displayed in a rectangle that is 300 pixels in width and 300 pixels in height.
A few methods are called from the birth of an applet to its death. The applet cycle
describes how these methods are called in order and how many times.
All applets have the following four methods:
public void init();
public void start();
public void stop();
public void destroy();
1. The init() method is called exactly once in an applet's life, when the applet is first
loaded. It is normally used to read PARAM tags, start downloading any other images
or media files and set up the user interface. Most applets have init() methods.
2. The start() method is called at least once in applet's life, when the applet is started
or restarted. In some cases it may be called more than once. Many applets that a
programmer writes will not have explicit start() methods and will merely inherit one
from their super class. A start () method is often used to start any threads the applet
will need while it runs.
3. The stop() method is called at least once in an applet's life, when the browser leaves
the page in which the applet is embedded. The applet's start () method will be called
at some later point when the browser returns to the page containing the applet. In
some cases the stop ( ) method may be called multiple times in an applet's life.
4. The destroy () method is called exactly once in an applet's life, just before the
browser unloads the applet. This method is generally used to perform any final
cleanup. For example, an applet that stores state on the server might send some data
back to the server before it is terminated. Many applets will not have explicit destroy
methods and just inherit one from their super class.
import [Link].*;
public class lifecycle extends Applet
{
public void init()
{
//Display the statement at the bottom of the Window
show Status("The applet is initializing...");
//pause for a period of time
for (int i = 1; i < 1000000000; i++) ;
}
public void start()
{
showStatus("The applet is starting....");
for (int i = 1; i < 1000000000; i++) ;
}
public void stop()
{
showStatus("The applet is stopping....");
for (int i = 1; i < 1000000000; i++) ;
}
public void destroy()
{
showStatus("The applet is being destroyed..."); for
(int i = 1; i < 1000000000; i++) ;
}
}
<html>
<APPLET>
<applet code ="lifecycle" height=200 width=200>
</APPLET>
</html>
The <APPLET> tag is used to add a Java applet to a web page. The <APPLET> tag is
responsible for starting the execution of applet. This tag must have a matching </APPLET>.
A required modifier named CODE gives the name of the compiled class file that
contains the applet. HEIGHTand WIDTHmodifiers are required to specify the size of the
applet.
The square brackets contain options. Some of the options are explained below:
CODEBASE:
This attribute gives the URL of the directory that contains the class file. The HTML
document's URL directory is used as the CODEBASE if this attribute is not specified. It is an
optional attribute.
CODE:
This required attribute denotes the class files for the applet.
ALT:
A short text message can be assigned to this tag and same will be displayed where the
browser cannot run Java applets for whatever reason.
ARCHIVE:
If an applet uses a lot of .class files, it is a good idea to collect all the .class files into a
single .zip or .jar file. Zip and jar files are archive files which hold a number of smaller files.
The Java development system is probably capable of creating them in some way. If class
files are in an archive, the name of the archive file has to be specified in an ARCHIVE
modifier.
These optional attributes specify the number of pixels above and below the applet
(VSPACE) and on each side of the applet (HSPACE).
NAME:
This optional attribute specifies a name for the applet instance, which makes it possible
for applets on the same page to find (and communicate with) each other. To obtain an applet
by name, getApplet(), method defined by the AppletContext interface can be used.
ALIGN:
This optional attribute specifies the alignment of the applet. The possible values of this
attribute are left, right, top, texttop, middle, absmiddle, baseline, bottom and absbottom.
This tag is the only way to specify an applet-specify attribute. Applets access their
attribute with the getParameter()method. This is discussed in the next section.
For example, for passing a parameter name txt with value "hello" will be defined as:
If parameter has no value, null will be returned as shown in the following example.
import
[Link];
import [Link].*;
public class appletparam extends Applet
{
String str, alter = null;
public void init()
{
//Get the value for the parameter alter =
getParameter("Txt");
str = (alter == null) ? "String is empty" : alter;
}
public void paint(Graphics g)
{
//Display the variable on the the screen
[Link](str, 15, 50);
}
}
/*html file
<html>
<applet code = "appletparam" width=200 height = 100>
<PARAM NAME =Txt value = "Welcome Applet">
</applet>
<html>
*/
THE PAINT, UPDATE AND REPAINT METHOD
GRAPHICS PROGRAMMING
• A graphics context is an object belonging to the Graphics class. Instance methods are
provided in this class for drawing shapes, text and images.
• The Graphics class is an abstract class, which means that it is impossible to create a
graphics context directly, with a constructor.
• There are two ways to get a graphics context for drawing on a component:
• first of all, of course, when a component's paint () method is called, the parameter to that
method is a graphics context for drawing on the component.
• Second, to make it possible to draw on a component from outside its paint() method,
every component has an instance method called getGraphics().
• This method is a function that returns a graphics context for the component.
g = [Link]();
For drawing lines, the Graphics class provides the method as:
void drawLine(int x1, int y1, int x2, int y2)
The method draws a line from (x1, y1) to (x2, y2). It can be used as:
[Link](10,10,50,10);
The method draws a rectangle whose top left coordinate is given as (20, 20), width 120
and height 50.
There is no separate drawSquare() method. A square is just a rectangle with equal length
sides, so to draw a square call drawRect() and pass the same number for both the height and
width argument.
A rounded rectangle can also be drown. For this purpose, there is method
drawRoundRect . The signature is:
public void drawOval(int left,int top,int width,int height); public void fillOval(int left, int
top, int width, int height);
For example, to draw a circle at centre (x, y) of radius r the following will be written:
[Link](x-r, y-r, 2*r, 2*r);
Drawing Polygon
Polygons are defined by their corners. The polygon seen and created here lie in a 2-D plane.
The basic constructor for the Polygon class is
public Polygon(int[] xpoints, int[]ypoints, int npoints)
where xpoint is an array that contains the x coordinate of the polygon and ypoints is an array
that contains the y coordinate. Both should have the length npoints. Thus to construct a 3-4-5
right triangle with the right angle on the origin one would type:
int[]xpoint = {0,3,0};
int[]ypoint =(0,0,4};
Polygon myTriangle = new Polygon(xpoints, ypoints, 3};
[Link](myTriangle);
The arrays and number of points can be passed directly to the drawPolygon() method if so
preferred:
There is also an overhead fillPolygon() method. The syntax is exactly as one expects:
Java automatically closes the polygons it draws. That is, it draws polygons that look like the
one on the right rather than on the left.
If the polygons are not wanted to be closed, a polyline can be drawn instead with the
drawPolyline()method of the Graphicsclass.
Graphics Programming
Using Color
Java is designed to work with the RGB color system. An RGB color is specified by three
numbers that give the level of red, green and blue, respectively, in the color. A color in Java is
an object of the class, Color . A new color can be constructed by specifying its red, blue and
green components. For example,
There are two constructors that can be called in this way. In the one that is commonly used
r , g and b are integers in the range 0 to 255 . In the other, they are numbers of type float in
the range 0.0Fto 1.0F. Often, constructing new colors can be avoided altogether, since
the Colorclass defines several named constants representing common colors:
The static color name may be in whole lowercase; for example, [Link] may be written as
Color. BLACK.
Programming Example
import [Link].*;
import [Link].*;
public class shapes extends Applet
{
public void paint(Graphics g)
{
[Link]([Link]);
setBackground([Link]);
[Link](10, 10, 100, 100);
[Link]([Link]);
[Link](20, 20, 120, 80);
[Link]([Link]);
[Link](200, 20, 100, 50);
[Link](200, 100, 80, 60, 10, 20);
[Link]([Link]);
[Link](100, 150, 80, 80, 0, 120);
[Link](130, 240, 80, 80);
}
}
/*[Link]
<html>
<applet code="shapes" width =200 height = 100>
</applet>
</html>
*/
Example:
<html>
<applet code="[Link]" width =200 height = 100>
</applet>
</html>
*/
import [Link].*; import
[Link].*; import
[Link].*;
public class applet3 extends Applet
{
public void paint(Graphics g)
{
[Link]([Link]); [Link](20,
20, 80, 80);
[Link]([Link]);
[Link](40, 40, 90, 90);
[Link](); [Link](100, 60,
80, 90);
}
}
Output: