Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

SYBCA - JavaNotes Unit 1 5

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

SYBCA - JavaNotes Unit 1 5

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Unit -1

 Java History the idea of “Web Applet”.


 Java is general purpose, object orented prog 1994 To run java applet, concept of java enabled
language developed by James Gosline and his browser, “Hot java” introduced.
team working in Sun Micro Sytem of USA in
1991 1995 Due to legal problems “Oak” renamed to
java.
 Orignially this language was named as OAK
and later on renamed to Java. 1996 Java established as Internet programming
language and also general purpose OO
 Java was designed for the devlopment of language.
software for consumer electrocnic devices like
TV,VCR, Microwave, Toasters, etc 1997 Sun MS released JDK 1.1

 This language was developed to solve the 1998 Sun MS released SDK 1.2
challenges of the languages existing at that 1999 Sun MS released J2EE
time in terms of :
2000 J2SE with SDK1.3 was released
o Simpliciy,
2002 J2SE with SDK1.4 was released
o Reliability and
2004 J2SE with JDK5.0 was released
o Portability
 By this time, java established in market in
 Java developed from its pre-decessor
following editions:-
languages C & C++, by using their many
features. o Standard Edition
 The historical milestones of java language o Enterprise Edition
development are:
o Micro Edition

1990 Team headed by James Gosling formed to
decide software language for consumer  Java Features
electronic device.
 Modern programming languages (C++, VB,
1991 Announce of Ook etc) were having many problems.
1992 “Green Project” team demonstrated  To overcome these James Gosling & his team
application using this new language for provided solution as Java language.
home appliances, hand-held devides and
 While developing this language, C & C++
touch sensitive screen.
languages were used as predecessor.
1993 For www, “Green Proj Team” suggested
 They added many new features and many
useless features were removed.
 Due ot this, java can be used to develop 4] Robust & Secure –
application and also web applets.
- Java code is said to be robust (avoid possible
 The different features supported are:- runtime error) and also secure due to following
reasons:
1) Compiled and Interpreter based
- strict compile and run-time checking or
2) Platform Independent
datatypes
3) Object Oriented
- garbage collection for virtual memory
4) Robust and secure management

5) Distributed - exception handling to handle all possible


runtime errors
6) Simple, small and familiar
- no pointers hence no chances of damage.
7) Multithreaded & Interactve
- virus free & secure web applets.
8) High performance
5] Distributed –
9) Dynamic & Extensible
- java helps to devlop network programs (socket
1] Compiled and Interpreter based programming) , hence java program developed on one
- As like any other high-level language, java lang. system can be easily transferred on other.
code also to be compiled. 6] Simple, small and familiar
-First it get converted to intermediate code having - Java doest not uses redundant features of C & C++ (
Bytecode instruction. It is done by “javac” compiler pointer, pre-processor directives, etc) hence it
& saved in file with .class extenion. becomes simple to use.
- once the bytecode is ready, it can be interpreted - Due to OO features, reusability is posible hence
using interpreter i.e. java interpreter. lengthy code is not required and java code becomes
- in interpretation, each bytecode instruction get small.
converted into machine code line by line and - most the java syntax is as like C & C++ hence, if
executed. any famililar with C, C++ can easily understand java
2] Platform – independent and portable code.

- Platform of any Computer or device represented 7) Multithreaded & Interactve


using Hardware ( Micro-processor) & software - By this , single java code can be divided into
(Operating System). multiple smaller executable parts to handle multiple
- Java code developed on one h/w –s/w platform can tasks simultaneously.
be easily transferred and executed on any other - Also highly interactive , user-friendly graphical
platform hence it is called platform independent. E.g. application can also be built using java language.
java code developed on Win-7 with P-3 processor can
be executed on Linux –Celeron-II platform. 8) High performance

3] Object Orineted - Due to bytecode creation, it is possbile that, java


code executes at high speed and also due to multi-
- Java is true /pure object oriented language & hence threading there is no waste and wating time.
supports all OO features like class, object,
inheritance, polymorphism, encapsulation, binding, 9) Dynamic & Extensible
etc.
- java langugage code and be easily linked with new
- Every function of java language belongs to class. and updated libraries hence it is said to be dynamic
language.
- Also java allows to call or access functions of other  For this “import” keyword can be used in
programming language to be called in java code following ways:
hence it is extensible.
a) to include single class
 Java programming structure
import java.lang.System;
- as java is programming language, it allows to write
b) to include all classes
java program. The general structure to write a java
program can be given as: import java.lang.*;
4. Interface statement –
- It is one optional section in java program.
- Interface concept is newly added feature in java
language to overcome the limitaiton of multiple
inheritance.
- Interface is as like class with some similarities and
many differences.
 From above structure it is clear that, java
program uses many sections, some are - Interface can be created using “interface” keyword
optional and some are compulsory. as:

 These different sections are : interface <IntfaceName>


{
1. Documentation section – it is one sugeested ----
section for use. It is used to give short ----
}
defination about the purpose of java program 5. class Defination – class is one the most
 It helps in easy understanding about the fundamental component of OO programming.
program. It can be given as comment line - As java is pure OO language, it needs at least one
either using: class to execute the program i.e. Main Class.
a) Single comment – using // - A class containing defination of main method is
b) Multi-line – using /*….*/ called main class.

2. Package statement – It is one optional - A class in java code can be created as:
section in java program. class <ClassName>
{
 It is used to inform compiler about the ----
package name to which the current java ----
program belongs. }
 For this, java language supports “package” 6. main method defination – this is one compulsory
keyword, that can be used as: part of executable java program.
package <PackageName>; - As like C, C++, a java program execution starts with
main method.
package myproj;
- main method must be defined within main class as:
3. Import statement - It is one optional section
in java program. class <ClassName>
{
 It is necessary to include the required java public static void main(String args[ ])
lib/package for current program as like header {
----
files of C & C++. ----
}
}
C++ Vs Java
 Once the java prog. is coded, it must be saved
by “ClassName” with “.java” extension. C++ Java

Complete .e.g It is only extension of It is pure OOPS


OOPS language.
 How java differs from C & C++
C++ supports pre- These are not supported
- Java as a language, developed from C & C++ as pre- processor directives like by java.
decessor languages. Hence it is having many common #include, #define, #ifdef
features.
Function with argument Function without
- Also to make joava more powerful many redundant in C++ can use void in argument in java must be
features are removed and new features are added, due parenthesis with empty parenthesis.
to this java shows considerable differences between
with C & C++. Functions with default These are not supported
argument can be defined. by java.
Java Vs C
C++ lang allows to create Pointer not supported by
and use pointer. java.
C Java C++ supports Operator Operator Overloading not
It belongs to POP It belongs to OOP Overloading. supported by java.
category category C++ supports multiple Java does not support
C lang supports sizeof, These are not supported inheritance multiple inheritance.
typedef keywords. by java. C++ supports concept of Java does not supports
C lang supports struct These are not supported global variables globar variable, instead it
,union datatypes by java. uses class variable

C lang supports storage These are not supported Destructor function is Destructor function is
class keywords like auto, by java. supported replaced by finalize( )
extern,register function.

C supports signed & These are not supported Main method in C++ Main method must be
unsgined types. by java. class program, must be within class
outside the class
C supports pre-processor These are not supported
directives like #include, by java. Class defination must Class defination not
#define, #ifdef ends with ; (semicolon) ended by ; (semicolon)

Functions with default These are not supported


argument can be defined. by java.  JVM
C lang allows to create Pointer not supported by - As java is high level language, hence its code must
and use pointer. java. be translated before execution.
Function without Function without - To implment java language, it requres its own
argument in C can use argument in java must be runtime environment i.e called JRE.
void in parenthesis with empty parenthesis
- JRE creates a virtual machine with-in real machine
Not supported by C lang. Java supports new hence it is called JVM i.e. machine within machine.
operators like instanceof,
>>>
- When java code is compiled by compiler, first it gets  Java Runtime Env
converted into bytecode / intermediate code which is
- To implment java programming on any system &
not machine specific (dependent).
also to execute java program on any system, a special
Java Java Virtual
environment is required i.e. Java Runtime
Machine Environment.
Program Compiler
(Byte Code)
(Source - JRE no only helps to build java program but also to
Code)
compile and execute it.
- And this bytecode is used by virtual machine for
- JRE consist of:
further processing.
i) JVM – It is virtual machine within real machine. In
- When java is interpreted by java interpreter, each
this, first bytecode is created by compiler.
line of byte code is conveted into machine code and
then executed as: - This bytecode is further converted into machine
code for execution.
Bytecode Java Machine
Interpret Code - due to this, java lang becomes machine independent
er
language.
ii) Runtime Class libraries – These are most basic
 The internal structure of JVM can be collection of built-in classes.
represented as:
- These classes are useful to execute java program &
all java library classes are available in built-in
packages.
e.g. String class in java.lang package.
iii) User Interface Toolkits – Toolkit is collection of
built-in libraries using which java based GUI
(Graphical User Interfaces) can be developed.
- Very commonly used java toolkits for building
GUI’s are AWT & Swing.
iv) Deployment Technologies – once a java based
software or application is developed it can be
installed / deployed on any machine using:
a) Java plug-in – it helps java applet to be
exeucted in browser.
b) Java web start – it helps java program
executed remotely.
 Installing & configuring java
- Installation steps to be noted in practical while
performing java installation.
- From above it is clear that, OS is working between
Real machine and JVM.
- User creates and submit user program to compiler
and interpreter uses API (Application Programming
Interface) which is collection of java library used to
compile any program.
Unit – 2 Overview of Java Language - During such compilation, each high-level language
instruction get converted into smaller pieces.
- Each smallest unit or piece of instruction is called
token.
- in java prog code following 5 types of tokens can be
considered:
1. Keyword 2. Identifier
3. Literal 4. Operator
5. Separator
1. Reserved Keywords – Keyword is one of the most
fundamental entity of programming language.
- It is predefined word with predefined meaning.
 Type of comment
- it is always used in small case and it can not be used
- It is necessary to make the program readable and as an identifier.
easy to understand.
- java supports almost all the keywords of C, C++ and
- for this, programming language allows to use some new keywords, thus java having 50 keywords
comment. like int, float, switch, super, throw, this, etc.
- Comment is read-only statement in program code 2. Identifiers – It is one token created by programmer
which neither compiled or executed. in prog code.
- Compiler will directly ignore such comment line - it is a valid name given to class, variable, function,
even if it is containg error. interface, object, package, etc.
- comment in prog code is used to give short - while creating an identifier , some rules must be
defination about program code or purpose of program followed:
for easy understanding.
i. It must start either with alphabet or underscore as:
- comment in java program can be given in one of the
following way: int RollNo, int _rollno;

1. Single line comment – any line in program code ii. It must not contain blank space, reserve character
starting with // can be considered as single line like -, period (.)
comment. iii. It must not be a reserve keyword
2. Multi-line comment – in case if set of lines to be iv. It may contain digits, Underscore as
declared as comment, it is to be enclosed in /*….*/.
int Num1, int roll_no.
e.g.
- Variable name can be of any length but it is
 Java Tokens recommended it should be meaningful.
- Every high-level language code first must be 3. Literals – This is one type of token created by java
compiled before execution. compiler from java prog code.
- For this compiler is used which compiles the high- - Literal is sequence of characters (digits, letters, or
level language code. other character) that represent constant values.
- A java prog code also gets compiled into - Such constant value can be stored in java program
intermediate code or byte code stored in .class file. variable.
- Literal not only represents value but also represents: V. Increment & Decrement operator
 How any such value is stored? VI. Special operator

 How such value to be processed?


- The different types of literals supported are: 5. Separators – It is also one type of token created
by java compiler.
i. Integer Literal – it is numeric value also complete
value without decimal point such as: - This token is used to divide the code and group it
properly.
rollno=21, Marks=436, etc
- following are the different java separators:
ii. Floating point Literals - it is numeric value with
decimal point and also called as fractional or real Name Description
value such as:
Parentheses ( ) It is used while defining the
temp=32.4, tax=3.5, height=5.4, perMarks=67.21. function and calling to specify
parameters.
iii. Character literals – it is value made of alphabets
or other characters with single char .e.g e.g. f1( [parm])
grade=’A’, etc Braces { } It is used to define code block and
to give set of array values.
iv. String literals – It is value made of group of
characters e.g. e.g.
StudentName=”John”; void f1() {…}
v. Boolean literals – this type of literal represents n[3]={2.4.5}
only “true” or “false” value.
Brackets [ ] Used to specify array size
4. Operators – This is one type of token created by
int n[3]
java compiler from java prog code.
Used as sentence terminator i.e.
- Operator is one special symbol that performs a Semicolon ; generally at the end of each line.
predefined operation.
To separate values , variable
- Operator uses value or variable to complete its
operation which is called Operand.
Comma , declarations

- Operators basically classified as: int a, b, c;

A) Unary Operator – Operator using single operand int n[3]={10 , 30 , 40};


such as i++, ++i, etc Used to show package and sub
B) Binary Operator - Operator using two operands
such as a+b, a*b; etc
C) Ternary Operator - Operator using three operands
Period . package name, object & member
java.awt.event
ob.display()
such as ?:
- As per the operations that an operator performs, they
are further classified as:  Variable

I. Arithmetic operator - A java program may uses different programming


II. Relational Operator elements & can perform different operations.
III. Logical Operator
IV. Assignment operator
- Collecting and storing the required data element to 2. Dynamic Initialization – if the value of
complete the execution is also one of the imp task of variable assigned at runtime it is called
java program. dynamic initialization.
- To collect and store the required data element java  For this, java language supports use of input
program uses Variable. statements.
- Variable is labeled temp memory location to store  In java language “Scanner” lib class can be
required data element. used to get different inputs like nextInt( ),
nextFloat( ), nextDouble( ), nextChar( ), etc
- A programming entity whose value can be changed
is called Variable. e.g.
class VarDemo
- A variable must be declared before its first use
{
anywhere in java program as:
public static void main( )
<DataType> <VarName>; {
int n=100; // static initialization.
e.g. int n; int m;
- at a time multiple variable of same data type can Scanner sc=new Scanner(System.in);
also be declared as: System.out.println(“Enter a int value:”);
m=sc.nextInt( ) ; //Dy initialization
int a, b, c; System.out.println( “ static value n=”+n);
- Variable Name is a valid name or “Identifier” as per System.out.println( “ Dynamic value n=”+m);
the following rules: }
}
o It must starts with alphabet (small /
capital) or underscore ( _ ) e..g int Rno;
char _sName;  Constant

o It must not contain blank space or any  Data types


reserve character like ( int roll-no, rollno. [  Type Casting
invalid] )
 Control statement
o It may contain underscore or digit like
Num1, roll_no;  Branching

- Variable declaration is compulsory as it informs  Looping


about following to compiler:  Jumping
o Name and datatype of variable.  Break
o Memory size of variable
o Scope of variable  Continue
 Once a variable is declared it can be initialized
in of the following ways:
1. Static Initialization – if the value to
variable is assigned such that it is fixed
and does not get change is called static
initialization as:
<DataType> <VarName>= Value;
e.g. int n=100;
or
int n;
n=100;
e.g.
class A
{
int x; // Data member
void f1() // function member
{}
}
 In single class, single or multiple data
members or same or different types can be
enclosed.
 In single class multiple data members can also
be enclosed.
 For execution of java program along with
other classes, there must be at least one main
class.
 Introduction – OO programming uses many  The class in which main method is defined is
fundamental entities like class, methods, data called Main Class.
members, objects, etc.
e.g.
 For this, all these members to be properly class A
created before use. {
int x, y;
 Defining Class – Class is one of the most
void display( )
fundamental entity of OO programming. {
 Class is one User Defined Data type which is x=10; y=20;
created for by programmer for a specific user System.out.println(“Addition=”+(x+y)
);
application.
}
 Class as user defined data type can enclose }
two types members: class MainCls
{
o Data members public static void main(String ar[])
{
o Function member
A ob=new A();
 A java program can be designed with single or ob.display();
multiple classes. }
}
 A class in java program can be created using  Fields Declaration – As class is User
“class” keyword as: Defined Data type, it can enclose data as well
as function member.
class <ClassName> [extends BaseClassName]
 Data membert in class represents, data fields
{ which are also called as variable.
[data members];  Data field in class used to store required data
[ function members]; elements.
 The variables enclosed in class but outside of
}
any method is called “Instance Variable”.
 As oppose to , class defined in C++ program,
 Variable or data field in class can be added as:
a class defination of java program never ends
with simicolon ( ; ). <dataType> VarName;
 Var Name must be an identifier i.e. a name void f3(int n, int m) {} // function with
given with all rules like: multiple parameters of same type
o It must starts with alphabet or void f4(int n, double d) {} // function with
Undersocre ( roll_num). multiple parameters of different types.
o It must not contain blank space, e.g.
reserve character.
class A
o It may enclose digit ( num1) {
int x, y;
e.g. void display( )
 Method Declaration- As class is User {
Defined Data type, it can enclose data as well x=10; y=20;
as function member. System.out.println(“Addition=”+(x+y));
}
 As data field represents data elements required void show()
for class, simillarly it also needs function {
member. x=10; y=20;
 Function member represents the operation System.out.println(“Subt=”+(x-y));
code used by class to operate & manipulate }
data member. }
class MainCls
 In sinle class either single or multiple methods {
can be defined. public static void main(String ar[])
{
 Melthod in class can be added as:
A ob=new A();
<ReturnType> FuncName( [ parm ] ) ob.display();
ob.show();
{ }
--- Function
}
Body
---  Creating Object – As like class, Object is
} also one of the most fundamental entity of
Object Oriented Programming.
 Return type – it shows whether function
returns value or not. If function returning  Object is said to be one Runtime Entity of
value which type of value it is returning. OOP or instance of class.
 Function Name – it is valid name or identifier  Object is one allocated memory block which
given as per the rules. reserves space for data mamber and function
 Function Body – it contains actual member. Object
operational code or set of instruction that
function performs. Data Member

 A function can be created with or with-out Function


parameter. Member

 If function is created with parameter, it may


with sinlge or multiple parameters of same or
different types:  Obect on any class in java program can be
created using Declaration and Initialization
void f1( ) {} // function without param as:
void f2(int n) {} // function with single parm
ClassName ObjName=new ClassName( ) ;
MathCls obj=new MathCls( );
 Alternatively it is also possible that,  This method name and it’s signature is
declaration and initialization can be separated necessary to call the function.
as:
 If a software contains too many functions with
 ClassName ObjName; // Only declaration different names and different signature it may
causes following problems:
ObjName=new ClassName( ) ; // initialization
e.g. o Remembering name of each method
MathCls obj and its signature at the time of calling.
obj=new MathCls( );
 Object is necessary to call / access the o If calling statement mismatched, will
members of class with help of Member cause error.
Accessing Operator ( .) as:  To solve these problems, OOP supports the
ObjName.MemberName; concept of Method Overloading.
e.g.  Method Overloading is a OOPs technique by
Obj.display( );
which mutliple methods are defined by same
 On single class single or multiple objects can name but different signature.
be created as:
MathCls obj1=new MathCls( );  The difference in signature may be:
MathCls obj2=new MathCls( ); o Parameter
MathCls obj3=new MathCls( ); o Number of parameters
 When multiple objects created, each object o Types of parameters
gets separate / individual copy of class
o Sequence of parameters
members.
 When a method is redifned by different
Complete E.g.
signature is called Method Overloading.
class A
{  Such redefined method is called “Overloaded
int x, y; Method”.
void display( )
{  For successful method overloading following
x=10; y=20; rules are important:
System.out.println(“Addition=”+(x+y));
} o Multiple functions in same class must
be defined by same name.
} o With different signature
class MainCls
{ o Return data type of function may be
public static void main(String ar[]) same or different, is not important.
{
A ob=new A();  Method overloading can be represented as:
ob.display(); void f1 ( ) {} // Defination 1
}
} void f1( int ) {} // Def. 2
void f1( double ) { } // Def. 3
 Method Overloading
void f1 (int , double ) {} Def 4
 A class may contain single method or multiple
methods. void f1 ( double, int ) {} Def 5
 To define a method, proper name and  Thus above five defination of f1 ( ) method
signature is specified. shows difference in signature in terms of
Parameter, type of parameter, number of Constructor is implicity created and called, in case
parameter and sequence of parameter. if constructor to be defined, following rules are
important:
e.g.
i. No return type to be given as
class A
constructor never returns value.
{
int x, y; ii. Function name and class name must be
void display( ) same
{
System.out.println(“ Overloaded Function”); iii. Construtor can be with or without
} parameter.
void display( int x)
{ iv. Constructor get called implicitly /
System.out.println(“Square=”+(x*x)); automatically when the object on class
} is created.
void display( int x, int y)
Construcor can be created as:
{
System.out.println(“Addition=”+(x+x)); class ClassName
} {
void display( String s) ClassName( ) // Construtor Defination
{ {
System.out.println(“Length=”+s.length( )); }
} }
}  Constructor can be defined with or without
class MainCls parameter.
{  Constructor without parameter is called
public static void main(String ar[]) “Default Constructor”.
{
A ob=new A();
e.g.
ob.display( );
ob.display(10); class A
ob.display(5,10);
ob.display(“ABC”); {
}
int n;
}
 In Method Overloading, the calling staement, A()
and the function defination is linked at run
time hence it is called Late Bining or {
Dynamic Binding. n=100;
 Constructor System.out.println(“Constructor Initialized”);
A class in java program can enclose data as well }
as function members.
void display( )
On class when object is created, some memory to
be allocated for its data and fucntion members. {

Every class used to have a special member S.o.p(“Square=”+( n*n ));


function called as construtor. }
Constructor is special member function of class }
which completes the job of Allocation &
Initialization. class MainCls
{
public static void main(String ar[ ])  Such constructor defined with different
signature is called “Overloaded
{
Constructor”.
A ob=new A( ); // call the constructor
 A constructor defined without parameter is
ob.display( ); called Default Constructor.

}  Any constructor get called implcitly when


object on that is created.
}
 If constructor is defined with parameter, then
 Constructor Overloading while creating object or calling constructor
 OOPS supports many features and one such parameter must be passed.
important feature is Method Overloading. e.g.
 It means, multiple methods defined by same class A
name but differfent signature. {
 As constructor is also one function / method A()
of class, hence it can be also overloaded. {
System.out.println(“It is default Constructor”);
 Construtor Overloading which means }
Constructor redefined in class with different A(int n)
signature. {
S.o.p(“Square=”+(n*n));
 Difference of signature involves: }
A(int a, int b)
o Parameter
{
o Number of parameter S.o.p(“Addition=”+(a+b));
}
o Type of parameters
}
o Sequence of parameters
class MainCls
 When in same class mutliple constructors are {
defined by same name with different signature public static void main(String ar[ ])
is called Construtor Overloading as: {
A ob1=new A( ); // call the default constructor
class ClassName A ob2=new A(20 ); // call the constructor with one int
parameter
{
ContstName ( ) {} A ob3=new A(20,100 ); // call the constructor with
two int parameters.
ConstName ( int ) {}
}
ConstName(int , int ) {} }
ConstName(double, String) {}
ConstName(String , double ) {}  Inheritance & Types – OOP offers many
features and many benefits, such as
} encapsulation, data hiding, method
 In all above definations, ConstNames are overloading, overrridng, etc.
same only difference of signature is - One such important feature is Inheritance.
maintained.
- In real-time software development, one common - When in inheritance process, if only one base class
factor is , if a software to be created it undergoes in and one derived class is used, it is called Single
many stages. Inheritance.
- Like Requirment analysis, designing, coding, testing - Single Inheritance can be represented as:
and then deployment.
A Base class
- all these stages takes too much time. In case, if
already a software is devloped with some same
features, generally the process is repeated which B Derived class
again takes too much time.
- single inheritance can be applied as:
- to overcome these problems, Inheritance technique
of OOPs can be used. Class ClassName extends BaseClasssName

- Inhertiance is a process by which from existing class {


new class can be created. }
- The existing class is called “Base Class or Super e.g.
Class or Parent Class”.
class A // Base class
- The newly created class is called “Derived Class or {
Sub class or Child Class”. int n;
void getInput( )
- due to inheritance, following effects can be {
observed: Scanner sc=new Scanner(System.in);
- copy of each data meber is given from base S.o.p(“Enter a num”);
n=sc.nextInt();
class to derived class.
}
- Derived class gets Permission to call base }
class function without object of Class Name. class B extends A // Creating derived class
{
- Using inheritance, when class or code is created, it void display( )
gives advantage of Reusability. {
getInput( );
- that means if the code is required again, no need to S.o.p(“Square Root=”+Math.sqrt(n));
recode and test it, the existing class can be inherited }
to create new class. }
class MainCls
- to implement inheritance in java language, a special
{
keyword is used i.e. “extends” as
public static void main(String ar[] )
class ClassName extends BaseClassName {
B obj=new B( );
{ obj.display( );
}
}
}
- in java language, following inheritnace types can be 2. Multi-Level Inheritance – In this type of
implmented. inheritance, chain of base and derived classes gets
created.
1. Single Inheritance 2. Multi-level Inheritance - When in Inheritance process, a derived class is
3. Hierarchial 4. Hybrid Inheritance further extended to create its child/dervied class it is
called Multi-level inheritance.
1. Single Inheritance – In this type of Inheritance, - thus, in this type, a derived also becomes base class
only one base class and only derived class is for its derived class.
involved. - It can be shown as:
}
A Base class }
3. Hierarchical Inheritance
- In this type of inheritance, multiple bases classes are
B Derived class extended / derived from single parent class.
- Due to this, each derived class will get separate copy
of base class members.
C Derived class -
of B A

- In this, “C” becomes grand child and “A” becomes
Grand parent class. B C D
- C as grand child class inherists properties directly
from its immediate parent class “B” and indirectly
- Hierarchial Inheritance is mainly used to provide
from “A”.
common reusable features.
e.g.
- Such feature is created once in base class, and all the
class A // Base class derived classes can use it.
{
int n; e.g. A { int n,
void getInput( ) getInput(){… } }
{
Scanner sc=new Scanner(System.in);
S.o.p(“Enter a num”);
B Call getInput() D
n=sc.nextInt();
Call getInput() Show sq.root Call getInput()
}
Show square Show cube
}
class B extends A // Creating derived class  Thus in above e.g., declaring one variable and
{ getting input in it, becomes common feature.
void display( )
{  It is created once in base class “A” and getting
getInput( ); reused in all derived classes.
S.o.p(“Square Root=”+Math.sqrt(n)); e.g.
}
} class A // Base class
class C extends B // Creating derived class {
{ int n;
void show( ) void getInput( )
{ {
getInput( ); Scanner sc=new Scanner(System.in);
S.o.p(“Cube=”+(x*x*x)); S.o.p(“Enter a num”);
} n=sc.nextInt();
} }
}
class MainCls class B extends A // Creating derived class
{ {
public static void main(String ar[] ) void showSquare( )
{ {
B obj1=new B( ); getInput( );
obj1.display( ); S.o.p(“Square =”+ (n*n));
C obj2=new C( ); }
obj2. show( ); }
class C extends A // Creating derived class  Thus it is clear that, above e.g. using Hybrid
{ inheritance.
void showRoot( )
{ e.g
getInput( ); class A
S.o.p(“Sq Root=”+Math.sqrt(x));
{
}
int n;
}
class D extends A // Creating derived class }
{ class B extends A
void showCube( ) {
{ void getInput( )
getInput( ); {
S.o.p(“Cube=”+(x*x*x)); Scanner sc=new Scanner(System.in);
} S.o.p(“Enter a num”);
} n=sc.nextInt();
class MainCls }
{ }
public static void main(String ar[] )
{ class C extends B
B obj1=new B( ); {
obj1. showSquare ( ); void showOddEven( )
C obj2=new C( ); {
obj2. showRoot ( ); getInput( );
D obj3=new D( ); if( n % 2==0)
obj2. showCube ( ); System.out.print(“Even Number”);
} else
} System.out.print(“Even Number”);
}
4. Hybrid Inheritance }
- When the other inheritance types are combinedly class D extends B
used in single java program, it is said to be using {
Hybrid Inheritance. void showPosNeg( )
{
- Hybrid Inheritance is applied by combining other getInput( );
inheritance types such as Single, Multi level and if( n >0)
Hierarchical. System.out.print(“Positive Number”);
else
- Due to this, in single java program advantages of System.out.print(“Negative Number”);
other inheritance types can be utilized. }
A }
class MainCls
{
B public static void main(String ar[])
{
C ob1=new C( );
C D ob1.showOddEven( );
- In above e.g., following different inheritances are ob2.showPosNeg( );
combined like }
}
Single Inheritance : AB  Method Overriding
Multilevel Inheritance : A B  C BC , BD
Hierarchical Inheritance : hierarchial inheritance
- OOPs provides many advantages and features such void display ( ) // Overridden method
as encapsulation, overloading (method and {
constructor), data hiding, inheritance, etc S.o.p(“I am Base Class”);
}
- One such imporant feature of OOP with inheritance
}
is method overriding.
class B entends A // Derived Class
- When, Inheritance is applied, it is possible that, {
from existing class (Base class) , new class (Derived void display ( )
class) can be created. {
display ( ); // chances of recursion.
- Due to this, the derived class inherits properties of S.o.p(“I am Derived Class”);
base class. }
- Along with inheritance, it is also possible to apply }
method overriding. - Thus when display ( ) method in above e.g. called
from drived class, it will not call base class method,
- Method Overriding is OOPs technique by which, but recursively calls itself.
bases class method can be redefined in derived To solve this problem, java language supports “super”
class. keyword.
- For Method overriding, following is must: - When a method, called with “super” keyword, then
 There must be atleast one base and one it is compulsory for JVM to call base class method as:
derived class. super.MethodName( );
 Base class method must be redefined in super.dispaly( );
derived class by same name.
e.g
class A // Base Class
A Base class {
void f1( ) void display ( ) // Overridden method
{
B S.o.p(“I am Base Class”);
Derived class }
void f1()
}
class B entends A // Derived Class
 The base class method which is redefined in {
derived class is called Overridden Method. void display ( )
{
 But when such base class overridden method, super.display ( ); // calls base class method.
if called from dervied class method, there may S.o.p(“I am Derived Class”);
chances of recursion. }
}
 As the base class and derived class method
class MainCls
name is same, the calling statement may
{
causes recursion
public static void main( String args[ ])
 The derived class method may calls itself {
infintely. B ob=new B( );
ob.display( );
e.g.
}
class A // Base Class }
{ Output –
I am Base Class. - When a variable or data member is declared
I am Derived Class with “static” keyword, it becomes static data
member as:
 Static Members - static <DataType> VariableName;
- As java is OOP language, it uses class as its - static int x;
fundamental entity. - it is also possible that, while declaring static
- For every executable java program, there must be member, value can also be assigned as:
at least one class defined with main ( ). - static <DataType> VariableName=value;
- Class as a user defined data type can enclose data - static int x=100;
& function members. - when a data member becomes static, it shows
- By default the members of class, data or function following important factors:
declared without static keyword and they are non- - only one copy of data member is created for
static. all objects.
- Static members in java class can be of following - Same copy of data member is reused by all
types: members as:
- 1. Static Data Member 2. Static Function -
Member. ob1 ob2 ob3
- 1. Static Data Member – the variables enclosed
with-in class are called data members which
represents data elements or data field of class. x
- As per general OO programming rule, on a class
either single or multiple objects can be created. - Advantages :-
- For every created object, JVM gives separate i. Resuse of memory of data member.
copy of data member. ii. No wastage of data member copy.
- In such case, there may be chances of memory - DisAdvantages –
wastage if particular object is not created like: i. Value created by one object will be replaced
class A by other object.
{ ii.Value is not safe.
int x; Imp Rule – A static data member can only be
--- accessed by static function member.
--- 2. Static Data Member
--- - A java class, as like data member can also enclose
} function member.
- On above class “A” if following objects are - generally function in class is added without “static”
created: keyword hence it is non-static functions.
- A ob1=new A( ); - if a function is non-static, then such function can be
- A ob2=new A( ); called outside using its object.
- A ob3=new A( ); class A
- Thus each object gets separate copy of “x” data {
member as void f1()
{--- ---- --- }
ob1 ob2 ob3 }
x x x
- thus, to call f1( ) method of class “A”, object of
- Thus in above case, once the execution of ob1 class to be created & then it can be accessed as:
is over, its memory is purely get wasted. A ob=new A( ); // declaring object
- To avoid this, java langauge supports concept ob.f1( );// calling function
of static members. - but in many cases, it is not possible to create object
on class, but still its function member to be called.
- in such case, such function member to be declared - Also as java is pure OO programming language,
as static. uses “class” uses its one of the basic entity to execute
- A static function member is function in class defined program.
using “static” keyword as: - generally these elements, variable, class & method
static <ReturnType> FuncName( [ arg ] ) are non-final but in some cases, these programming
{ entities to be declared final.
--- Final Variable
--- - Variable is one programming entity, which is used
} to store data elements.
static void display( ) - But one variable at a time can store only one data
{ value, if some other value is assigned, its previuos
--- value get replaced.
--- - In may cases it is necessary to maintain the value
} of variable.
- if the function member is static, it does not require - In many cases, change in value of variable should
to object to call, but can be called directly with the not be allowed.
help of ClassName as: - For this reason, such variable should be declared
ClassName.FuncName([arg]); as final variable.
A.display( ); - When a variable in java prorgram is declared with
- Imp Rule – A static function member can only “final” keyword it becomes final variable.
access only staticdata member. - Such variable shows following important
e.g. characteristcs:
class A o Value of such variable can not get
{ changed.
static int x; o Value of such variable can be used and
static void display( ) reused many times.
{ o Such variable becomes “Symbolic
x=10; // accessing static data member Constant” in java program.
S.o.p(“Cube=”+(x*x*x));
- In real life, there are many such constants
}
which are used such as PI=3.14.
}
class MainCls - Following are the important rules to create
{ and use final variable / symbolic constant :
public static void main(String ar[] ) 1. At the time of declaration itself, value must be
{ assigned, as later on its value can not be
A.display(); // calling static function member. changed.
} 2. It must be declared with class but outside
} method i.e. class variable.
- It is recommended that, variable name to be in
- There are many built-in classes having static
capital letters for easy understanding.
functions which can be called directly by class name
such as:
- A final variable in java program can be
Math.sqrt(int); Integer.parseInt( ) created as:
final <DataType> VarName=Value;
Double.parseDouble( )
final double PI=3.14;
final int MaxMarks=100;
 Final Class, Variable, Method - If in program, we try to change the value of
- As java is programming language, it uses all basic final variable, it will show compiler error such
programming elements like variable, methods, etc. as ” can not assign value to final variable”.
e.g.
class A
{ obj.display();
final double PI=3.14; }
void display( int r) }
{
System.out.println(“Area of Final method
Circle=”+(PI*r*r)); - class is one the most basic entity of OOP and for
} every executable java program there must be atleast
} one class.
class MainCls - class as user defined datatype combines data and
{ function members.
public static void main(String ar[]) - OOP supports many features and one such is
{ Inheritance by which a class can be sub classed or
A obj=new A( ); extended to create sub class.
obj.display(5); - When inheritance is applied, there can be another
} realted feature i.e. Method Overriding.
} - It means, a base class method, is redefined in
Final class derived class and such method becomed overridden
- class is one the most basic entity of OOP and for method.
every executable java program there must be atleast - but in some cases, this method overriding should not
one class. be allowed and for this , it is created as final method.
- class as user defined datatype combines data and - A final method is method in class which is creted
function members. with “final” keyword as:
- OOP supports many features and one such is final <RetType> FuncName( [arg])
Inheritance by which a class can be sub classed or {
extended to create sub class. ---
- in many cases, it is necessary to restrict a class to be ---
inherited , for this it is created as final class. }
- when a class in java program is declared with - When such method is attempted to be
“final” keyword it becomes final class as: redefined / override in derived class, compiler
final class <ClassName> shows error “Can Not Override”.
{
} class A
- when a class is declared as “final” , it can be used in {
inheritance process or it’s derived/child class can not final void display()
be created. {
- if a java program attempts to inherit such final class, System.out.println(“I am final class”);
java compiler will show compiler error that “can }
not inherit from final class”. }
final class A class MainCls
{ {
void display() public static void main(String ar[])
{ {
System.out.println(“I am final class”); A obj=new A( );
} obj.display();
} }
class MainCls }
{
public static void main(String ar[])  Finalizer method
{ - As Java is OOP language, uses class, object ,
A obj=new A( ); constructor , etc.
- the constuctor is used for initialization simillarly, }
java also uses the concept of finalization. }
- java as oppose to C++, does not uses the destructor }
but uses following : Output
Garbage Collection
finalize( )
- Garbage collection – it is one automated process of
JVM which is used to find the allocated but unused
memory and make it free.
- Garbage collection is automatically called in
following two cases:
- When the system is in idle conditon.
- When a program is facing shortage of
memory problem.  Abstract Method & Abstract Class
- but in some cases, java program also uses, non- Abstract Class
object resource memory such as File Desciptors, - A class which contains the abstract keyword in its
window system fonts, etc declaration is known as abstract class.
- The garbage collection can only free object resource - Abstract classes may or may not contain abstract
memory but can not frees non-object resource methods, i.e., methods without body ( public void
memory. get(); )
- hence there will be chances of more memory - But, if a class has at least one abstract method, then
wastage, to avoid this problem, java langauge the class must be declared abstract.
supports finalizer method. - If a class is declared abstract, it cannot be
- the finalizer method is used by defining finalize( ) instantiated.
method. - To use an abstract class, you have to inherit it from
- this method will get called to release object based another class, provide implementations to the abstract
memory as well as non-object resource memory. methods in it.
- there are many library classes which are defined - If you inherit an abstract class, you have to provide
with finalize( ) method such as GrogorianCalendar. implementations to all the abstract methods in it.
- while using this class, finalize( ) method can be Syntax:-
used. abstract class ClassName
e.g. {
import java.util.*; }
public class FinDemo extends GregorianCalendar { Abstract Methods
- If you want a class to contain a particular method
public static void main(String[] args) { but you want the actual implementation of that
try { method to be determined by child classes, you can
// create a new FinDemo object declare the method in the parent class as an abstract.
FinDemo ob = new FinDemo(); - “abstract” keyword is used to declare the method as
abstract.
// print current time - You have to place the abstract keyword before the
System.out.println("" + ob.getTime()); method name in the method declaration as
abstract <ReturnType> FuncName([arg]);
// finalize cal - An abstract method should only be declared, but not
System.out.println("Finalizing Started"); without method body.
ob.finalize(); - Instead of curly braces, an abstract method will have
System.out.println("Finalized."); a semoi colon (;) at the end.
abstract class A
} catch (Throwable ex) { {
ex.printStackTrace(); abstract void display(); // declaring abst method
}
class AbDemo extends A
{
void display() // Defining abst method
{
System.out.println("I am from Abstract Class");
}
public static void main(String ar[])
{
AbDemo ob=new AbDemo();
ob.display();
}  Defining & Implementing Interface –
} - Java as programming language derived from it
 this keyword predecessor languages C & C++.
- java as programming lanugage supports different - Due to this, it shows many similarites and also
tokens and one such token is keyword. many differences.
- there are many keywords supported java language, - One important difference is in terms of
and one such important keyword is “this”. inheritance i.e. java doesn’t support Multiple
- “this” as a keyword is useful in many cases such as: inheritance.
this can be used to get the current object. - This limitation can be solved using the concept of
this can be used to invoke current object's method. interface.
this() can be used to invoke current class constructor - Interface in java program is like a class which can
- in other words, it can be said that, “this” keyword include data member and function member.
can be used to show: - Interface in java program can be of following
- current class types:
- current method scope, etc o Built-in interface – these are pre-defined
- e.g. interfaces avaialable in every jdk version
class A such as:
{ ActionListener, MouseListener, Runnable,
int rno;String sname; etc
A(int rno, String sname) o User Defined Interface – it is an interface
{ created by programmer for any user
this.rno=rno; // assign rno value to rno of class. application.
this.sname=sname; // assign sname value to sname of class. - Interface can be created using “interface” keword
} as:
void display() interface <InterfaceName>
{ {
System.out.println(“Roll [data member]
No=”+rno+”Name=”+sname); [function member]
} }
} E.g.
class MainCls interface Inft1
{ {
public static void main(String ar[]) public int n=100;
{ public void display();
A ob=new A(101,”Abc”); }
ob.display(); - Interface can enclose single or multiple data and
} function members.
} - But as oppose to class, interface shows following
important featuees or differences.
i. data member in interface always by default is }
final. }
ii. Function member or method in interface must - Some important factors regarding interface are:
be abstract i.e only declared & not defined. - As like class, interface can also be extended
iii. As like class interface to be saved with “.java” using “extends” keyword.
extension, & can be compiled. But interface interface A
never get executed. {
- Interface can be created and saved either in same ---
java program file or can be separately in same }
location. interface B extends A
- Implementing interface {
- Once an interface is ready, it can be used by any ---
other java class. }
- Using an existing interface is called implementing - In case of interface, multiple inheritance is
interface & for this, it uses special keyword i.e. allowed as:
“implements” as: interface A
class <ClassName> implements <IntfName> {
{ ---
--- }
--- interface B
--- {
} ---
- The practical meaning of implmenting interface }
says: interface C extends A,B
o The class which is implementing interface can {
use data member of interface but can not ---
chance its value. }
o The class which is implementing interface - Class can implment interface and use it, but vice-
must define the abstract method of interface. versa i.e. interface can use class not allowed.
e.g. - Each and every method of interface must be
interface Ift1 defined in class which is implementing interface.
{ - If interface containing multiple methods and any
public double PI=3.14; of the method from interface not required, then
public void display(int r); atleast, its empty defination to be given as:
} interface Itf1
 Save it as: Ift1.java {
 Compile it as : C:\> javac Ift1.java public void f1();
class A implements Ift1 // interface implemented by A class public void f2();
{ }
public void display(int r) Class A implements Ift1
{ {
System.out.println(“Area of Circle=”+(PI*r*r)); public void f1()
} {
} --- method Defination
class IftDemo ----
{ }
public static void main(String args[]) public void f1(){} //empty defination
{ }
A ob=new A(); Inner Class
ob.display(5);
- class is one the most basic entity of OOP and for }
every executable java program there must be atleast }
one class. class mcls
- class as user defined datatype combines data and {
function members. public static void main(String ar[])
- as like control statements if, for, java language also {
allows to use class in nested form. A outObj=new A();
- when one class defined within other class it is called outObj.display();
nested class. A.B inObj=outObj.new B();
- the class, in which other class is defined becomes inObj.show();
outer class. }
The class defined with-in outer class becomes inner }
class.
- Nested class can be given as: Package
class A // outer class Creating & Accessing Package
{ - Java as programming language derived from it
--- predecessor languages C & C++.
--- - Due to this, it shows many similarites and also
class B // inner class many differences.
{ - One important difference is in terms of header
--- files.
--- - C or C++ program requires inclusion of header
} files, but in case of java language, header files are
} replaced by package.
- the relation between, outer & inner class shows - Package is a container which contains group of
important characteristics such as:  all related classes, interfaces or both for a
i. Inner class can access each and every member [data single software.
as well as function] of outer class. - In simple words, a package can be folder or
ii. But outer class doesn’t have any permission to directory in which all classes & interfaces
access any member of inner class. required for a complete java application are
- Rules to access outer and inner class members: stored.
i. outer class member can be directly access using its - Packages gives many advantages:
object. o Reusability – class created once & if
ii. to access inner class member, object of inner class stored in package, can be resued.
to be created with preceded by outer class as: o Unique Name – in once package class
- OuterClassName.InnerClassName name will unique, but by same name
<ob>=<outClassObj>. New OuterClassName( ) class can be created in other package.
e.g. o Class hiding – if class enclosed in
class A //outer class package can be hidden for its internal
{ details, but can be accessed from
void display() // outer class method anywhere.
{ o Less coding – due to reusability, length
System.out.print("I am Outer Class"); of code will be less.
} - In java language, packages will be of
class B //inner class following types:
{ - 1. System Package / Built-in package – it is
void show() // inter class method also called API package which are already
{ created and distributed with different JDK
System.out.print("I am Inner Class"); versions.
}
- There are many built-in packages supported 2. using import statement – package class can be
java language such as: accessed using import statement.
- <diagram> - This statement can be used in following ways:
2. User Defined Package - a. importing all classes – if from a package all or
- This is the package created by programmer for a many classes to be accessed, following statement can
specific user application or sotfware. be useful:
- these are not previously available in any JDK import packageName.*;
library. import MyPack.*;
Creating Package b. importing single class – if from a package single
- a user defined package can be created in following class to be accessed, following statement can be
steps: useful:
Step 1 : Create one folder in current working folder import PackageName.ClassName;
to be used as package. E.g. import MyPack.StudInfo;
C:\MyJava e.g.
C:\MyJava
MyPack
MyPack
Number.java MainCls.java
Number.clas MainCls.class
- in above e.g., MyJava is current working folder, s
under which, MyPack folder is created as Package package MyPack;
folder. public class Number
Step 2 : adding class to package {
- once package is created, in this classes can be public void display( int n)
added. {
- For this, while defining class, “package” keyword if (n%2==0)
must be used to inform about package name as: System.out.println(“Even Number”);
package <PackageName>; else
package MyPack; System.out.println(“Odd Number”);
class <ClassName>
{ }
--- }
---  Save above program in
} MyPack folder as Number.java
- a package may contain single class or any number of  Also compile in same folder.
classes. import MyPack.Number;
Step 3 : accessing package class class MainCls
- once package & its class is ready, than it can be used {
by any other java program which is saved in its parnet public static void main(String ar[])
folder. {
- thus, if a java class stored in package folder, it can Number obj=new Number( );
be accessed by other java program which stored in obj.display(10);
parent folder of package. }
- for this, package class can be accessed in one of the }
following way:  Save above program in MyJava
1. Using Fully Qualified Name (FQN) – the packag folder as MainCls.java
class name written with complete package name as:  Also compile in same folder.
PackageName.className;  Execute in same folder
MyPack.Numbers;
 Types of Error
- a java program undergoes in different stages such as 3. Runtime Error – when error occurred during
designing, coding, compiling and then execution execution phase of program is called runtime error.
phase. - Such runtime error also called as Exception &
- during these different stages, there are chances of runtime error are said to be most difficult types of
different types of error may get generated. error to debug.
- an Error is any invalid situation or statement in - When runtime error occurs it causes following:
program which occurs when program breaks the rule o It abnormally terminates the program
of programming language environment. o Important house-keeping programming
- as program undergoes into different stages, operatons like closing of DB, file, etc can be
following different types of error can be generated: skipped.
1. Compile time error 2. Logical Error - there are many programming situations where there
3. Runtime Error are chances to generate runtime error such as:
1. Compile Time Error – When an error occurs o Division by zero
during compilation phase of java program it is called o Reading from non existing file
compile time error. o Accessing array element with out of index
- If a program having compile error , such program range, etc
will not be compiled successfully and also does not - Such runtime error or Exception is must be handled
get executed. due to following reasons:
- this error is detected by compiler of respective o Avoid abnormal termination of program.
language. o To make std software.
Such as: - to handle runtime error, java language supports
o Undefined symbol special keywords as exception handler like try, catch,
o Unclosed string, etc throws, etc.
- Such type of errors are easy to debug due to
following reasons:  Handling exception
o It is detected by compiler itself. when error occurred during execution phase of
o It shows line number of error program is called runtime error.
o Some advance compilers also shows - Such runtime error also called as Exception &
reason & solution of error like runtime error are said to be most difficult types of
NetBeans, Eclipse, etc error to debug.
3. Logical Error – the error which is generated - When runtime error occurs it causes following:
due to wrong or poor logic of program is o It abnormally terminates the program
called logical error. o Important house-keeping programming
- It occurred during execution phase of program operatons like closing of DB, file, etc can be
but not giving correct output or expected output, skipped.
suc - there are many programming situations where there
h type of error is called logical error. are chances to generate runtime error such as:
e.g. use “<” instead or where “>” is required, o Division by zero
loop without termination, initializing fact value to o Reading from non existing file
zero (fact=0) in calculation of factorial, etc. o Accessing array element with out of index
- such error is caused due to : range, etc
o Poor logic - Such runtime error or Exception is must be handled
o Poor programming language knowledge due to following reasons:
o Poor understanding of software o Avoid abnormal termination of program.
requirements, etc o To make std software.
- Such types of errors are little bit difficult to - To handle any exception, java supports many built-
debug as compare to compile error. in exception handling classes such as:
- It needs good logic and repeated exeuction of ArithmaticException,
program code to solve the error ArrayIndexOutOfBoundsException, SQLException,
etc.
- All these exception classes are derived from ---
“Exception” base class. }catch(<ExceptionClass> obj>{-- code ---}
- to handle runtime error, java language supports e.g.
special keywords as exception handlers like: class Ex2
1. throws, 2. try….catch 3.finally. {
1. throws – this keyword as exception handler works public static void main(String ar[])
in following way {
It will call system defined exception handler. Scanner sc=new Scanner(System.in);
It will show predefined error message. System.out.print(“Enter Ist No:”);
It will stop further execution of program. int n=sc.nextInt();
- “throws” keyword should be used with the function System.out.print(“Enter IInd No:”);
in which the code is enclosed which may generate int m=sc.nextInt();
exception.
- it can be written as: System.out.println(“Addition=”+(n+m));
<RetType> FuncName([arg]) throws <Exception> try
{ {
--- System.out.println(“Division=”+(n/m));
--- }catch(Exception ex)
} {
System.out.println(“Division by Zero not allowed”);
e.g. }
class Ex1 System.out.println(“Subtraction=”+(n-m));
{ System.out.println(“Multiplication=”+(n*m));
public static void main(String ar[]) throws }
Exception }
{ - Thus, in above code, if user enter 2nd value as non-
int n=10,m=0; zero, program succesffully performs all arithmatic
System.out.println(“Addition=”+(n+m)); operations.
System.out.println(“Division=”+(n/m)); - But it, 2nd number is zero, it will go to catch block
System.out.println(“Subtraction=”+(n-m)); and then also exeuctes remaining part of program.
System.out.println(“Multiplication=”+(n*m));  Multiple catch statement
} In catch block, the code to handle exception can be
} enclosed.
- This above program will only execute addition, from - If exception occurs, it will execute catch block and
division statement exception generated and further still further code exeuction will be continued and thus
execution will be stopped. abnormal termianation can be easily avoided.
1. try…catch – these keywords are used to defined - It can be used as:
exception handling block. try
- all those statement by which possibly exception may {
be generated, are enclosed in try block. ---
-In catch block, the code to handle exception can be ---
enclosed. ---
- If exception occurs, it will execute catch block and }catch(<ExceptionClass> obj>{-- code ---}
still further code exeuction will be continued and thus - in many cases it is also found that, same code may
abnormal termianation can be easily avoided. generate multiple exceptions.
- It can be used as: - And for any std. software it is necessary to handle
try each & every exception.
{ - For this, java language allows to use multiple catch
--- blocks with single try block as:
--- try
{ -Built-in exceptions are predefined exception classes
--- such as:
--- ArithmaticException,
--- ArrayIndexOutOfBoundsException, SQLException,
}catch(<ExceptionClass> obj>{-- code1 ---} etc.
catch(<ExceptionClass> obj>{-- code2---} - User Defined Exception – it is an exception class
catch(<ExceptionClass> obj>{-- code3 ---} defined by programmer for a specific user
- Thus, any number of catch blocks can be used with application.
single try block. - e.g.
- This will ensure, all possible exceptions can be Entering –ve value rate or qty in billing application.
handled successfully. Entering out of range value in MarkSheet application.
e.g. - To handle such types of exception, User Defined
class Ex3 exception can be create and used in following steps:
{ 1. Create one class inherited from Exception lib class.
public static void main(String ar[]) 2. Define its constructor for handling error.
{ class <ClassName> extends Exception
Scanner sc=new Scanner(System.in); {
try ---
{ ---
}
System.out.print(“Enter Ist No:”); 3. User Defined exception must be explicitly called
int n=sc.nextInt(); using “throw” keyword
System.out.print(“Enter IInd No:”); throw new <ClassName>( );
int m=sc.nextInt(); e.g.
System.out.println(“Addition=”+(n+m)); class NegValue extends Exception
System.out.println(“Division=”+(n/m)); {
System.out.println(“Division by Zero not allowed”); NegValue( )
System.out.println(“Subtraction=”+(n-m)); {
System.out.println(“Multiplication=”+(n*m)); System.out.println(“Don’t use –ve value for Rate
} or Qty”);
catch(NumberFormatException ex) }
{ }
System.out.println(“Enter only Int value”);
} class Ex4
catch(ArtihmeticExcpeiton ex ) {
{ public static void main(String ar[])
System.out.println(“Division by Zero not allowed”); {
} Scanner sc=new Scanner(System.in);
} try
} {

 Creating user Defined Exception System.out.print(“Enter Rate:”);


- when error occurred during execution phase of int rate=sc.nextInt();
program is called runtime error. System.out.print(“Enter Qty:”);
- Such runtime error also called as Exception & int qty=sc.nextInt();
runtime error are said to be most difficult types of if(rate<=0 || qty<0)
error to debug. throw new NegValue( ); // calling User Def Expt
- java supports exceptoins of following types: else
1. Built-in Exceptoin 2. User Defined Exception System.out.println(“Amount=”+(rate*qty));
}
} ---
} }
Finally clause -The flow chart representation of finally block can be
- java language supports many exception handlers & given as:
one such is finally clause.
- A java program during exeuction need to perform
many different operations.
- Among these, some might be optional and some
may be very compulsory or critical.
- The critcal operatons that every java program
must perform before closing or termination called
as House Keeping Operations.
- These house keeping operations may be :
Closing of DB
Closing of DB Connection
Closing of file, etc
- But, in some cases, if exceptions generated, these
important operations may get skipped and JVM will
not perform these house keeping operations.
- To solve this problem Java Lang supports one
important and very useful keyword or clause i.e.
“finally”.
- using this keyword, a block of executeable code can
be defined. But for this, there must by try block as:
try
{ - When finally block is added to code, for JVM it is
--- compulsory to execute this code before closing the
--- program.
--- e.g. Reading one character from given file. In this,
} in any case, the file must be closed before closing
finally the program.
{ import java.io.*;
--- class Fio1
--- {
--- public static void main(String args[])
} {
- To use, finally block, try block is compulsory, catch FileReader Fobj = null;
block is optional i.e. finally can be used with or with try {
catch block. Fobj = new FileReader("input.txt");
try int c;
{ c = Fobj.read() ;
--- System.out.print((char)c);
--- }catch(IOException ex){}
--- finally
} {
catch(<ExcepClassName> obj) {------} System.out.print(“This is Finally block”);
finally
{ }
--- }
--- }
Unit - V StringObj.toUpperCase();
4. equals( ) – this method used to compare one
string with other in terms of length, characters,
and case. If all are same, it returns zero that
means both strings are equal/same as:
StringObj.equals(“StringValue”);
5. equalsIgnoreCase( ) – this method used to
compare one string with other only in terms of length
and characters, but it ignores the case.
StringObj.equalsIgnoreCase(“StringValue”);
6. concat( ) – This string is used to append new string
String Class at the end of existing string.
- Java a programming language allows to use StringObj.concat(“String”);
different types of data like int, float, double, 7. trim( ) - this string used to remove all leading (left
boolean, char etc. side) and trailing (right side) spaces of given string.
- A char variable at a time can store and process 8. substring( int start, int end) – it extract number of
only 1 char, but in many real-time applications characters from start index to end index -1 as
group of characters is needed. substring.
- Group of character or sequence of characters in StringObj.substring(int start,int end)
programming is called String. 9. charAt( index) – this method is used to extract
- There are many examples where, a program need only one character of given index from string.
to store and process string such as StudName, StringObj.charAt(index);
EmpName, SubjName, etc. e.g.
- In java program, string can be created in one of class str
the following ways: {
o Using char Array public static void main(String ar[])
o Using String object {
- As like, C & C++, in java langauge also char array String s="SRTMU";
can be used to create a string as: System.out.println("Length="+s.length());
- char x[ ]={“SRTMUN”}; System.out.println("Lower Case="+s.toLowerCase());
- But use of char array is not recommened as it System.out.println("Compare="+s.equals("srtmu"));
provides very less options for string manipulations. System.out.println("Compare="+s.equalsIgnoreCase(
- For this, String object can be used. "srtmu"));
- String is one built-in class in java lang available in s=s.concat(" Nanded");
java.lang package. System.out.println("New String="+s);
- It’s object can be created as: System.out.println("one char from
String <obj> = new String (“Value”); string="+s.charAt(3));
String s=new String(“SRTMUN”); System.out.println("Substring="+s.substring(3,7));
or }
String s=”SRTMUN”; }
- This string class provides following built-in Output –
methods: Length=5
1. length() – this method counts and returns number Lower Case=srtmu
of characters in string including spaces. Compare=false
StringObj.length(); Compare=true
2. toLowerCase() – this method converts each New String=SRTMU Nanded
character of string into lower / small case. one char from string=M
StringObj.toLowerCase(); Substring=MU N
3. toUpperCase() – this method converts each
character of string into upper / capital case.
StringBuffer Class StringBuffer sb=new StringBuffer("Jack");
- Java a programming language allows to use
different types of data like int, float, double, System.out.println("String="+sb+"\tLength="+sb.len
boolean, char etc. gth());
- A char variable at a time can store and process sb.append(" Back");
only 1 char, but in many real-time applications System.out.println("New String="+sb);
group of characters is needed. sb.insert(5,"is ");
- Group of character or sequence of characters in System.out.println("New String="+sb);
programming is called String. sb.replace(9,12,"lue");
- There are many examples where, a program need System.out.println("New String="+sb);
to store and process string such as StudName, sb.delete(5,7);
EmpName, SubjName, etc. System.out.println("New String="+sb);
- In java program, string can be created using sb.reverse();
String object. System.out.println("Rev String="+sb);
- But String class having some limitations i.e. it }
creates static string or fixed length string. }
- In this, in between the string new string can not be Output –
inserted or removed. String=Jack Length=4
- to overcome these problems, java lib support New String=Jack Back
StringBuffer class. New String=Jack is Back
- StringBuffer is one peer class of String from New String=Jack is Blue
java.lang package which is used to create dynmaic New String=Jack Blue
string. Rev String=eulB kcaJ
- StringBuffer class can be used as:
StringBuffer <Obj>=new StringBuffer(“string”); Stream Class
StringBuffer sb=new StringBuffer(“SRTMUN”); - As like any other programming language, a java
- This class provides all the functionalities of String program can also different operations.
class and also supports some additional functions like: - one of the important feature of any program is, it
1. append(String) – this method is used to append must be interactive .
new string at the end of existing string as: - A java program needs to get input with-in program
<StringBufferObj>.append(“String”); and also should be able to give output from program.
2. insert(int index, string) – this method used to - For this java program uses Data Flow which can be
insert new string at given index position as: of following types:
<StringBufferObj>.insert(int index, “Newstring”); - flow of data into program
3. replace(int start,int end, “string”) – this method - flow of daout out of program
used to replace charcaters from start index till end - To complete this job of input and output data flow,
index -1 by new string. java language uses concept of Stream.
<StringBufferObj>.replace(int index,int end - Stream is ordered sequence of data that a java
“Newstring”); program uses for input or to give output.
4. delete(int start,int end) – this method used to - Stream is path or channel using which data can be
delete charcaters from start index till end index -1 . taken as input or given as output.
<StringBufferObj>.delete(int index,int end ); - A stream uses two ends, Source to get input and
5. reverse( ) – this method is used to reverse the destination to give output.
given string characters. - Stream in other words is – uniform, easy to use
<StringBufferObj>.reverse(); objected oriented interface between java program and
e.g input/output devices.
class strb - A java program can get input from different sources
{ and can give output to different sources as:
public static void main(String ar[])
{
different location than, complete path must be given
as:
FileReader fr=new FileReader(“C:/abc/input.txt”);
- to get input from any file, that file must be
existing.
- this class provides built-in method read( ) which can
read one character at time from file.
e.g.1 reading one character
import java.io.*;
- The library classes which provides such stream and class Fio1
functionalities to complete input –output operations {
called Stream Classes. public static void main(String args[])
- These classes are available in java.io package of java {
library. FileReader Fobj = null;
- All the stream classes are braodly classified in two try {
main categories based on type of data they use. Fobj = new FileReader("input.txt");
o Byte stream classes – performs Input-Output int c;
operations using bytes. c = Fobj.read() ;
o Character stream classes – performs Input- System.out.print((char)c);
Output operations using characters. }catch(IOException ex){}
- These stream classes are further sub-classified finally
as: {
try
{
Fobj.close();
}catch(IOException e){}

}
}
}
e.g.2 reading all characters from file.
import java.io.*
 Character Stream Classes
class Fio2
- These classes for File I/O are used to perform read
{
& write opepration on file using sequence of public static void main(String args[])
characters. {
- for this, two most commonly used library classes FileReader Fobj = null;
are: try {
FileReader Fobj = new FileReader("input.txt");
FileWriter int c;
i. FileReader – this lib class belongs to java.io. while ((c = Fobj.read()) != -1)
package. {
- This class can be used to perform read operation on System.out.print((char)c);
given file, for this it’s object can be created as: }
FileReader <Obj>=new FileReader(“path & }catch(IOException ex){}
finally
fileName”);
{
e.g.
try
FileReader fr=new FileReader(“input.txt”); {
- If file is available in current location of java Fobj.close();
program, only file name is sufficient, but if it is in }catch(IOException e){}
} creation of files and directories,
}
file searching,
}
ii. FileWriter - this lib class belongs to java.io. File or Directory rename
package.
To check file / directory properties like read-
- This class can be used to perform write operation on only, hidden, etc
given file, for this it’s object can be created as:
FileWriter <Obj>=new FileWriter(“path & File/directory deletion, etc.
fileName”); The File object represents the actual file/directory on
e.g. the disk. Following is the list of constructors to
FileWriter fr=new FileWriter(“input.txt”); create a File object.
- If file is available in current location of java
The object of this class can be created as:
program, only file name is sufficient, but if it is in
complete path must be given as: File <obj>=new File(String pathname);
FileWriter fr=new FileWriter(“C:/abc/input.txt”); e.g.
- While using FileWriter class, following factors to be
rememberd: File ob=new File(“c:\\abc\\f1.txt”);
1. if file is not existing, it will be created by JVM by File ob=new File(“C:/abc/f1.txt”);
given name in given location.
- This class supports many file and directory
2. if file is existing, by default it will be overwritten.
related built-in methods:
3. to avoid overwritting of file, folllwing constructor
to be used:
getParent() – this method returns the name of
FileWriter fr=new FileWriter(“input.txt”,true); parent directory in which file is present.

- this class provides built-in method write( ) which getPath()- this method returns complete path and
can write one character at time in file. name of file including directory and sub-
e.g. directory.
import java.io.*;
class Fio3 exists() – this method returns true if the file is
{ available by the given name else returns false.
public static void main(String args[])
{ canWrite() - this method returns true if the file is
FileWriter Fobj = null; writable by else returns false.
try {
canRead() - this method returns true if the file is
Fobj = new FileWriter("input.txt",true);
readable by else returns false.
Fobj.write('B');
}catch(IOException ex){} length() – this method returns the length of file as
finally integer i.e. number of characters present in file.
{ import java.io.*;
try
{ class Fio3
{
Fobj.close();
public static void main(String args[])
}catch(IOException e){}
{
} File Fobj= new File("c:\\temp\\input.txt");
} System.out.println("Get Parent=" +
} Fobj.getParent());
 File Class System.out.println("Get Path=" +
Java File class represents the files and directory Fobj.getPath());
pathnames in an abstract manner. System.out.println("File is Existing=" +
Fobj.exists());
This class is used for
System.out.println("File is Writable=" +
Fobj.canWrite());
System.out.println("File is Readable="
+Fobj.canRead());
System.out.println("File is Length=" +
Fobj.length());
}
}
Output –
Get Parent=c:\temp

Get Path=c:\temp\input.txt

File is Existing=true

File is Writable=true

File is Readable=true

File is Length=2
Unit -VI - stop( ) – by this, applet exeuction is stopped
temporarily.
- destroy( ) – applet exeution is stopped permenantly.

- As like application, an applet code also to be saved


as className.java extension.
- As like applicaton, applet code can alo be compiled
using java compiler.
 Introduction & Creating Applet - But to execute applet, it should be loaded in applet
- Java programming language is used to create both viewer or in any java enabled browser (e.g hot java)
types of program like application as well as applet. using HTML code.
- Application is java program which get executed - For this, HTML supports a special tag i.e. <Applet>
using local system environment. - a paired tag - with different attributes.
- Applet is small java program created for internet - This HTML code can either be in same java code
computing which can be transported over the internet file enclose in comment entry /*….*/ or it can be
and can be loaded in browser or applet viewer. stored in separate file.
- due to applet programing, java contributed to - The HTML code can be given as:
convert static web pages into dynamic web pages. <Applet code=”ClassName” width=int height=int>
- As like applicatoin , an applet can also perform </applet>
different operations like: e.g.
 Arithmetic operatoins import java.awt.*;
 Dispay graphics, import java.applet.*
 Play sounds, get user input public class Ap1 extends Applet
 Gives output {
 Create animation, etc public void paint(Graphics g)
- Applet in java program can be created in {
following types: g.drawString(“Hello & Welcome”,10,20);
- Local applet – if the applet code is saved on local }
hard disk and loaded in browser, it is local applet. }
- Remote applet – when the applet code is saved /* <Applet code=”Ap1” width=500 height=500>
on server, transported on client machine and </applet>
loaded in browser, it is Remote Applet. */
- To create an applet, services of two library classes - Save the above code as “Ap1.java”
are required such as: - compile the above code as:
i. Applet class from java.applet package javac Ap1.java
ii. Grpahics class from java.awt package. - Load the applet in applet viewer as:
- To create an applet, a java class to be create which appletviewer Ap1.java
must be extended from Applet class as: - in above e.g., drawString( ) is one lib function of
class <ClassName> extends Applet Graphics class which can draw some output on given
{ col (x) & row (y) location.
---
---  Applet Life Cycle
} - Java programming language is used to create both
- Applet as a library class provides many built-in types of program like application as well as applet.
methods like - Applet is small java program created for internet
- init( ) – from where applet initialized computing which can be transported over the internet
- start( ) – applet execution starts. and can be loaded in browser or applet viewer.
- paint( ) – it is used to perform different drawing - Every java applet from it creation stage to end stage
operations on applet window. undergoes in different stages which shows its life
cycle.
- The different stages of applet from its creation point 2. Running State – After initialization state, applet
to end point represents applet life cycle. enteres in this, Running state.
- Each stage of applet also uses it’s built-in method - This state is controlled by start( ) method of Applet
supported by Applet class. class.
- Applet life cycle can be represented as: - this method can be defined as:
public void start( )
{
---
---
}
- This state can be repeated in one life of applet, as
applet if it is in idle state can come back to running
state.
- once the exeuction of start( ) method over, it
automatically calls to paint( ) method.
3. Display State – When the job of running state is
over, applet enters in display state.
- When applet is perforimg different drawing
operation of applet window, it is said to be in display
state.
- This state is controlled by paint( ) method of Applet
class.
- The diagram show following different stages - this method is defined with abstract class
in applet life cycle: “Graphics” of java.awt package as:
1. Initialization state [init ( ) method] public void paint( Graphics g)
2. Running state [start( ) method] {
3. Display state [ paint( ) ] ---
4. Idle or stopped state [ stop( )] ---
5. Dead state [ destroy( )] }
1. Initialization State – Every applet execution starts - this state can be repeated in one life of applet.
with initialization state. 4. Idle State – When applet execution is temporarily
- This state is controlled by init( ) method of Applet stopped, it is said to be in idle state.
class. - If applet is in idle state, it is still in memory and also
- Thus, it is clear that every applet execution starts it does not releases the allocated objects.
with init( ) method, which is used to perform - any applet enters in idle state when its stop( )
following: method is called.
 Creating object needed for applet - this stage can be controlled by stop( ) which can be
 Setting up initial values defined as:
 Loading images, fonts, etc public void stop( )
 Setting color, etc {
- In one life cycle, this stage comes only once and ---
hence init( ) executed only once. ---
- This method can be defined as: }
public void init( ) - this stage can be repeated in one life cycle of applet.
{ - from this stage applet can either enter into to dead
--- stage or running stage.
--- 5. Dead State - When applet execution is
} permenantly stopped, it is said to be in Dead state.
- After finishing its job, init( ) automatically calls to - Every applet can not directly enter into dead state,
start() method. first it enteres in idle state by calling stop( ) method
and then enters in dead state by called destroy( ) - For this HTML supports, a paired tag
method. <Applet>…</Applet>
- Before entereing in dead state following operations - this tag supports many attributes, among these, some
are performed on applet: are optional and some are compulsory.
o All the resources are taken back from applet. - The different attributes are :
o All the objects created are deleted 1. code – this is one compulsory attribute to be used
o Applet is unloaded from memory with <Applet> tag.
- in one life cyle, dead state comes only once for any this attribute is used to specify class name of local
applet. applet to be loaded in browser as:
e.g. <applet code=”ClassName”>…</Applet>
Applet program showing its different stages:
import java.awt.*; 2. codebase – this attribute is used to specify the URL
import java.applet.* of remote applet to be loaded from internet.
public class Ap2 extends Applet <applet codebase=”URL”>…</Applet>
{
public void init( ) 3. width - this is one compulsory attribute to be used
{ with <Applet> tag.
setBackground(Color.red); - This attribute uses one int value which decides the
} horizontal size of applet as:
public void start( ) <applet code=”ClassName” width=int>…</Applet>
{
setForeground(Color.blue); 4. height- this is one compulsory attribute to be used
} with <Applet> tag.
public void paint(Graphics g) - This attribute uses one int value which decides the
{ vertical size of applet as:
g.drawString(“Hello & Welcome”,10,20); <applet code=”ClassName” height=int>…</Applet>
}
public void stop( ) 5. hspace - This attribute uses one int value which
{ decides the horizontal space before and after applet
System.out.println(“Applet stopped”); and also between two applets as:
} <applet code=”ClassName” hspace=int>…</Applet>
public void destroy( )
{ 6. vspace - This attribute uses one int value which
System.out.println(“Applet Destroyed”); decides the vertical space before and after applet and
} also between two applets as:
} <applet code=”ClassName” vspace=int>…</Applet>
/* <Applet code=”Ap2” width=500 height=500>
</applet> 7. align – This attribute is used to decide applet
*/ alignment of applet in browser window or applet
viewer.
 Applet Tag - This attribute use values like LEFT,TOP,BOTTOM,
- Java programming language is used to create both RIGHT, MIDDLE.
types of program like application as well as applet. - by default applet uses LEFT property as:
- Applet is small java program created for internet <applet code=”ClassName” align=Right>…</applet>
computing which can be transported over the internet
and can be loaded in browser or applet viewer. 8. alt – this attribute of <applet> tag used to assign
- As oppose to application, applet can not be directly alternate text which will be displayed in case if applet
executed. is not getting displayed.
- for execution, applet to be loaded in browser using - Generally it is used to show error message if applet
HTML code. is not getting loaded.
<applet code=”ClassName” alt=”text”>…</applet> 2. value – this attribute specifes the actual value to be
Syntax: passed to java applet.
<Applet - one <param> tag can be used to pass only 1 value /
code=”ClassName” paramet at a time.
width=int height=int - if mulitple parameters to be passed, multiple
vspace=int hspace=int <Param> tags to be used.
align=TOP|Left|Right|Bottom|Middle getParameter()
alt=”text”> - It is one lib function in Applet class which is
</applet> used to receive parameter in java code.
e.g. - getParameter() method can be used as:
import java.awt.*; String <obj>=getParameter(“ParmName”);
import java.applet.* - the parameter name must be same as given in
public class Ap3 extends Applet HTML code in same case.
{ - it always receives parameter only in string
public void paint(Graphics g) type.
{ - It can receive only one parameter at a time
g.drawString(“Hello & Welcome”,10,20); - if numeric value passed as parameter then it must be
} typecasted using:
} Integer.parseInt( ) – converts string to int
/* <Applet code=”Ap3” width=500 height=500 Double.parseDouble( ) – converts string to
vspace=10 hspace=10 align=right alt=”Sorry Applet double
can not be Loaded”> e.g.
</applet> import java.awt.*;
*/ import java.applet.*
public class Ap4 extends Applet
 Passing Parameter Applet  {
- Java programming language is used to create both public void paint(Graphics g)
types of program like application as well as applet. {
- Applet is small java program created for internet String studname=getParameter(“sname”);
computing which can be transported over the internet String temp=getParameter(“marks1”);
and can be loaded in browser or applet viewer. int m1=Integer.parseInt(temp);
- As oppose to application, applet can not be directly temp=getParameter(“marks2”);
executed. int m2=Integer.parseInt(temp);
- for execution, applet to be loaded in browser using int tot=m1+m2;
HTML code. g.drawString(“Stud Name=”+studname,10,20);
- as like java application, a java applet can also g.drawString(“Marks1=”+m1,10,40);
receive external input which can be provided by g.drawString(“Marks2=”+m2,10,60);
HTML code. g.drawString(“Tot Marks=”+tot,10,80);
- For this 2 parts are required:
1] <Param> tag in HTML code as sender }
2] getParameter( ) method in java code as receiver. }
- HTML supports a special tag i.e. <Param> tag with /* <Applet code=”Ap3” width=500 height=500 >
its attributes as: <param name=”sname” value=”David”>
<Param name=”ValidName” Value=”any value”> <param name=”marks1” value=”35”>
- the importance of these attributes are: <param name=”marks2” value=”45”>
1. name – ths attribute specifies the valid name of </applet>
parameter to be passed from HTML code to java */
applet.
- this name is case sensitive and must be valid name
(without space)
 Working with Graphics  - this method works in same way but it draws square
- A java program can perform different operations or rectangle with filled colour.
and provide many features. fillRect(10,20,100,100)
- One such important feature of java lang. is use of 5. drawRoundRect(int x,int y, int width, int height,
graphics. int WidthArc, int HeightArc) – this method works
- A GUI based java program (application or applet) as like drawRect() but it also uses two extra
both provides drawing area where different parameters for arc angles.
drawing operations can be performed. e.g.
- The graphics drawing of java uses coordinate drawRoundRect(10,20,30,30,10,12)
system made of 2D pixels using x(col) & y(row) 6. drawOval(int x,int y, int width, int height) –
order. This method is used to draw circle or ellipse.
- It uses the origin 0,0 i.e. upper-left corner of the - when the width and height values are same, it draws
drawing area. circle else it will be ellipse.
- Value of x (column) increases from left to right - This method uses four parameters, x , y as origin
and value of y (row) increases from top to bottom. and width and height to decide the size.
- To perform different graphics related operations, e.g.
java language supports special class “Graphics”. drawOval(10,20,50,50);
- “Graphics” is one abstract class on which object 7. fillOval(int x, int y, int widht, int height) – This
can not be created, it belongs to java.awt method uses four parameters, x , y as origin and width
package. and height to decide the size.
- It supports following built-in methods: - It draws colur filled circle or ellipse.
1. drawString(“string”,int x,int y) – this method fillOval(10,20,50,50);
uses 3 parameters: Complete E.g
o string – to be drawn on graphics window import java.awt.*;
o x – value of column from where output to import java.applet.*;
be started. public class ap4 extends Applet
o y – value of row from where output to be {
started. public void paint(Graphics g)
e.g. {
drawString(“Welcome”, 10,30); g.drawString("Graphics Demo",300,20);
2. drawLine(int x1,int y1,int x2,int y2) – this g.drawLine(298,40,400,40);
method uses four int parameters, x1,y1 as origin and g.drawRect(10,50,100,90);
x2,y2 as end point for drawing line. g.fillRect(10,150,100,100);
e.g.1 g.drawRect(170,50,30,90);
drawLine(10,20,100,20) – this will draw horizontal g.fillRect(170,150,90,30);
straight line. g.drawOval(270,150,100,100);
e.g.2 g.fillOval(370,150,100,100);
drawLine(10,20,10,100) – this will draw vertical }
straight line. }
3. drawRect(int x,int y, int width, int height) – this /*
method uses four int parameters, x, y as origin and <applet code=ap4 width=700 height=700>
width and height decides the size. </applet>
- If the width and height is same it forms sqaure */
else it will draw rectangle. [ use can either use above complete e.g. or any simple
e.g. 1 e.g.]
drawRect(10,20,100,100) – it will draw square.
drawRect(10,20,100,30) – it will draw rectangle.
4. fillRect(int x, int y, int width, int height) – the
previous method draws empty rectangle (without
colour filled).

You might also like