.Java 2 Standard Edition: Easy To Read The Programming Code. Easy Maintainable. Code Is More Flexible

Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

.

JAVA 2 STANDARD EDITION


 It is purely object oriented programming language.
Programming Approach:
There are two commonly programming approach we used………
# Procedural Programming Approach
# Object Oriented Programming Approach
Procedural Programming
In this programming approach we divided a large program into a set of sub procedure (function). That perform
a particular task in the procedural programming every procedure is inter connect to each other.
In programming, procedure is also known as functions, routines, subroutines, behavior, or methods in various
programming languages procedure programming is basically used for developing the simple applications.

Advantages of Procedure Programming Languages:


# Easy to read the programming code.
# Easy Maintainable.
# Code is more flexible.
In the procedure programming most of the data is shared anywhere with in the program only but we can not
access this data out side the program in any condition.

Note:
 Difference between project and products…….
Project is basically for specific client but products are common for all.

Object Oriented Programming Approach:


In the OOPS a large application is consists of the components objects with interact with each other.

Advantages of Object Oriented Programming Approach:


# Real World Programming
# Reusability of code
# Modularity of code
# Resilience to change
# Information hiding (data hiding)

JAVA

J2SE (JSE) J2EE (JEE) J2ME (JME)


Java 2 Standard Edition Java 2 Enterprises Edition Java 2 Micro Edition

JDK Java Development toolkit


SDK Software development toolkit
Java 1.2 version also called Tiger version
 Real World Programming Manish Kumar([email protected])
OOPS Approach directly associated with the real world Scenario (life).
 Reusability of code
In the OOPS Approach we build classes which can be used by Several Java Application.
 Resilience to change
In the OOPS we can involve the various version of the software.
When a change suggested in old system in that case we do not create new software from the scratch. But
We do some changes in the existing software.
 Information hiding (data hiding)
In the Information Hiding we increase data security in a program.
 Modularity of code

Class and Object


They are basic building blocks of the OOPS. Class is just a prototype. There is no memory allocation for the
class. Class has no Physical Appearance. Class is collection of object.

Class
CAR

NENO Swift

Object

1. An Object means a material thing that is capable presented to the senses.


2. An Object has the following Characteristics
 It has a State(Variable).
 It may display behavior (Function).
 It has unique identity.
Feature of OOPS Approach
There are four feature of OOPS.
 Encapsulation
 Abstraction
 Inheritance
 Polymorphism
1. Encapsulation:According to “Grady Booch” Encapsulation is the process that we hide
irrelevant details of an object from the customer. It is the feature in that we provide the security to the
data as well as methods of the class.
2. Abstraction: According to the “Grady Booch” in the abstraction we visualized the irrelevant
details of an object to the customer.

Note:Encapsulation hides the irrelevant details of an object and abstraction makes only
 the irrelevant details of an object visual.
Manish Kumar([email protected])
3. Inheritance: with the help of the inheritance we increase the functionality of an existence class.
In the Inheritance we add some new feature and functionality to an existence class.
 Super Class: A super class or parent class is the one form which another class inherits attributes
and behavior (the variable and function).
 Sub class: A Sub Class or the child class is a class that inherits the variables and function from a
super class or parent class.
Types of Inheritance:
1. Single Inheritance 2.Multiple Inheritance

1. Single Inheritance:In a Single Inheritance a sub class is inherited from only one super class.

Super Class (Parent) Number

Sub Class (Child) Even no. Odd no. Prime no.

2. Multiple Inheritance: In this heritance a sub class is inherited from more one super class
Super
SuperClass
Class(Parent1)
(Parent) Super Class (Parent2)

Sub Class (Child)

4. Polymorphism: It is Inherited from two latten world (1) Poly (Many) (2) Morph (forms or
Shape)

INTRODUCTION TO JAVA
Java Application: It always gets executed on the local computer. There are two types of Java
applications.
1. CUI 2. GUI
1. CUI: In this type of application user interacted always happens through Character for example:-
DOS
2. GUI:In this type of application user interacted through graphics examples:-Windows

Applets:It is the small Java program that run on a web pages and they Required the java enabled
Browser for examples:-Internet Explorer, Netscape Navigator, Hot Java……
Applet program always comes in the GUI format means we can’t create the CUI program in the java.
Servlets:

Packages:

Manish Kumar([email protected])
First program in java
class hello
{
public static void main(String args[] )
{
System.out.println(“Hello this is java”);
}
}
• How to compile a java program?
Install javaopen cmdnow write some command in cmd
1. path=C:\Program Files\Java\jdk1.6.0\bin
2. open saved java file dir.
3. now type javac filename. java (compile command)
4.now type java class name (run command or executing command)
Java is the platform independent language because of byte code is intermediate code that
is under stood by JVM (Java Virtual Machine). 50 Keyword are in JAVA. There are 50
keyword in Java (JDK 1.5), Earlier there were 49 keywords. Unum is a new keyword that
is adds from JDK 1.5.
 In java all keywords comes in the lower case.
 Our program executed from main function.

Public static void main (String args[])

Function

Return Type Class / Predefine class


Non Access Specifier
or Non Access modifier

Access Specifier or
Access modifier

Predefine Class:
In java all predefine Class always starts with the Capital Character. There are 3500 Classes.

System.out.println("hello this is java");

Function
.  . Operator or Member Access Specifier
Static class

Predefine class

Java Java
Java File Byte Code Machine
Compile Interpr
r code
eter
Note:In Mac JDK are also installed.
Data Type:in java there are two types of data types.
1. Primitive data type or the simple data type
2. Abstract or derived data types (reference type)
In primitive data type farther category is 8 categories.
Integer Family:--
Data type Memory Occupation
byte 1 byte
short 2 byte
int 4 byte
long 8 byte
Floating Family:--
Data type Memory Occupation
float 4 byte
double 8 byte

Data type Memory Occupation


char 2 byte
Boolean 8 byte

 character occupied 2 byte in java because of Uni code(universal code). Java supported
Uni code along with ASCII code. Range of ASCII code is 0 to 255 while Uni code range is 0 to
65535.bit’s full name is binary code.
 There are two new data types in java if I compare with the c++, Those are byte and
Boolean.
2. Reference Data type:--
It is inherited from the primitive data type for example—class, Array, interface, etc.

Defining the variable and literal:


Int a=10; int Data Type, a  Variable, = Assignment operator, 10Value/Constant.
A variable is name that referred of a memory allocation. Where we store some value.

Naming conventions and rule for the variables:


1. A variable name should be meaningful, short.
2. We can’t have the space in between of the variable name but we can use the underscore sign
inside of space.
3. Special symbol are not allowed in the variable name but we can use two special symbol those are
following $ and_.
4. We can’t use the keyboard as a variable name.
5. We can’t start the variable name with the digit but digit can be in between of the variable name.
//this program is for data type and variable.
class ram1
{
public static void main(String args[])
{
int a=10;
boolean n=true;
double m=2.0564899;
System.out.println("the value of var is="+a); Manish Kumar([email protected])
System.out.println("the value is booleaan="+n);
System.out.println("the value is dou="+m);
}
}
+  is concationation (used for joining to sentence or variable).

Operators in Java
1. Earthmatics operator:--(+, -, *, /, %)
+ use for addition.
- Use for subtraction.
* use for multiply.
/ Always occupy the quotient.
% always occupies the reminder.

//this is demo for / and % operators.


class opdemo
{
static public void main(String..ar)
{
int r1,r2,r3,r4;
r1=7/2;
r2=2/7;
r3=7%2;
r4=2%7;
System.out.println("the value of r1 is="+r1);
System.out.println("the value of r1 is="+r2);
System.out.println("the value of r1 is="+r3);
System.out.println("the value of r1 is="+r4);
}
}
In java access specifier and non access specifier can be interchange (static public void main
(string…agr)) or (static public void main (string[]arg)) or (static public void main (string agr[]))
it (…) is called var_args.

Increments and decrement operators:--


When we want to increase the value of variable by one(1) that time we use the increments
operator and we want to decrease the value of a variable by one(1) that time we use decrement
operators.
The increment operators farther categorized in two categories.
1. Pre increment operators 2. Post increment operators
The decrement operators also farther categorized in two categories.
1. Pre decrement operators 2. Post decrement operators
//this is demo for in. and de. Operators.
class demo
{
static public void main(String...m)
{
int n=10; Manish Kumar([email protected])
System.out.println("the value is="+ ++n);
n=10;
System.out.println("the value is="+ n++);
n=10;
System.out.println("the value is="+ --n);
n=10;
System.out.println("the value is="+ n--);
}
}

Array
It is special variable. In that we can store the more then one value of the similar data type.
It is categorized in 2 categories.
1. Single dimensional array
2. Multi dimensional array

Array always starts with 0.


Memory allocation of array.
EMP_ID [0]
EMP_ID [1]
EMP_ID [2]

//this is demo for array


class array
{
public static void main(String...m)
{
int []a={10,11,12,13};
for(int i=0;i<4;i++)
{
System.out.println(a[i]);
}
}
}
 In Java if we are given the value for an array at the time of declaration. That time we can not
give the size for an array. Like this…….
int [4]a={10,11,12,13}; is wrong

In Java file name and class name can be different but if our class is public then file name and class name
must be same.

We used " public static synchronized final void main(String []args)”n the place of “public static void
main(String []args)”
Question Can we executed my program with out main?
Answer::

Conditional Statement:
When we want to executed the selected data based on the condition that time we use the if else Statement
or switch case statement.

When we executed only one statement in the if block or in the else block that time curl brace is optional,
but if we are executing more than one statement in the if block and else block that time curl brace is
mandate.

Relational operator:
This operator is basically used to compare the value is two variable and find the relationship b/w these
two. It is always give Boolean value.
<, >, <=, >=, ==, !=
//this demo for relational operator //this demo is for if else
class relopdemo class ifelse
{ {
public static void main(String[]arg) public static void main(String[]args)
{ {
System.out.println(100>99); int age=20;
System.out.println(10>-10); if(age>18)
System.out.println(0>-0); {
System.out.println(10==10); System.out.println("u r a valid voter");
System.out.println(10<=11); }
System.out.println(10>=10); else
System.out.println(10!=9); {
} System.out.println("u r not valid voter");
} }
}
}

Else is optional it means it is not mandate to use else after that if.
Logical Operator:
When we use to combine the expression that time we use the logical operator.
1. Logical AND (&&) Operators: It returns true if both condition must be true.
2. Logical OR (||) Operators: It returns true if either of the condition is true.
3. Logical NOT ( ! ) Operators: It returns true if value is false.
4. Logical XOR (^) Operators: It returns true if both conditions are dissimilar

//this demo is for logical operator


class Logopdemo
{
public static void main(String[]args)
{
boolean preLoanRequest=false;
double loanAmount=4000;
if((!
(preLoanRequest))&&(loanAmount<5000))
{
System.out.println("Loan Can be
Offered");
}
else
System.out.println("Loan not to be
offered");
}}

Good Program Property:


1. Write class and interface Ist Letter is Capital.
2. Variable and Function write in Camel case.
3.

Switch Case Statement:When we want to test the value of a variable again of list a case level.
//this demo is for switch case  Note: break is the keyword that is use
class switchdemo in the switch case and the loop with the help
{
public static void main(String[]args) of that we move out from the switch block
{ and from the loop.
int a=20;
switch(a)
{  Important Point:
case 10: 1. we can use only byte, short, int, char, and enem
System.out.println("u choise 10"); In the switch case. It means we can’t use long, float,
break; double and Boolean in the switch case.
case 20: 2. we can use the default in the switch case any
System.out.println("u choise 20"); where.
break; 3. we can’t have more then one case with same
case 30: value.
System.out.println("u choise 30");
break;
default:
System.out.println("not good choice");
break;
}}}

JAVAC JVM (JRE)

Hello.java

Hello.class

Static initializer block


Static initialize block gets executed at time of loading.
Exit is a pre define static function of the system class with the help of that we move out from the JVM (JRE).

LOOP
When we want to repeat a particular task again and again, that time we used the loop.
In java loop is categorize in four categories.
1. While Loop //this demo for while loop
2. Do while loop class while_loop
//this
3. demo
basicfor
fordo while loop
loop // {this is demo for basic for loop
class4.Do_while_loop
enhanced for loop or for each loop public
class static void main (String []arg)
Basic_for_loop
{ {{
public static void main(String []arg) int i=0;
public static void main(String[]arg)
{Java is a case Sensitive Language. { while(i<=10)
int i=0;
while (1)= wrong int{ arr[]={10,20,30,40};
do
while (True)= wrong System.out.println("hi
for(int thi is #");
i=0;i<arr.length;i++)
{while (true)=right { i++;
System.out.println("this is j#"); }}}
System.out.println(arr[i]);
i++; }
}while(i<10); }
} }
}
Length is predefine property of an array with the help of that we can find out the no. of element in
array
 length ( ): it is a function means it is not array property. It is used with function class.

4. Enhanced for loop or for each loop:


It is basically meant for array and collection with the help of that we can print the value from the begning to
end.

//this is demo for enhanced for loop 1. For each loop is used in java from jdk 1.5
class Enhanced_for_loop 2. For knowing java version we use javac –version
{ command.
public static void main(String[]arg) 3. function is also called method and variable is
{ called data member.
int arr[]={10,20,30,40,50,60};
for (int num:arr) For(int num:arr)
{
System.out.println(num); Expression
} Declaration
}
}

int num;
for(num:arr)  Wrong for(int num:arr)  Right

//this is demo for data member and method Instance variable is having the separate copy for
class Student the individual instance. If we want to access (use)
{ any time from the class we have to create an
String name; object of the class.
int age; Student S = new Student ();
void display() //instance funcation
{
System.out.println("my name is "+name);
System.out.println("my age is "+age); Constrictor
}
Keyword
static public void main(String []a)
{
Student S=new Student ();
S.name="Manish";
S.age=20; Assignment Op.
S.display();
}} class Reference variable(object reference )
S it is not an object.
new is a keyword with the help of that we create an object.
 in java every object always create a heap memory that is why every object variable (instance variable)
always create an heap memory.
 function and function variable always lives in the stack memory.
 when we does not give the value to the instance variable that time instance variable gives the default
values.

S name
age
name
S1 age

Stack Heap

Memory
Default Value:

byte float char ‘\u0000’ String null Boolean false


short 0 double 0.0
int
long
//this demo for default value
class Def
{
byte a;
boolean b;
double d;
char c;
String s;
static public void main(String[]arg)
{
Def o=new Def();
System.out.println("default value for byte="+o.a);
System.out.println("default value for boolean="+o.b);
System.out.println("default value for double="+o.d);
System.out.println("default value for char="+o.c);
System.out.println("default value for String="+o.s);
}
}

Constructors
Constructors are the special function because it has get the same name of the class.
It is not having any return type
It gets automatically called while we create an object of a class.
There is no need to call the constructors. It gets automatically called.
It is meant only for the initialization.

Manish Kumar([email protected])
Types of Constructors:--
In java there are three types of constructors.
1. Non parameterized constructors.
2. Parameterized constructors
3. Default Constructors
//this is demo for non_parametrized_construcotrs //this is demo for non_parametrized_constracotrs
class non_parametrized_construcotrs class parametrized_constracotrs
{ {
int a,b; int a,b;
non_parametrized_construcotrs() parametrized_constracotrs(int num1, int num2)
{ {
a=10; a=num1;
b=20; b=num2;
} }
void sum() void sum()
{ {
int result=a+b; int result=a+b;
System.out.println("result is="+result); System.out.println("result is="+result);
} }
public static void main(String []a) public static void main(String []a)
{ {
non_parametrized_construcotrs h=new parametrized_constracotrs h=new
non_parametrized_construcotrs(); parametrized_constracotrs(20,25);
h.sum(); h.sum();
} }
} }

3. Default constructors:
When we do not create a constructor that time java automatically creates constructors, which is known as
default constructors.

Access Specifies
With the help of Access Specifies we define the scope of the variable, function, class. In java there are four
types of access specifies
1. Public
2. Private
3. Protective
4. Friendly / default / No Access Specifies

1. Public Access Specifies:


With the help of the public access specifies we can access the class , variable , function any where in the java
universe.
2.//this
PrivatedemoAccess Specifies:
for this keyword Instance Variable: under the class and outside the
Private variable and function can only be accessible onlyfunction
class This with in the class. In that they are declared. .
{ it means we can’t access the private things outsideLocal the class in any condition.
Variable: under the functions, it is also
3.int
Protected
num=10; Access Specifies: called automatic variable, static variable, and
protected
public voidvariable and protected
disp(int num) function can be access anywhere in the same packages plus (+) kids (child).
method variable.
{ Child class can be any where in the same packages asStatic well as outside the
variable: packages
under also.and outside the
the class
Packages are the collection of many classes and interface.
this.num=num; function with static keyword also called class
4.}Friendly / default / No Access Specifies: variable.
When we do not specify any access specifies before the class, variable, function that time default access
specifies is automatically
public static used. []a)
void main(String
Default
{ things (variable, class, function) can be access any where in the same packages only.
ThisWe t =can’t use the private and protective before the class.
new This();
t.disp(20);
System.out.println("answer is ="+t.num);
}
}
//this demo for variable  In java instance variable and static variable get the
class variable Default value but local variable does not get the default
{ value. It means we can’t use the local variable without
static int a;//this is class variable Initialization otherwise we would get the complier error.
int b; //this is instance variable
public void disp()  we used static variable without class object .
{
int c=10; //this is local variable
System.out.println(c);
}
public static void main(String[]a)
{
variable v= new variable();
v. disp();
System.out.println(a);
//we use static variable without class object
means here v.a
System.out.println(v.b);
}
//this
} is demo for function overloading1 //this is demo for function overloading1
class Overloading1 class Overloading2
{ {
public void sum(int a, int b) Function Overloading  a, int b)
public void sum(float
When{ we have the more than one function with the same{ name but different signature in a class. That process is
known as function
int result; overloading. float result;
Types of signature.
result=a+b; result=a+b;
There are three types of signature.
System.out.println("result="+result); public void sum(int a, int b,int c)
System.out.println("result="+result);
}1. No. of Arguments } {
2. Types of Arguments
public void sum(int a, float b) int result;
public void sum(int a, float b)
{3. Order (Sequence) of the Arguments. { result=a+b+c;
float
//this is result;
demo for function overloading float result;System.out.println("result 1="+result);
result=a+b;
class Overloading result=a+b;}
public static void main(String[]a)
{ System.out.println("result 1="+result); System.out.println("result 1="+result);
} void sum(int a, int b) } {
public
{ public static void main(String[]a) public static Overloading o=new Overloading();
void main(String[]a)
o.sum(2,3);
int{ result; {
Overloading
result=a+b; o=new Overloading(); Overloadingo.sum(2,3,4);
o=new Overloading();
o.sum(2,3); o.sum(2,5); }
System.out.println("result="+result);
} o.sum(2,3); o.sum(2,3);
} }
} }
Passing Arguments in the main methods

//this is program for arguments at command lines after compile command for
class Argument run the program is java class
{
public static void main(String[]a) name String0 String1 then
{ press enter
System.out.println("my name is "+a[0]);
System.out.println("my age is "+a[1]);
}
}
//after compile command for run the program is java
classname String0 String1

Nested class
When we have a class inside a class that process is known as nested class.
//this is example of nested class public static void main(String[]a)
class Myouter {
{ Myouter m=new Myouter();
int a; Myouter.Myinner m1=m.new Myinner();
class Myinner m1.disp ();
{ }
void disp() }
{ //after compile the program here two class r
System.out.println(a); makes
} 1.Myouter$Myinner.class
} 2. Myouter.class

Inheritance
Java does note Support multiple inheritance. It means in java we can’t inherited more thane one
class at a time. //this program is for inheritance
Syntax: class A
class A {
public void display()
{ {
} System.out.println("i m child");
class B extends A }
{ }
} class B extends A
{
public static void main(String[]a)
{
B b=new B();
Mainly object makes of child class. b.display();
Always makes child object. }
}
Multilevel Inheritance:
Multilevel inheritance takes a value at one time. In multilevel inheritance we inherited the variable and function
from another sub class.
Syntax: Class A
class A
{
} Class B
class B extends A
{
}
Class C
class C extends B
{
}
//this program is for multilevel inheritance public static void main(String[]a)
class A {
{ C o = new C();
public void disp() o.disp();
{ o.disp1();
System.out.println("hello i m grand parent"); o.disp2();
} }
} }
class B extends A //here which class they contain main body of
{ program we save our file that class name. Java
public void disp1()
{
System.out.println("hello i m parent");
}
}
class C extends B
{
public void disp2()
{
System.out.println("hello i m child");
}
public static void main(String[]a)
Super Function (‘super()’)
 In the constrictor first line is always is super function whether we type (write) or not write it.
 Super is the pre defining function it always calls the parents class constrictors.
 In java we do not inherited any class that time every class automatically inherited the object class.
// this program is for super function Javap classname
class Super_function It is using for decompile the program.
{ Javap -c classname
Super_function() It is using for decompile the program in details.
{
super();//super function Dos makes always parent directory and
System.out.println("this seq no is "); current directory.
}
}
class Super_function1 extends Super_function
{
Super_function1()
{
super();//super function
System.out.println("i m the child class ");
}
public static void main(String[]a)
{
Super_function1 f=new Super_function1();
}
}

Methods Overriding (Function Overriding)


Function overriding is only possible in the case of inheritance implementation. When we have the ageist (same)
function in parent class as well as in child class. That process is known as Function overriding.
Ageist means each and every thing will be same.
//this program is for function overriding.  In the function overriding always called that
class Parent class for where we are creating an object.
{ 1.
public void disp() Parent C= new Parent ();
{ C.disp ();
System.out.println("i h black & white color"); OUTPUT:--
} i h black & white color
} 2.
class Child extends Parent Parent C= new Child ();
{ C.disp ();
public void disp() OUTPUT:--
{ I have all colours
System.out.println("i have all colours"); 3.
} Child C= new Parent ();
static public void main(String[]a) C.disp ();
{ OUTPUT:--
Child C= new Child(); It is not complied
C.disp();
}
}
//OUTPUT:--
//I have all colours

Manish Kumar([email protected])
Super Keyword
Super is the pre defining keyword with the help of that we can call the parent class function and variable.
//this program is for function overriding with super //this program is for function overriding with super
keyword keyword
class Parent class Parent
{ {
public void disp() public void disp()
{ {
System.out.println("i h black & white color"); System.out.println("i h black & white color");
} }
} }
class Child extends Parent class Child1 extends Parent
{ {
public void disp() protected void disp()
{ {
super.disp(); super.disp();
System.out.println("i have all colours"); System.out.println("i have all colours");
} }
static public void main(String[]a) static public void main(String[]a)
{ {
Child C= new Child(); Child1 C= new Child1();
C.disp(); C.disp();
} }
} }
//OUTPUT:-- //OUTPUT:--
// i h black & white color //not compile(order change of public and protected)
//I have all colours

//this program is for function overriding with super //this program is for function overriding with super
keyword keyword
class Parent class Parent
{ {
protected void disp() public void disp()
{ {
System.out.println("i h black & white color"); System.out.println("i h black & white color");
} }
} }
class Child1 extends Parent class Child extends Parent
{ {
public void disp() void disp()
{ {
super.disp(); super.disp();
System.out.println("i have all colours"); System.out.println("i have all colours");
} }
static public void main(String[]a) static public void main(String[]a)
{ {
Child1 C= new Child1(); Child C= new Child();
C.disp(); C.disp();
} }
} }
//OUTPUT:-- //OUTPUT:--
// i h black & white color //not compile(because here different function in
//I have all colours parent and child class) demission are not allow in
//permission are allow in f. overriding function overriding
In the function overriding demission are not allow but permission are allow.
Abstract Keyword
abstract keyword can be used with class and function, means it can not be used with variable.
abstract class can only be inherited it and can’t be instanced . It means we can only inherited the class but
we can not create object of it.
abstract function are those function there are not having the body it means they must be followed by
semicolon (;).
If we have abstract function in a class it means class must be
// this program for abstract class
abstracted but vice versa it not mandatory.
abstract class father
{
public abstract void disp();
}
class child2 extends father
{
public void disp()

{
System.out.println("child ");
}
public static void main(String[]a)
{
child2 c= new child2();
c.disp();
}
}

Final Keyword
Final is a keyword it can we used with class, variable, function.
 Final class can’t be inherited it can also only be instanced. It means we can not inherit the final class be can
just create an object of it.
 Final function can not be override it means we can not override the final function.
 Final variable can’t be changed it means we can not change he value of the final variable once be assign it.
//example of final keyword //example of final keyword
final class father final class father
{ {
final int a=10; final int a=10;
final void disp() final void disp()
{ {
System.out.println("i m parent"); System.out.println("i m parent");
} }
} }
class child3 extends father class child3
{ {
final void disp() public static void main(String[]a)
{ {
System.out.println("i m child"); father f= new father();
} f.disp();
public static void main(String[]a) System.out.println(f.a);
{ }
child3 f= new child3(); }
f.disp();
System.out.println(f.a++);
}
}
1 2
In first program have 3 errors but 2 program is right, in first program we show the Final class not inherited,
final function not to be override and final variable value not to be changed.
Interface
 1. It is a set of abstract methods and static data member
 2. It is known as prototype for a class.
 3. Method defined in a interface are only abstract methods, It is the 100 % abstract class because interface
all function are the abstract and variable are public static final.
 4. In java we can implement the more than one interface in a single class.
Syntax:--
Interface < interface name >
{

}
//example of multiple inheritance in interface
//example
interface inter of interface  If a class is implements an interface in that
interface
{ inter situation, class has to define to body of all function.
{ int f=2500;  public static final data type is directly accessible.
public static
void disp();final int f=2500; e.g. in given example we used System.out.println(f); or
public
} abstract void disp(); System.out.println(h.f);.
}interface inter1
class
{ hello implements inter
{ void disp1(); Public static final int a=10; These are same
public void disp() static final int a=10; because in
} final int a=10;
{interface inter2 extends inter1 interface
System.out.println("we are override the father"); int a=10; function are
{
} void disp2(); abstract function
public static void main(String[]a) and data type are
}
{interface inter3 extends inter2 static data
hello h= new hello(); public abstract void display(); member we
{ abstract public void display();
h.disp(); write or not
void disp3(); abstract void display();
System.out.println(f); write it
} void display();
}public class hi implements inter3,inter
}{ public abstract void display();
public void disp()
{Two interface are implements by a class.
//two interface are implements
System.out.println by adisp");
("this is first class public static void main(String[] args)
interface
} inter {
{public void disp1() hi h=new hi();
{ int f=2500; h.disp();
void disp();
System.out.println ("this is secound disp"); h.disp1();
}} System.out.println(f);
interface
public voidinter1
disp2() }
{{
void disp1();
System.out.println ("this is third disp"); }
}}
public public class hi implements inter1,inter
void disp3()
{{  Note:-- Java Supports multiple inheritance in
public void disp()
System.out.println ("this is fourth disp"); the case of interface.
{}
System.out.println ("this is first args)
public static void main(String[] disp");
} {
public void disp1()
hi h=new hi();
{ h.disp();
System.out.println
h.disp1(); ("this is secound disp");
} h.disp2(); Manish Kumar([email protected])
h.disp3();
Example of multiple inheritance in interface is given below.
System.out.println(f);
}

}
Exceptions
Exceptions can be defined as an abnormal event that occurs the time of program execution. In exception
program are abnormally terminated.
In java there are two types of error
1. Compiler time error
2. Run time error
Run time error is known as the exception.
Object
Error Throw ableRunException
time Exception
We can implements the exception handling in a program by using the following keywords try, catch, throw,
throws, finally.
Try & Catch:--
Try block is known as the guarded section because in that we write those statement in that exceptions might
rise. Exception can handled by the try for that sack we used the catch keywords catch block is basically used in
an exception handler.
Syntax:--
//example for exception handling
try
public class exception_handling
{
{
//statement that can cause an exception
public void func()
}
{
catch
int d,a;
{
try
//error handling code
{
}
d=0;
//example of exception a=42/d;
public class exception System.out.println("this number will note be
{ printed");
static void func() }
{ catch(ArithmeticException e)
int d=0; {
int a=42/d; System.out.println("please do not devide by zero");
} }
public static void main(String[] }
args) public static void main(String[] args)
{ {
exception e= new exception(); exception_handling e= new exception_handling();
e.func(); e.func();
} }
} }

catch is working as an exception handler catch always gets excited when exception is raised. It means catch is
conditional not raised a single try can have the multiple catch statement.
//example of multiple catch int b=Integer.parseInt(args[1]);
public class multi_catch int c=b/a;
{ System.out.println(c);
public static void main(String[] args) }
{ }  catch(ArithmeticException e) function of
“parseInt” is the pre define
try
catch(NumberFormatException e) {
the integer class with the help of that we
{{ 1
System.out.println("please
converts a value into integer. enter good
2
intSystem.out.println("please
a=Integer.parseInt(args[0]);
enter only number ");
number int b=Integer.parseInt(args[1]);
"); }
}
}
}
3

For showing all messages own message + jvm message (for exception) than we write like this
catch(ArithmeticException e)
{
System.out.println("please enter good number "+e);
}
catch(NumberFormatException e)
{
System.out.println("please enter only number "+e);
}
Array index out of bounds exceptions.
//example of multiple catch A try must have at least one catch it means a
public class multi_catch try can not be without catch
{  try must be followed by catch it means
public static void main(String[] args) we can not have any things between try and
{ catch example below.
try e.g.
{ try
int a=Integer.parseInt(args[0]); {
int b=Integer.parseInt(args[1]); //statement that can cause an exception
int c=b/a; }
System.out.println(c); System.out.println("this is not valid");
} catch
catch(ArithmeticException e) {
{ //error handling code
System.out.println("please enter good number "); }
} OUTPUT:--
catch(NumberFormatException e) not compiled
{
System.out.println("please enter only number ");  In the exception we have super class
} above of the sub class and in that case
catch(Exception e) compiler would not compiled the program
{ e.g.
System.out.println("there are some error "+e); catch(Exception e)
} {
} }
catch(NumberFormatException e)
} {
}
catch(Exception e)
{
}  wrong
catch(NumberFormatException e)
{
}
This program are not compile because super class above and sub class below of super class.

Finally Block:When we want to do a particular task whether exception is raised or not that time we used the
finally block.
 the sequences is always try than catch than finally .
 in java try can’t be alone it must have either catch or finally.
class try_catch_finally class try_finally
{ {
public static void main(String []m) public static void main(String []m)
{ {
try try
{ {
int a=Integer.parseInt(m [0]); int a=Integer.parseInt(m [0]);
int b=Integer.parseInt(m[1]); int b=Integer.parseInt(m[1]);
int c=a/b; int c=a/b;
System.out.println(c); System.out.println(c);
} }
catch(ArithmeticException e) finally
{ {
System.out.println("value of b can't 0"); System.out.println("Bye...");
} }
finally }
{ }
System.out.println("Bye...");
}
}
}

Throw Keyword: when we want to farcically called the exceptions that time we used throw keyword.
If we are using the throw keyword than we always used object and object variable after the throw keyword, it
means we can not use the class name after the throw keyword.
class throwclass
public class throwsclass{
{ static void throwDemo()
//public static String{ Null;
public static void maintry (String []args)
{ {
class plnclass
String input=null; throw new ArithmeticException("Hi");
{
try }
public String toString()
{ catch(ArithmeticException e)
{
String Capitalized ={ Capitalized(input);
return "hello i m manish";
System.out.println(Capitalized);
System .out.println("Caught:" +e);
}
} }
public static void main(String[]m)
catch(NullPointerException
} n)
{
{ public static void main(String []m)
plnclass p=new plnclass();
System.out.println(n); {
System.out.println(p);
} throwDemo();
//or System.out.println(p.toString());
} }
}
public static String } Capitalized(String s)throws
}
NullPointerException
Throws
{ Keyword:When we want to declared the exceptions in a function that time we used the throws
keyword it is always used in front of function. If we are using the throws keyword after the function it means
if(s==null)
that function
{ might generated the exception. We always use the class name after the throws keyword, it means
we can throw
not us the
newobject and object variable after passed
NullPointerException("you the throws.
a null
Handle
value "); try and catch, Declared  throw and throws
}
String theRest=s.toUpperCase(); Println( ) or println function automatically
return theRest; called the toString( ) or toString function
} always e.g.
}
Assertion
Assertion is comes from JDK 1.4, Assertion are the statements in java with the help of that we test the
assumption made in a program execution. It is a like an exception but here we have choice for enable and
disable assertion in program. Command for running assertion program is given below
java –ea classname , command for running program without assertion in java is java –da classname. Default
program are run without assertion. e.g.
//example of assertion keyword Assertion are two types
class Assertion 1. Simple Assertion
{ 2. Really Simple Assertion
static float bal=1500;
static float transaction(float amt) assert Boolean express
{ :”Statement”;  it is called Simple
bal=bal-amt; assertion while
System.out.println("The current balance is ==>$"+bal);
return bal;
} assert Boolean expression; it is
public static void main(String[]m) called really simple assertion.
{
float n; in assertion first expression is always
for(int i=0;i<4;i++) in the Boolean value.
{
n=transaction(400);
assert bal>=500.00:"balance is to low";
}
}
}
User define Exceptions 
The examples of user define exception is given below.
//examples of user define exceptions
class UserException extends Exception
{
UserException()
{
}
public String toString()
{
return"UserException the sum to two no. exceeds 20..";
}
}
class user_exception
{
static void calc(int a,int b)throws UserException
{
int c;
System.out.println("calculation method("+a+","+b+")");
c=a+b;
if (c>20)
throw new UserException();
System.out.println("the value of two no. is = "+c);
}
public static void main (String[]m)
{
try
{
calc(12,1);
calc(12,12);
}
catch(UserException obj)
{
System.out.println("Caught"+ obj);
}
}
}

Applet and Swings


Types of interface
There are two types of interface.
1. CUI (Character user interface)
2. GUI (Graphics user interface )
Components of GUI:--
Visual controls such as label test box are known as components. there are three types of components in java.
1. Top level Components  frame, applet
//example of awt components  panel, tabbed pane.
2. Intermediate
import java.awt.*;
3. atomic components  button, level, text box.
class frame
Packages Its is the collection of class and interface, it is categorize in two category .
{ 1. Pre-Define Packages
public
2. static
User- void
Definemain(String[]m)
Packages
{ AWT (The Abstract Window Toolkit) 
Frame f =new Frame("my frame");
This packages is basically used the creation of the Graphics user interface. e.g.
f.setBackground(Color.black);
f.setSize(300,200);
f.setVisible(true);
System.out.println("if u want to exit then go dos prompt press ctrl+c");
}
}
Note: -- Constant comes in java in capital letters.

//example of frame with the help of inheritance //example to make a button and add it in the frame.
import java.awt.*; import java.awt.*;
class myf extends Frame class f
{ {
myf()//constractor public static void main(String[]a)
{ {
super("This is my frame"); Frame m=new Frame("this is button frame");
setBackground(Color.yellow); m.setSize(300,300);
setSize(300,300); Button b=new Button("press here");
setCursor(Frame.HAND_CURSOR); m.add(b);
show();//to show the frame m.setVisible(true);
} b.setBackground(Color.green);
public static void main(String[]a) m.setLocation(50,50);
{ }
myf f =new myf();//or new myf(); }
System.out.println("please press ctrl+c to exit");
}
}

--:HTML:--
Html has two tad first head and second body. <head> </head>, <body> </body>,
< > Tag, <…..> Element,
Tag are two types 1.Contains tag 2. Empty tag

<html>
<head >
<title>my web page</title>
</head>
<body background="default\2.gif">
<b ><h1 align="center">My name is manish.</h1></b><hr/>
<marquee bgcolor="yellow" direction="right">manish</marquee>
</body>
</html>

Manish Kumar([email protected])

Applet
An applet is a java program that is enabled in a HTML web pages applets program always gets execution inside
the web browser (IE).
 That is why we need java enabled web browser.
 With the help of applet we can only create GUI Programs.
Java.lang.object

Java.awt.component

Java.awt.container

Java.awt.panel

Java.applet.Applet
 Applet class contains various methods with the help of those methods we can display the text, images, audio
and etc.
Example of applet :--
//code for prg1.java <html>
import java.applet.*; <title> //code for prg1.html </title>
import java.awt.*; <body>
public class prg1 extends Applet <applet code="prg1.class"
{ width=300
public void paint (Graphics g) height=300>
{ </body>
g.drawString("Hello,this is my first java </html>
applet",50,100);
}
}

How to run applet program in java?


First Method
1. First save program in java file and then save html program in html file.
2. In CMD compile the java file and after compilation run html file.
Second Method
1. First save html code and program code in java file but remember that the html code writes in
import comment
java.applet.Applet;
(/* */).
import java.awt.*;
2. In CMD compile the java file and then write command appletviewer javafilename press enter.
public class prg2 extends Applet
{
Void
Font f=paint
new(): It is the pre
Font("Times Newdefine function of the applet class. With the help of that we provide display area
Roman",Font.BOLD+Font.ITALIC,30);
for
Fontthef1=
drawing.
new Font("arial",Font.ITALIC,15);
Graphics It is the
public void paint pre define
(Graphics g) class of the java.awt package, with the help of that we can draw the string,
lines,
{ rectangle, etc…
<html>
drawString:
g.setFont(f); It is the pre define function of the graphics class with the help of<body> it we can draw the string its
takes the three arguments
g.drawString("my name1. is string Text 2. x co-ordinate 3. y co-ordinate.
manish",100,100); <applet code="prg2.class"
g.setFont(f1); width=600
g.drawString("i m a student of b.tech",110,120); height=300>
g.drawString("my name is manish",110,140); </body>
} </html>
}
Font : It is the pre define class it comes in the java.awt package with the help of it we can adjust the font, it
takes three arguments 1. font name 2. font property (bold, underline, italic) 3. Font size.
setFont() : it is used for set the font.
import java.awt.*; <html>
import java.applet.*; <body>
public class prg3 extends Applet <applet code="prg3.class"
{ width=600
String n; height=300>
String a; <param name="Name" value="manish">
public void init() <param name="Age"value="20">
{ </body>
n=getParameter("name"); </html>
a=getParameter("Age");
}
public void paint(Graphics g)
{
g.drawString(n +" is a student of b.tech.",20,20);
g.drawString(n +" is only"+a+"year old.",20,50);
}
}
Param tag is used always inside the applet.
Param tag always inside the applet.
Get parameter: It is the pre define function of the applet class with the help of it we retrieve the value of the
parameter, it always retrieve the string type values.
Audio clip player(midi player)
import java.applet.Applet; <html>
import java.applet.AudioClip; <body>
public class BackgroundPlay extends Applet <applet code="BackgroundPlay.class"
{ width="200"
AudioClip c; height="100">
String soundurl; <param name="soundurl"value="own.mid">
public void init() </body>
{ </html>
soundurl=getParameter("soundurl");
c=getAudioClip(getDocumentBase(),soundurl);
c.play();
}
}
getAudioClip: It is the predefine function of the applet class it takes two arguments 1. contaxt information
about the songs, 2. Song name.
 It returns the audio clip type value.

Some of the methods are follows


1. void init()  inti function get s execution when we executed applet first time.
2. void start()  start function get execution after the init or applet received the focus.
3. void stop()  stop function gets execution when applet looses its focus.
4. void destroy()  destroy function gets execution when we remove the applet from the memory.
5. void pain ()  it draw the applet output.

HTML tag in Applet:


We need to include the java file in a html file to load the file in web browser.
 The applet tag is basically used to embed (add) an Applet in a html document.
 Applet tag always refers inside the body tag.
<html> <head></head>
<body>
<applet
code
codebase
height
vspace
hspace
align
alt
<param name= parameter name value= value of the parameter >
</applet>
</body>
</html>
Code and Codebase Attributes: code attribute is basically used to indicate the name of the class file.
 code attribute is used when both java file and html file are locate the same directory, but codebase attribute
is used where are java file and html file are placed in different directory.
 codebase attribute is used to indicate the path of class file.
HSPACE AND VSPACE: hspace and vspace attributes are specify the horizontal and vertical space
between the applet and text, hspace controlled the space from the left and right side but vspace controlled the
space from up and bottom of an applet.
ALIGN: Its attribute specify the alignment of an applet.
ALT: It specify the AlterNet text to be display if the browser does not support the applet.

Applet Life Cycle: The life cycle of an applet describe the sequences of the stages there are four stages of
an applet life cycle.
1. Initial of an Applet
2. Starting of an Applet
3. Stopping of an Applet
4. Destroy of an Applet
1. Initial of an Applet:
The init method is used for initiation of an Applet. this is the first function to be execute.
2.Starting of an Applet: the start method is called to start the execution of an applet.this function always
called after the init function or when an applet received the focus.
3.Stopping of an Applet: the stop method suspend the execution of an Applet, This function always called
when an Applet loses the Focus.
4.Destroy the Applet: the destroyed method is called when applet is destroy.
 init and destroyed method always called only one in the life cycle of an Applet.

Manish Kumar([email protected])
init( )

Initial Applet When an applet


opened for the first
time or re opened
start( )

Starting Applet When an applet


received the focus.

stop( )

Stopping Applet
When an applet
looses the focus.
destroy( )

Destroyed Applet When an applet


destroyed.

import java.applet.Applet; /*<applet code="prg4.class" height=100 width=450>


import java.awt.*; </applet>
public class prg4 extends Applet */
{ }
String out;
public void init()
{
setBackground(Color.blue);
setForeground(Color.yellow);
System.out.println("init");
out="init->";
}
public void start()
{
System.out.println("Start");
out+="start->";
}
public void stop()
{
System.out.println("Stop");
}
public void destroy()
{
System.out.println("Destroy");
}
public void paint(Graphics g)
{
System.out.println("Paint");
out+="paint->";
g.drawString(out,100,10);
}
Graphics Methods in Java
 Awt packages support various graphics method with the help of them we can draw the lines, arc, rectangle,
circle and polygon.
Drawing Lines Rectangle and Polygon:
1. Line:-
drawLine(int x1, int y1,int x2, int y2);
( x1, y1 are the argument of starting point and x2, y2 are the argument of ending points)
2. Rectangle:-
drawRect(int x, int y, int width, int length);
(Width and length arguments specify the dimension of a rectangle)
3.Polygon:-
drawPolygon(int x[], int y[], int num);
Arc Circle and Oval:
1. Arc:
drawArc(int x, int y, int width, int height, int start angle, int stop angle );
2. Oval:
drawOval(int x, int y, int width, int height );

Example:-
import java.awt.*; import java.awt.*;
import java.applet.*; import java.applet.*;
public class prg6 extends Applet public class prg5 extends Applet
{ {
public void paint(Graphics m) public void paint(Graphics m)
{ {
m.drawLine(120,40,20,100); m.drawLine(120,40,20,100);
m.drawLine(120,40,220,100); m.drawLine(120,40,220,100);
m.drawRect(20,100,200,180); m.drawRect(20,100,200,180);
int x[]={100,140,170,140,100,60,100}; int x[]={100,140,170,140,100,60,100};
int y[]={150,150,200,250,250,200,150}; int y[]={150,150,200,250,250,200,150};
int n=7; int n=7;
m.drawPolygon(x, y, n); m.drawPolygon(x, y, n);
m.drawOval(100,60,30,30); }
m.drawLine(310,120,310,280); /*
m.drawLine(340,120,340,280); <applet code="prg5"height=300
m.drawArc(280,80,150,150,90,120); width=300>
m.drawArc(220,80,150,150,90,-120); </applet>
} */
/* }
<applet code="prg6"height=350
width=450>
</applet>
*/
}

Manish Kumar([email protected])
Example of Smiley face--
import java.awt.*;
import java.applet.*;
public class smile extends Applet
{
public void paint (Graphics g)
{
//g.drawLine(50,50,10,100);
g.fillArc(175,250,100,100,0,-180);
//g.drawArc(280,80,150,150,90,120);
g.drawOval(0,0,450,450);
g.fillOval(85,112,60,60);
g.fillOval(300,112,60,60);
g.drawLine(225,143,225,250);
}
/*
<applet code="smile.class" width=300 height=300 >
</applet>
*/
}
Example of Image loader in an Applet.:-
import javax.swing.*;
public class gif extends JApplet
{
JPanel p;
JLabel l;
public void init()
{
p=new JPanel();
add(p);
ImageIcon i=new ImageIcon("img.gif");
l=new JLabel(i);
p.add(l);
}
/*
<applet code="gif.class"width="500"height="500">
</applet>
*/
}

Awt control Component


We can create many components with the help of the awt packages
1. Text files: with the help of text file component, we can accept the single line
2. Text Area: with the help of that we can accept multiple line.
3. List: with the help of list component we can add the multiple items.
4. Check Box: it always exists in dual static.
5. Button  it is used for making the button.
Swing Component
It is the extension of awt Components, it provides two advantages over the awt components
1. Cross Platform Support
2. Swing components can be Customized (for example we can add tool tip to a button control.)
In swing there are three types of components
1. Top level components
2. Intermediate components
3. Atomic components
Swing component are developed by java foundation classes (JFC).
Swing component are provides the PLAF (play look and feel) functionality to our class.
It is also provides drag and drop functionality.
There are some examples of swing components are given below:-
import javax.swing.*; import javax.swing.*;
public class cust public class cust1
{ {
JFrame f; JFrame f;
JPanel p; JPanel p;
JComboBox c; JLabel l;
public static void main(String arg[]) JTextField t;
{ public static void main(String arg[])
cust cu = new cust(); {
} cust1 cu = new cust1();
public cust() }
{ public cust1()
f=new JFrame("Name"); {
p=new JPanel(); f=new JFrame("Name");
f.add(p); p=new JPanel();
String f.add(p);
man[]={"Executive","Standard","i....la"}; l=new JLabel("Customer Name");
c=new JComboBox(man); t=new JTextField(30);
p.add(c); p.add(l);
f.setSize(300,300); p.add(t);
f.setVisible(true); f.setSize(300,300);
}} f.setVisible(true);
}}
Customer Registration form:-
import javax.swing.*; Example Image loader in frame:-
public class customer
import javax.swing.*;
{
public class gif
JFrame f;
{
JPanel p;
JFrame f;
JLabel l;
JPanel p;
JTextField t;
JLabel l;
public static void main(String arg[])
public static void main(String []m)
{
{
customer cu = new customer();
gif g=new gif();
}
}
public customer()
public gif()
{
{f=new JFrame("Welcome Image");
f=new JFrame("Reg form");
f.setSize(475,375);
p=new JPanel();
p=new JPanel();
f.add(p);
f.add(p);
JTextArea textArea = new JTextArea(3,3);
ImageIcon i=new ImageIcon("img.gif");
JScrollPane scrollPane=new
l=new JLabel(i);
JScrollPane(textArea);
p.add(l);
l=new JLabel("Customer Name");
f.setVisible(true);
t=new JTextField(30);
}
p.add(l);
}
p.add(t);
p.add(scrollPane);
f.setSize(300,300);
f.setVisible(true); Manish Kumar([email protected])
}}
Layout Management
 Layout management is a process in that we insure the size and position of a component in a container.
 or It is a process in that we place our components in an organized manner.
Layout Manager:- it are the special object with the help of that we perform the management.
Java offers some layout managers classes these are follows
1. FlowLayout 2. GridLayout 3. BorderLayout 4. CardLayout 5. GridBagLayout
All the above classes belongs to the java.awt packages.
1. Flow Layout:-
 With the help of the flow layout we place our components form left to right in a container.
 It is the default layout for an applet and for a panel it means if we do not use the any layout in an applet or in
a panel that time they are automatic using flow layout
Constructor of FlowLayout:-
1. FlowLayout ();
2. FlowLayout (int align);
3. FlowLayout (int align,int hgap, int vgap);

Examples of flow layout:-


import java.awt.*;
import java.applet.*;
public class flow extends Applet
{
public void init()
{
FlowLayout f=new FlowLayout ();
setLayout(f);
Button a,b;
a=new Button("Add");
b=new Button("Sub");
add(a);
add(b);
add(new Button("Multi"));
}
/*
<applet code="flow" width=200 height=200>
</applet>
*/
}

2. Grid Layout:-
 With the help of Grid Layout we can place our components in a rectangle Grid. It means it can we place our
components in row and column.
 In the Grid Layout row is fixed and column are flexible, it means if we are having the more components
comparatively form the grid in that case column automatically extends.
Constructor of GridLayout:-
4. GridLayout();
5. GridLayout(int row, int column);
6. GridLayout(int row, int column,int hgap, int vgap);
Examples of Grid Layout:-
import java.awt.*; add(new Button("red"));
import java.applet.*; add(new Button("bi8"));
public class grid extends Applet add(new Button("yellow"));
{ add(new Button("clay"));
public void init() }/*<applet code="grid" width=200
{ height=200>
GridLayout g=new GridLayout (2,2,3,3); </applet>
setLayout(g); */}
add(new Button("red")); }
3.Border Layout:-
 With the help of border layout class we can place our components in the direction.
 There are five directions specified for the Border Layout EAST, WEST, NORTH, SOUTH, CENTER.
 Border Layout are the default layout in the Frame component.
 We have the java components in the Border Layout classes. They are follows…
1. BorderLayout.NORTH, 2. BorderLayout.SOUTH 3. BorderLayout.EAST 4. BorderLayout.WEST
5. BorderLayout.CENTER.
 When we do not specify the direction in the border layout that time it automatically use the center directions.
Example of Border Layout:-
import java.awt.*;
import java.applet.*;
public class border extends Applet
{
public void init()
{
BorderLayout b1=new BorderLayout();
Panel p=new Panel();
add(p);
p.setLayout(b1);
p.add(new Button("east"),BorderLayout.EAST);
p.add(new Button("west"),BorderLayout.WEST);
p.add(new Button("south"),BorderLayout.SOUTH);
p.add(new Button("north"),BorderLayout.NORTH);
p.add(new Button("center"),BorderLayout.CENTER);
}
/*
<applet code="border" width=300 height=300>
</applet>*/
}

CardLayout:-
 With the help of card layout manager we can arrange our components one behind another.
Example of card layout:-
import java.awt.*;
import java.applet.*;
public class card extends Applet
{
public void init()
{
CardLayout c=new CardLayout();
Panel p=new Panel();
add(p);
p.setLayout(c);
p.add("b",new Button("east"));
p.add("b",new Button("west"));
p.add("b",new Button("south"));
}
/*
<applet code="card" width=300 height=300>
</applet>*/
}

Grid Bag Layout:-


 With the help of Grid Bag Layout Manger classes we can specify the direction and the size of components.
 For the Grid Bag Layout manger we used two classes
1. GridBagLayout classes
2. GridBagConstrints
Example of Grid Bag Layout:-
import java.awt.*;
import javax.swing.*;
public class gridbag extends JApplet
{
JPanel p;
JLabel l;
JTextField t;
GridBagLayout g;
GridBagConstraints gb;
public void init()
{
g=new GridBagLayout();
gb=new GridBagConstraints();
p=new JPanel();
add(p);
p.setLayout(g);
l=new JLabel("Customer Name");
t=new JTextField(30);
gb.anchor=GridBagConstraints.NORTHWEST;
gb.gridx=1;
gb.gridy=5;
g.setConstraints(l,gb);
p.add(l);
gb.anchor=GridBagConstraints.NORTHWEST;
gb.gridx=5;
gb.gridy=5;
g.setConstraints(t,gb);
p.add(t);
}
/*
<applet code="gridbag" width=300 height=300>
</applet>*/
}

Event Handling
 Event is an object that describes a changes of status in a sources components.
 The source components can be any element from the GUI.
 For event handling in java we would use one packages that is java.awt.event.
Source of the event:-
 An Event is an object that generates an event.
 An Event source registers some listener which received the notification about a specific type of the event
that is generated by the event source.
Action Listener:-
 Action Listener is the pre define interface it comes in the java.awt.event packages.
 This interface works as an event listener it has got only one function that is action performed.
Example of action listener:-

Manish Kumar([email protected])
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class button extends Applet implements ActionListener
{
Button b;
public void init()
{
b= new Button ("Clicked Me");
add("Center",b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
b.setLabel("Button Clicked");
}
/*
<Applet code="button" width=100 height=100>
</Applet>
*/
}

Key Listener:-
 Key Listener is the pre define interface, it comes in the java.awt.event Packages it has got three function
KeyPressed, KeyReleased, KeyTyped.
 getkeycode is the pre define function with the help of that we retrieve the sky values of the particular key.
Example of KeyListener:-
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class key extends Applet implements KeyListener
{
TextField t,t1;
public void init()
{
t=new TextField();
t1=new TextField();
t.addKeyListener(this);
add(t);
add(t1);
}
public void keyPressed(KeyEvent ae)
{
int a=ae.getKeyCode();
t1.setText(Integer.toString(a));
}
public void keyReleased(KeyEvent ae)
{
}
public void keyTyped(KeyEvent ae)
{
}
/*
<Applet code="key" width=200 height=200>
</Applet>
*/ }
MouseMotionListener:-
 MouseMotionListener is a pre define interface it comes in the java.awt.event packages.
 It got two function 1.mouseMoved 2. mouseDragged.
getX and getY are the pre define function of the MouseEvent class with the help of it we retrieve the x and y
coordinate, showStatus is the pre define function of the applet class with the help of that we visualized the
status bar of an applet.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class mouse extends Applet implements MouseMotionListener
{
public void init()
{
addMouseMotionListener(this);
}
public void mouseMoved(MouseEvent ae)
{
int a=ae.getX();
int b=ae.getY();
showStatus(a+","+b);
}
public void mouseDragged (MouseEvent ae)
{
}
/*
<Applet code="mouse" width=200 height=200>
</Applet>
*/
}

MouseListener Interface:-
 MouseListener is a pre define interface it comes in the java.awt.event packages.
 It got the five function 1.mousePrassed 2.mouseReleased 3.mouseClicked 4.mouseEntered 5.mouseExited.
 Repaint is the pre define function of the applet class it clear the screen then called the paint function.
Example of MouseListener:-
import java.awt.*; c=ae.getX();
import java.awt.event.*; d=ae.getY();
import java.applet.*; repaint();
public class mouse1 extends Applet implements }
MouseListener public void mousePressed(MouseEvent ae)
{ {
int c,d; }
public void init() public void mouseEntered (MouseEvent ae)
{ {
int c=30; }
int d=40; public void mouseExited (MouseEvent ae)
addMouseListener(this); {
} }
public void paint (Graphics g) public void mouseReleased (MouseEvent ae)
{ {
g.drawString(" *****",c,d); }
} /*
public void mouseClicked (MouseEvent ae) <Applet code="mouse1" width=200 height=200>
{ </Applet>*/
c=ae.getX(); }
Adapter classes:-
In java if a class is implementing an interface in that case we have to define the body of all function in a
class.
 If we using the adapter class inside of the interface in that case there is no need to define the body of the all
function because the definition of the function is already define in the adapter class.
KeyListener  KeyAdapter
MouseMotionListener  MouseMotionAdapter
MouseListener  MouseAdapter
WindowListener  WindowAdapter

 ActionListener have no adapter class because it have only one function.


Example of adapter class:-
import java.awt.*; import java.awt.*;
import java.awt.event.*; import java.awt.event.*;
public class wind extends Frame public class adapter extends Frame
{ {
public wind() TextField t;
{ adapter()
aa d=new aa(); {
addWindowListener(d); setLayout(new GridLayout(3,2));
} t=new TextField(20);
public static void main(String []m) a q=new a();
{ Button b=new Button("OK");
windowev w=new windowev(); b.addMouseMotionListener(q);
w.setSize(300,400); add(t);
w.setVisible(true); add(b);
} }
} class a extends MouseMotionAdapter
class aa extends WindowAdapter {
{ public void mouseMoved(MouseEvent me)
public void windowClosing(WindowEvent ae) {
{ String z="manish";
System.exit(1); t.setText(z);
} }
} }
public static void main(String []m)
{
adapter w=new adapter();
w.setSize(300,400);
w.setVisible(true);
}
}

JAVA Packages
* A packages is the collection of class and interfaces.
* Normally a packages is treaded as a folder.
* Packages is categorized in two category.
1. Predefine packages(java API packages). (Application programming interface)
2. User define packages.
* There are various packages some of them are as follows.
1. java.lang :- this package is default package it means if we do not import any package. That time java.lang
package automatically imported.
 There are various classes in the java.lang package such as class, object, System.
2. java.util:- this packages provides some utility classes such as dates, calendar, and some collection
fremwork related classes ArrayList, LinkList, etc .

3. java.io:- this package is related with input and output stream, with the help of that we perform the file
handling operation.

4. java.awt:- with the help of this package we provide some class to implement the GUI interface such as
button, textbox, menus, etc .

5. java.lang package:-
* object class  it is the predefine class it comes in the java.lang package.
 This is mother of the all classes, it means all classes are inherited from the object class.
 There are various methods in the object classes
1. toString :- with the help of this function we convert the thing into string, the println always call the toString
function. Where we call it or not call it.
SYNTAX:- Public String to String();
class my
{
public String toString()
{
return"ram is shayam.";
}
public static void main(String []m)
{
my o=new my();
System.out.println(o);
}
}

Wait, Notify, NotifyAll, Equal, hasCode, Finalize.


2. class class :- this class also belong the java.lang packages with the help of this class we load some classes at
run time.
3. System class:- with the help of this class we provide some standard interface for input, output, err device. It
has got some variable in, out, err to represent the input, output, error device.
4. Wrapper class:- with the help of this class we represent the primitive data types such as int, char, double as
object.
 it means wrapper class provides the class functionality to the data type some wrapper class are as follows.
Data type Wrapper class
byte Byte
short Short
int Int
long Long
boolean Boolean
char Character
class wrapper
{
public static void main(String []m)
{
int a=Integer.parseInt(m[0]);
int b=Integer.parseInt(m[1]);
int r=a+b;
System.out.println("the sum is "+r);
} Manish Kumar([email protected])
}
Math class:- math is the pre define class it comes in the java.lang packages with the help of that we can
performed the number operation such as calculations the squire root, absolute value of a number, maximum and
minimum value and etc.

 There are various methods in the math class some of them are as follows-
1. abs() :- This function except a value and return the absolute value of that.
Syntax:- public static double abs(double a)
public static float abs(int a)
public static Int abs(int a)

2. ceil() :- this function returns the smallest double value up the next higher integer.
Syntax:- public static double ceil(double a)

3. Floor() :- this function returns the largest double value of the next smaller integer.
4. max() :- this function excepts two arguments and return the large of the two value but in this function two
arguments must be of same data type.
Syntax:-
public static Int max(int a, int b)
public static double max(double a, double b)

5. min() :- the functionality of this function is same as the Max function, but this function return the
minimum value out of two.
6. sqrt() :- this function accept single argument as a parameter and return the positive squire root of the
parameter.
Syntax:- public static double sqrt(double a)
Some examples:-
class absdemo class ceildemo
{ {
public static void main(String []m) public static void main(String []m)
{ {
int a=-5,absval; double v1=9.0,cv1;
absval=Math.abs(a); double v2=3.2,cv2;
System.out.println(absval); double v3=-7.3,cv3;
} cv1=Math.ceil(v1);
} cv2=Math.ceil(v2);
cv3=Math.ceil(v3);
double floor1=Math.floor(v1);
class maxdemo
double floor2=Math.floor(v2);
{
double floor3=Math.floor(v3);
public static void main(String []m)
System.out.println(cv1);
{
System.out.println(cv2);
int v=19,v1=54,max,min;
System.out.println(cv3);
max=Math.max(v,v1);
System.out.println(floor1);
min=Math.min(v,v1);
System.out.println(floor2);
System.out.println(min);
System.out.println(floor3);
System.out.println(max);
}
}
}
}

class sqrtdemo
{
public static void main(String []m)
{
System.out.println(Math.sqrt(9));
System.out.println(Math.round(7.5));
}
} Manish Kumar([email protected])
String class:- It is the pre define class it comes in the java.lang package. Its object is immutable it means once
an object is created of that class it can’t be changed.
 it means we can not changed the existing value.
//immutable demo
class immutabledemo
{
public static void main(String []m)
{
String x="JAVA";
x.concat(" advavance");
System.out.println(x);
}
}

There are various method in the string class some commonly used methods are as following –
1. charAt() :- it is a predefine function used for retrieve a particular character on the specified index.
Syntax :- public char charAt (Int Index)

2. conCat() :- it is used for add a string with the string.


Syntax :- public string concat(String S);

3. length() :- it is used for find out the no.of the elements in a string.
Syntax:- public Int Length()

4. replace() :- it is used for replace the old character with the new one.
Syntax :- public char replace(Char old,Char new)

5. substring() :- it is used retrieve a part from the string.


Syntax :- public String substring(Int begin)
public String substring(Int begin, Int end)

6.toLowerCase() :- public String toLowerCase()

7.toUpperCase() :- public String toUpperCase()

8. trim() :- it is used for remove the leading and trilling spaces from the string.

public static void main(String []m)


{
String z="manish kumar";
String z1 =new String("maDan Kumar");
System.out.println(z1.toUpperCase());
System.out.println(z1.toLowerCase());
System.out.println(z1.length());
System.out.println(z1.charAt(0));
System.out.println(z1.indexOf('m'));
System.out.println(z1.substring(2));
System.out.println(z1.substring(2,4));
System.out.println(z1.equals(z));
System.out.println(z1.trim());
}
}

Manish Kumar([email protected])
String Buffers and String Builder class :-
 String object are immutable but StringBuffer and string Builder classes object are mutable it means we can
do some changes in the exixting value.
 If we doing the changes in a string again and again that times we should use string buffer and string buildr
classes instead of string class.

String buffers Vs String Builder :-


 string builder is a class that is added from jdk 1.5.
 string builder & string buffer are the similar classes but there is a major difference b/w the string buffers and
string builder.
1. string buffer is a thread safe classes but string builder is not.
2. thread safe classes means all function of a class are specified synchronized.
3. string builder class run faster if we compare with the string buffer because string builder class is not
thread snap.
class buff
{
public static void main(String []m)
{
String x="xyz";
x.concat("abc");
System.out.println("X="+x);
StringBuffer sb=new StringBuffer("xyz");
sb.append("abc");
System.out.println("SB="+sb);
}
}

Commonly used method in the string buffer and string builder class—
1. append() :- it is used for add a string after the string.

2. delete () :-
Syntax :- public builder delete(int start, int end);

3. insert() :-
Syntax :- public String Builder insert(int start, string)

4. reverse ():-
Syntax :- public synchronized String Buffer reverse ()

User Define Packages:- we can create our own packages also with the help of the package keyword.
 every package as treat as a folder, that is our packages and folder name must be same.

Steps to create the user define packages.


1. make a folder and rename it.
2. then make a file in notepad with java extension.
3. then save it in the folder name.
4. compile it.
5. for using your packages make a program and save in the same drive where package are saved.
6. then compile it and run it.
Examples:

Manish Kumar([email protected])
package hellopackages; import hellopackages.*;
public class hello class mypack extends hello
{ {
public void disp() public static void main(String []m)
{ {
System.out.println("i make this new mypack().disp();
packages"); }
} }
}

Some command for packages:-


javac –d e: hello.java
set classpath=%classpath%;e:\;

♥ File Handling ♥
 It is the pre define class it comes into java.io package, it is used for create a file and folder and can access
the property of a file or folder such as file permission, date and time, path of a directory (folder).
Example of file handling operation:-
import java.io.*; import java.io.*;
class fh class fh1
{ {
public static void main(String []m) public static void main(String []m)
{ {
File file =new File("ram.txt"); try
} {
} boolean newFile=false;
/* File file =new File("d:\\ram.txt");
File file =new File("ram.txt"); System.out.println(file.exists());
It is not used for making file. newFile =file.createNewFile();
*/ System.out.println(newFile);
System.out.println(file.exists());
File file =new File("ram.txt"); System.out.println(file.getName());
This line is doing two jobs. System.out.println(file.getParent());
1. it open the file in the memory(if file already System.out.println(file.getPath());
In the drive). }
2. if file is not there it just create a logical. catch(Exception e){}
exists() :- it is pre define function used for check}
whether file is there or not. It is always return }
the boolean type value.

createNewFile() :- it is the pre define function of file class used for creating new file if file is not there.
 if file is already there in that case it would not create the file.
 it is also return the Boolean type value.
mkdir(): it is predefine function of the file class, it is used for create a folder.

read() : it is the predefine function of the input stream class with the help of that we can accept only on
character at a time

FileInputStream () : it is pre define class it comes in the java.io package it is used for read the data from the
file.

FileOutputStream () : it is pre define class it comes in the java.io package it does two jobs.
1. It creates a file if file is not already there.
2. It writes the data in file.
import java.io.*; import java.io.*;
class fh2 public class fh3
{ {
public static void main(String []m) public static void main(String []m)throws
{ IOException
try {
{ try
File myDir=new File("man");; {
myDir.mkdir(); int b=System.in.read();
File myFile=new File(myDir,"man.txt"); System.out.println((char)b);
myFile.createNewFile(); }
} catch(Exception e)
catch(Exception e){} {
} System.out.println("this is the input out
} exception");
}}}

import java.io.*; import java.io.*;


public class fh4 public class fh5
{ {
public static void main(String []m)throws public static void main(String []m)throws
IOException IOException
{ {
byte buffer[]=new byte[80]; FileInputStream f=new
System.out.println("type the text to be FileInputStream("c:\\ddd.txt");
displayed"); int b;
try b=f.read();
{ while(b!=-1)
System.in.read(buffer); {
} System.out.println((char)b);
catch(Exception e) b=f.read();
{ }
System.out.println("Exception:"+e.toString()); f.close();
} }
String str=new String(buffer); }
System.out.println(str);
}}

import java.io.*; b=fi.read();


public class fh6 }
{ fi.close();
public static void main(String []m)throws fo.close();
IOException }
{ }
FileInputStream fi=new FileInputStream("c:\\
ddd.txt");
FileOutputStream fo=new
FileOutputStream("c:\\d.txt");
int b;
b=fi.read();
while(b!=-1)
{
fo.write(b); Manish Kumar([email protected])
b=fi.read();
 Thread 
A thread is a define as the execution of a program.
A process that is made of one thread is known as single thread process.
 If a process that create two or more thread is called multithreading process.
 Multitasking is the ability to execute more than one task at the same time.
Multitasking can be divided into two category
1. Process based multitasking
2. Thread based multitasking
The thread class:
This class belong to java.lang package it is used to create a thread, there are various method in the thread class
commonly used method are as follows.
start() : it is used for start a thread by called the run function.
Note: we call the start and start called the run method.
get Priority() : return the priority of the thread.
set Priority() : reverse
isAlive() : we check whether the thread are alive or not.
getName() : return the name of the thread.

 The first thread to be executed in a multithreading process is called the main thread.
The main thread is created automatically on the startup when the java program execute.
 It means main thread automatic created
Thread  worker, run work
We can do the multithreading by two ways.
 By inheriting the thread class or by implementing the runnable interface.
 but in java multiple inheritance is not allowed, hence most of time we use the runnable interface.
Runnable is pre define interface it comes in the java.lang package it has got only one function that is run().
Examples:
2
class th implements Runnable class th1 implements Runnable
{ {
public void run() public void run()
{ {
for(int x=1;x<6;x++) System.out.println("name runnable running");
{ System.out.println("run by
System.out.println("SCJP Test"); "+Thread.currentThread().getName());
}}} }}
public class TestThreads public class TestThreads1
{ {
public static void main(String []m) public static void main(String []m)
{ {
th r=new th(); th1 r=new th1();
Thread t=new Thread(r); Thread t=new Thread(r);
t.start(); t.setName("manish");
} t.start();
} }}

3.
public class mm
{
public static void main(String []m)
{
System.out.println("thread is "+Thread.currentThread().getName());
}
}
4.
class th2 implements Runnable
{
public void run()
{
for(int x=1;x<4;x++)
{
System.out.println("Run by"+Thread.currentThread().getName());
try
{
Thread.sleep(1000);
}
catch(Exception e) {}
}}}
public class TestThreads2
{
public static void main(String []m)
{
th2 r=new th2();
Thread t=new Thread(r);
t.setName("Fred");
Thread t1=new Thread(r);
t1.setName("Raju");
Thread t2=new Thread(r);
t2.setName("Rancho");
t.start();
t1.start();
t2.start();
}}

5.
import java.lang.*;
class thread3 extends Thread
{
thread3()
{
start();
}
public void run()
{
for(int i=0;i<50;i++)
{
System.out.print("\tchild"+i);
}}
public static void main(String []m)
{
thread3 r=new thread3();
for(int j=0;j<50;j++)
{
System.out.print("\tmain"+j);
}}}

Manish Kumar([email protected])
Life Cycle of a Thread
There are various state in the life cycle of a thread.

New: When we create an object of the thread class that state is known as new state(unstated state).

Runnable state: When we call the start function on the thread that state is known as the runnable state.

Running state: When the thread is inside the run function that state is known as running state.

Not Runnable: When we call the sleep function or wait function on the thread that state is known as the not
runnable state.

Terminated or Dead: When the job is finished of a thread that state is known as Dead state.

Sleep/wait/ Not runnable State


block

New
Stat Runnable State Running State Dead State
e

Manish Kumar([email protected])
Website: http://gnnetmanish1.cetpa.in

You might also like