.Java 2 Standard Edition: Easy To Read The Programming Code. Easy Maintainable. Code Is More Flexible
.Java 2 Standard Edition: Easy To Read The Programming Code. Easy Maintainable. Code Is More Flexible
.Java 2 Standard Edition: Easy To Read The Programming Code. Easy Maintainable. Code Is More Flexible
Note:
Difference between project and products…….
Project is basically for specific client but products are common for all.
JAVA
Class
CAR
NENO Swift
Object
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.
2. Multiple Inheritance: In this heritance a sub class is inherited from more one super class
Super
SuperClass
Class(Parent1)
(Parent) Super Class (Parent2)
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 javaopen cmdnow 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.
Function
Access Specifier or
Access modifier
Predefine Class:
In java all predefine Class always starts with the Capital Character. There are 3500 Classes.
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
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.
Operators in Java
1. Earthmatics operator:--(+, -, *, /, %)
+ use for addition.
- Use for subtraction.
* use for multiply.
/ Always occupy the quotient.
% always occupies the reminder.
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
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
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;
}}}
Hello.java
Hello.class
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.
//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:
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
//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();
}
}
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);
}
}
}
//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);
}
}
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( )
stop( )
Stopping Applet
When an applet
looses the focus.
destroy( )
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>
*/
}
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>*/
}
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
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);
}
}
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)
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)
8. trim() :- it is used for remove the leading and trilling spaces from the string.
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.
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.
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"); }
} }
}
♥ 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");
}}}
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.
New
Stat Runnable State Running State Dead State
e
Manish Kumar([email protected])
Website: http://gnnetmanish1.cetpa.in