Friday 21 April 2017

Java Notes

=============================================================
Java Features
=============================================================

Simple
Object-Oriented
Distributed
Robust
Secure
System Independence
Portability
Interpreted
High Performance
Multithreaded
Scalability
Dynamic

Simple:
----------

When java is developed, they wanted it to be simple because it has to work on  electronic devices, where

less memory is available.

 The difficult concepts of C and C++ omitted in java. eg: Pointers which difficult for both learners and

programmers.

The Syntaxes of C and C++.

Object-Oriented:
-----------------------

Java is an object oriented programming language. It uses objects and classes.  It provides reusablility.

Distributed:
----------------

Information is distributed on various computers on a network.  Using java we can write programs, which

capture information and distribute it to the clients.  Because java can handle the protocols like TCP/IP

and UDP.

Robust:
----------

Robust means strong.  Java programs are strong and they don't crash easily like a C or C++ program.  It

has excellent feature i.e. Exception Handling.  An exception is an error that occurs at runtime.

Another feature is memory management.We need not allocate or deallocate memory in Java.  Everything

will be taken care of by JVM only. In C and C++ we have to allocate to dellocate memory.

Secure:
----------

Security problems like evedropping, tampering, impersonation and virus threats can be eliminated or

minimized by using java on internet.

System Independence:

Java's byte code is not machine dependent.  It can be run on any machine with any processor and any

operating system.

Portability:
----------------

If a program yields the same result on every machine, then that program is called portable.  Java

programs are portable.  This is the result of Java's Sysem independence nature.

Interpreted:
-----------------

Java programs are compiled to generate the byte code.  if we take any other language, only an interpreter

or a compiler is used to execute the programs.  But in java, we use both compiler and interpreter for the

execution.

High Performance:
-------------------------

The problem with intepreter inside the JVM is that is slow.  Because of this, java programs used to run

slow.  To overcome this problem, along with the interpreter, JavaSoft people have introduced JIT(Just In

Time) compiler, which enhances the speed of execution.  So in JVM, both interpreter and JIT compiler

work together to run the program.

Multithread:
------------------

A thread represents an individual process to execute a group of statements.  JVM uses several threads to

execute different blocks of code.  Creating multiple threads is called multithreaded.

Scalability:
--------------

Java platform can be implemented on a wide range of computers with varying levels of resources - from

embedded divices to mainframe computers.  This is possible because java is compact and platform

independent.

Dynamic:
---------------

Before the development of java, only static text is used to be displayed in the browser.  But java provides

dynamically interacting programs on Internet.







Operators in Java
================









Example 1:
---------------
class A
{
public static void main(String args[])
{
System.out.println("THis is First Program..");
}
}
Example 2:
---------------
class A5
{
public static void main(String args[])
{
int a=10;
System.out.println("a...."+a);
}
}


Example 3:
---------------
class A
{
public static void main(String args[])
{
int x=10;
int y=20;
int z=x+y;
System.out.println("The Sum is "+z);
}
}

Example 4:
---------------
/*Using Command Line Arguments */

class A
{
public static void main(String args[])
{
int x,y,z;
x=Integer.parseInt(args[0]);
y=Integer.parseInt(args[1]);
z=x+y;
System.out.println("Your First Number is "+ x);
System.out.println("Your Second Number is "+ y);
System.out.println("The Sum is "+z);

}
}

javac A.java
java A 10 20

Example 5:
---------------
//Using Scanner Class

import java.util.*;
class A2
{
public static void main(String args[])
{
Scanner s= new Scanner(System.in);
int x,y,z;
System.out.print("Enter a Number to x: ");
x=s.nextInt();
System.out.print("Enter a Number to y: ");
y=s.nextInt();
z=x+y;
System.out.println("The Sum of " + x + " and " + y+" is "+z);
}
}


Example 6:
---------------
//Using BufferedReader Class

import java.io.*;
class A3
{
public static void main(String args[]) throws Exception
{
BufferedReader B=new BufferedReader(new InputStreamReader(System.in));
int num;
System.out.print("Enter a number.... ");
num = Integer.parseInt(B.readLine());
System.out.println("U entered....."+num);
System.out.printf("U entered.....%d",num);
}
}
Example 7:
---------------
//To display System Date

import java.util.Date;

class A4
{
public static void main(String args[])
{
Date today=new Date();
System.out.println("Today's Date is " +today);
}
}

Example 8:
---------------

class A6
{
public static void main(String args[])
{
int empNumber;
float salary;
char gender='M';
double shareBalence=456790.087;
boolean ownVehicle=false;

empNumber=101;
salary = 6789.50f;

System.out.println("Emp Number :"+empNumber);
System.out.println("Salary :"+salary);
System.out.println("Gender :"+gender);
System.out.println("ShareBalence :"+shareBalence);
System.out.println("owns vehicle :"+ownVehicle);
}
}


Example 9:
---------------
//If Condition

class A1
{
public static void main(String[] args)
{
int x=10,y=20;

if(x>y)
{
System.out.println("x is Greater");
}
else
{
System.out.println("y is Greater");
}
}
}

Example 10:
---------------

class A2
{
public static void main(String[] args)
{
int x,y,z;

x=Integer.parseInt(args[0]);
y=Integer.parseInt(args[1]);
z=Integer.parseInt(args[2]);

if(x>y && x>z)
{
System.out.println(x + " is greater..");
}
else if(y>z)
{
System.out.println(y + " is greater..");
}
else
{
System.out.println(z + " is greater..");
}
}
}

javac A2.java
java A2 10 20 30

Example 11:
---------------
import java.util.*;

class A3
{
public static void main(String[] args)
{
Scanner S=new Scanner(System.in);

int x,y,z;
System.out.print("Enter Value to x: ");
x=S.nextInt();
System.out.print("Enter Value to y: ");
y=S.nextInt();
System.out.print("Enter Value to z: ");
z=S.nextInt();

if(x>y && x>z)
{
System.out.println(x + " is greater..");
}
else if(y>z)
{
System.out.println(y + " is greater..");
}
else
{
System.out.println(z + " is greater..");
}
}
}

Example 12:
---------------
class A4
{
public static void main(String[] args)
{
int x=1;

while(x<=10)
{
System.out.println(x);
x++;
}
}
}
Example 13:
---------------
class A5
{
public static void main(String args[])
{
int i=10;

do
{
System.out.println(i);
i--;
}
while(i>=1);
}
}

Example 14:
---------------
class A6
{
public static void main(String[] ar)
{
for(int i=2;i<=20;i=i+2)
{
System.out.println(i);
}
}
}
Example 15:
---------------
class A10
{
public static void main( String args[])
{
char color='a';

switch(color)
{
case 'r':
System.out.println("Red Color..");
break;
case 'g':
System.out.println("Green Color..");
break;
case 'b':
System.out.println("Blue Color..");
break;
default:
System.out.println("Invalid Color..");
}
}
}


Example 16:
---------------

//Using Enhanced for loop

class A7
{
public static void main(String args[])
{
int arr[]={10,20,30,50,60,89,34,56,67,67,45};

for(int i : arr)
{
System.out.println(i);
}
}
}

Example 17:
---------------
class A8
{
public static void main(String arg[])
{
String arr[]={"Sunitha","Scott","Martin","Smith"};

for(String str : arr)
{
System.out.println(str);
}
}
}

Example 18:
---------------
class A9
{
public static void main(String args[])
{
char ch[]={'A','P','T','E','C','H'};

for(char c : ch)
{
System.out.println(c);
}


}
}
Arrays
=================
Purpose of Array:
----------------------
Consider a program that stores the names of 100 students. To store the names, the programmer

would create 100 varibles of type string.  In such situations, the programmer can create an array for

storing the 100 names in single variable.

Difinition of an Array:
----------------------------
Arrays are group of values of same datatype.  These values are stored in adjacent memory

locations, making it easier to access and manipulate them.  Each value is referred to as an element.  These

elements are accessed using index numbers that determine the position of the eleement in the array list.

syntax:
-----------
Datatype arrvar[]
Or
Datatype[] arrvar;

1.. Array variables are allocated memory on the stack.
2.In the second step we create the memory for the array elements with the new keyword using the below

syntax:

Arrvar=new datatype[width];

Ex:- a=new int[10];

In java, we don’t have pointers as the memory allocated to array will not refer to large extent.

The array elements are themselves allocated memory on the heap.

Unlike in c++, arrays in java are internally treated as objects.

Reading past the boundaries of an array generates an exception called
ArrayIndexOutOfBoundsException

Because arrays are internally treated as objects they have given  built in property called length which

returns the number of elements in the array

The array elements are implicitly assigned default values zeroes in case of numbers, false in case of

Booleans, null in case of characters and other objects.

Example 19:
---------------
//Arrays
class A11
{
public static void main(String args[])
{
int[] a={10,20,30,40,50};

for(int i=0;i<5;i++)
{
System.out.println(a[i]);
}
}
}

Example 20:
---------------
//Arrays
import java.util.*;

class A12
{
public static void main(String args[])
{
Scanner S=new Scanner(System.in);

int arr[]=new int[5];
System.out.println("Enter five values to an Array: ");

for(int i=0;i<5;i++)
{
arr[i]=S.nextInt();
}
System.out.println("Printing an Array\n----------------");
for(int i=0;i<5;i++)
{
System.out.println(arr[i]);
}
}
}


Example 21:
---------------
//Arrays
import java.io.*;

class  A13
{
public static void main(String arg[]) throws Exception
{
BufferedReader B=new BufferedReader(new InputStreamReader(System.in));

int a[]=new int[5];
int sum=0;
System.out.println("Enter Five Values to an Array :  ");

for(int i=0;i<5;i++)
{
a[i]=Integer.parseInt(B.readLine());
}
for(int i=0;i<5;i++)
{
sum=sum+a[i];
}
System.out.println("The Sum of an Array is "+sum);
}
}

Example 22:
---------------
//Arrays
import java.io.*;
class A14
{
public static void main(String a[]) throws IOException
{
BufferedReader B=new BufferedReader(new InputStreamReader(System.in));
String str[]=new String[5];
System.out.print("Enter any Name: ");
for(int i=0;i<5;i++)
{
str[i]=B.readLine();
}
System.out.println("\nThe names are \n");
for(int i=0;i<5;i++)
{
System.out.println(str[i]);
}
     }
}




Types of Arrays:
---------------------
1. Single-Dimensional Arrays
2. Multi-Dimensional Arrays


1. Single-Dimensional Arrays
----------------------------------------
The elements of a single-dimensional array are stored in a single row in the allocated memory.
Example 23:
---------------
//Arrays
class A15
{
public static void main(String args[])
{
char ch[]={'A','P','T','E','C','H'};

for(int i=0;i<6;i++)
{
System.out.print(ch[i]);

}
}
}

2. Multi-Dimensional Arrays
-----------------------------------------
Consider a scenario where we need to store the roll numbers of 50 students and their marks in

three exams.  Using a single-dimensional array, we require two separate arrays for storing rollnumbers

and marks.  However, using a multi-dimensional array, we just need one array to store both, roll numbers

as well as marks.

A multi-dimensional array allows you to store combination of values of a single type in two or

more dimensions.  The dimensions of the array are represented as rows and columns similar to the rows

and columns of a Microsoft Excel Sheet.

There are two types of multi-dimenstional arrays.  Those are
1. Rectangular Arrays
2. Jagged Arrays.

 1. Rectangular Array:
------------------------------
A rectangular array is multi-dimensional array where all the specified dimensions have

constant values.  A ractangular array will always have the same number of columns for  each row.

Example 25:
---------------
// Rectangular Array
class A17
{
public static void main(String args[])
{
int arr[][]=new int[4][5];
int i=0;

for(int row=0;row<4;row++)
{
for(int col=0;col<5;col++)
    {
    arr[row][col]=i;
       i++;
    }
}
for(int row=0;row<4;row++)
{
for(int col=0;col<5;col++)
  {
                  System.out.print(arr[row][col]+ "\t");
}
System.out.println();  
}
}
}

Jagged Array:
--------------------
A jagged array is a multidimensional array where one of the specified dimensions can have

varying sizes.  Jagged arrays can have unequal number of columns for each row.

Example 24:
------------------
//Jagged Arrray
class A16
{
public static void main(String args[])
{
String[][] companies=new String[3][];
companies[0]=new String[]{"Intel","AMD"};
companies[1]=new String[]{"IBM","Microsoft","Sun"};
companies[2]=new String[]{"HP","Canon","Lexmark","Epson"};
for(int row=0;row<companies.length;row++)
{
System.out.print("List of companies in group "+(row+1) + ":\t");
for(int col=0;col<companies[row].length;col++)
{
System.out.print(companies[row][col] + " ");
}
System.out.println();
}
}
}


=================================================
OBJECT ORIENTED PROGRAMMING SYSTEM
=================================================

OOPS:- Object Oriented Programming Language
---------------------------------------------------------------
It is very important  concept in Java  Language.  OOPS have three parts based on their process.

a.OOD:-Object Oriented Designing
b.OOA:-Object Oriented Approach
c.OOP:-Object Oriented Programming
The combination of above three parts are called "OOPS".

Above all process is used to develop any application systematically by following set of

predefined standards.  All the standards comes under "Unified Modiling Language"(UML)

a.Object Oriented Designing(OOD):-
---------------------------------------------
It stands for object oriented design.  It determines to develop the application by phasewise

designing of each module and each module will be designed later by following set of methods, principles

and applications.

b.Object Oriented Approach(OOA):-
----------------------------------------------
It follows the object oriented designing based on its (OOD) phase.

c.Object Oriented Programming(OOP):-
--------------------------------------------------
It determines the real implementation of program(coding) by following set of functions

libraries,header files and other technical tools by performing a suitable syntaxes.  Any real

implementation of the program in OOP which follows a standard structure of program.

In Java we have a standard structure of program.  If you write program we should clear about

object.

* Standard Structure of Program in OOPS:-

class
Object
objective
1.Data Members
2.Member Functions



Class:-
In a Java program the "class"  keyword denotes that the Java program follows this standard

of class structure.
(or)
Class is nothing but collection of data and functions.
(or)
Collection of data members and member functions.



2.Objective:-
It is a invisible and it is the end result of an application which can be achieved using data

members and member functions. Objective means end result of the programme.

3.Data Members:-
Data members are the elements which can be participated in a prog to achieve the objective of

an application.

4.Member Function:-
It is a process of a technic in a program which can take a parameter and returns a value.

Member function can be called methods in OOPS Programming.

5.Object:-
It is a instance of a class which can be gives the reference to its.  The data member and the

member functions which can be used outside of the class.
(or)
Object is nothing but instance of class.

Datatypes:-
Datatypes which are denotes what type of data that your processing to our program.

Variables:-
It is a location memory where we can store the values into the memory those values in the

memory called "constants".

   OOPS:- Object Oriented Programming System
--------------------------------------------------------------
1.Encapsulation
2.Data Abstraction
3.Polymorphism
4.Inheritance

1.Data Encapsulation:-
The union of data and functions into objects is known as Data Encapsulation.
(or)

Details of what a class contains need not be visible to other classes and objects that use it.  Instead, only

specific information can be made visible and the others can be hidden.  This is achieved through

encapsulation, also called data hiding.  Both abstraction and encapsulation are complementary to each

other.

Data Abstraction:-
-----------------------
We can give restricting the data, to set a number of functions.
(or)
It gives security.
(or)

Abstraction is the feature of extracting only the required information from objects.  For

example, consider a television as an object.  It has a manual stating how to use the television.  However,

this manual does not show all the technical details of television, thus giving only an abstraction to the

user.

Polymorphism:-
-------------------
It is ability to take more than one form.
(or)
Use of something for different purposes.
(or)

Polymorphism is the ability to behave differently in different situations.  It is basically seen in

programs where you have multiple method declared with the same name but with diferent parameters and

different behavior.

Inheritance:-
----------------
Relation between two classes.
(or)
Object of one class can acquire the properties of  another class.
(or)

Inheritance is the process of creating a new class based on the attributes and methods of an

existing class.  The existing class is called the base class whereas the new calss created is called the derived

class.  This is very important concept of objet-oriented programming as it helps to reuse the inherited

attributes and methods.

Super Class:-
---------------
It is a old class or parent class
Sub Class:-
--------------------
It is a new class or child class which can acquire the properties from base class.



Example 26:
---------------
//class and object

class Test
{
public void display()
{
System.out.println("This is my First Method..");
}
public void disp()
{
System.out.println("This is my Second Method..");
}
}
class A18
{
public static void main(String[] args)
{
Test T=new Test();
T.display();
T.disp();
}
}


Example 27:
---------------
class Test
{
int a=10,b=20;

public void Sum(int x, int y)
{
System.out.println("The Sum is "+(x+y));
}
public int Subtract(int x, int y)
{
return x-y;
}
public int Product()
{
return a*b;
}
public void display()
{
System.out.println("The Addition is "+(a+b));
}
public void disp()
{
System.out.println("This is a Method.. without Arguments..");
}


}
class A19
{
public static void main(String args[])
{
Test T=new Test();
T.Sum(10,20);
System.out.println("The Difference is "+T.Subtract(40,10));
System.out.println("The Product is "+T.Product());
T.display();
T.disp();
}
}


Example 28:
---------------
class Demo
{
double l;
double b;
double h;

public double volume()
{
return l*b*h;
}
}
class A8
{
public static void main(String args[])
{
Demo d=new Demo();
d.l=100;
d.b=200;
d.h=20;
System.out.println("Volume is "+d.volume());
}
}

Example 29:
-------------------
class A11
{
int sno;
String name;
String course;


void display()
{
System.out.println("Student No: "+sno);
System.out.println("Student Name: "+name);

System.out.println("Course: "+course);
}

public static void main(String args[])
{
A11 S=new A11();
S.sno=101;
S.name="Scott";
S.course="J2EE";
S.display();
}
}



Constuctors
======================
Constructors are special member function whose name is same as a class name constructors

are need not require to be called because it is invoked automatically when the objects are created.

Constructor may have an argument or may not have an argument.  Constructors have no return type.

Normal Method:
=============
A normal method may have any name associated with it. Normal methods may or may not

return values.  Normal methods may be invoked any time anywhere once  an object is created.

Example 29:
---------------
//Constructor

class Demo
{
public Demo()
{
System.out.println("This is a Constructor..");
}
}
class A9
{
public static void main(String args[])
{
Demo d=new Demo();
}
}

Method Overloading:
=================
No class is allowed to contain two methods with the same name and same signature.  However,

it is possible for a class to have two methods having the same name but different signatures.  The concept

of declaring more than one method with the same method name but different signatures is called method

overloading.


Constructor Overloading:
=======================
The concept of declaring more than one constructor in a class is called constructor

overloading.  The process of overloading constructor is similar to overloading methods.  Every

constructor has a signature similar to that of a method.  You can declare multiple constructors in a class

wherein each constructor will have different signatures.  Constructors reduce the task of assigning

different values to member variables each time when needed by different objects of the class.

Example 30:
-------------------
//Constructor Overloading
class Demo
{
public Demo()
{
     System.out.println("This is Parameterless Constructor..");
}

public Demo(int x)
{
     System.out.println("The Integer Values is "+x);
}

public Demo(String str)
{
      System.out.println("The String is " +str);
}

public Demo(double y)
{
       System.out.println("The Double Value is "+y);
}
}
class A10
{
public static void main(String args[])
{
Demo d=new Demo();
Demo d1=new Demo(100);
Demo d2=new Demo("Aptech Computer Education");
Demo d3=new Demo(12d);
}
}

this keyword:
============
1. We can have the global and local variables can have the same name. We can have the same name for

formal parameters and instance variables…


2. The this keyword hence is a representation of the current object.

3. A formal parameter and an instance variable may have the same name but in such a  case it is the

formal parameter that is given precedence over the instance variable within the method. To differentiate

the two, we precede the instance variable with the this keyword.

4. We can also use keyword this for different names of instance variables and formal parameters.

Example: this. length= l

5.  this can be used in two ways: 1) Keyword  2)Method.  this method can be used only within a

constructor.

6. If used as a keyword it represents the current object.

7. If used as a method it let us execute other overloaded constructors from within a constructor.

8. The usage of this method is subject to the following restrictions.
i. It can be used only within constructors.
ii. Even within a constructor it has to be the first statement.

Example 30:
---------------
//Using this keyword

class Demo
{
int x,y;

Demo(int x,int y)
{
this.x=x;
this.y=y;

}
public void Display()
{
    System.out.println("The Sum is "+(x+y));
}

}
class A13
{
public static void main(String args[])
{
Demo d=new Demo(10,20);
d.Display();
}
}

Example 30:
-------------------
//Using this method

class A
{
A()
{
this(0,0);
System.out.println("In A()");
}
A(int x,int y)
{
this(x,y,0);
System.out.println("In A(int x,int y)");

}
A(int x,int y,int z)
{
System.out.println("In A(int x,int y,int z)");
}
}
class A12
{
public static void main(String args[])
{
A obj=new A();
A obj1=new A(10,20);
A obj2=new A(40,50,60);
}
}

Example 30:
-------------------
//Single Inheritance
class Test
{
public void display()
{
System.out.println("Method from Super Class..");
}
}
class Demo extends Test
{
public int Sum(int x, int y)
{
return x+y;
}
}
class A20
{
public static void main(String args[])
{
Demo D=new Demo();
D.display();
System.out.println("The Sum is "+D.Sum(10,20));
}
}

Example 30:
-------------------
Hierarchical Inheritance
======================

//Hierarchical Inheritance
class Test
{
public void CRT()
{
System.out.println("Everyone should attend CRT Classes..");
}
}
class BTech extends Test
{
public void CSE()
{
System.out.println("Computer Science Engineering..");
}
}
class MTech extends Test
{
public void IT()
{
System.out.println("Information Technology..");
}
}
class PG extends Test
{
public void MCA()
{
System.out.println("Master of Computer Applications..");
}
}
class A21
{
public static void main(String args[])
{
Test T=new Test();
T.CRT();
BTech B=new  BTech();
B.CSE();
B.CRT();
MTech M=new MTech();
M.IT();
M.CRT();
PG P=new PG();
P.MCA();
P.CRT();

}
}


Example 30:
-------------------
//Multilevel Inheritance

class Epack
{
public void C()
{
System.out.println("C is a middle level programming language..");
}
}
class ITBooster extends Epack
{
public void Java()
{
System.out.println("Java is a Platform-Independent..");
}
}
class ACCP extends ITBooster
{
public void DotNet()
{
System.out.println(".Net is Framework..");
}
}
class A22
{
public static void main(String args[])
{
ACCP A=new ACCP();
A.C();
A.Java();
A.DotNet();
}
}


Example 30:
-------------------
//Inheritance with Constructor

class Demo
{
public Demo()
{
System.out.println("Constructor from Super Class..");
}
}
class Test extends Demo
{
public Test()
{
System.out.println("Constructor from Sub Class..");
}
}
class A23
{
public static void main(String args[])
{
Test T=new Test();
}
}

Example 30:
-------------------
//Multilevel Inheritance with Constructor

class Polygon
{
public Polygon()
{
System.out.println("This is Polygon method");
}
}
 class Circle extends Polygon
{
public Circle()
{
System.out.println("This is Circle Method");
}
}
class Rectangle extends Circle
{
public Rectangle()
{
System.out.println("This is Rectangle");
}
}
 class A24
{
public static void main(String args[])
{
Rectangle R=new Rectangle();
}
}

Example 30:
-------------------
Abstract Class:
==============
A class that is defined using the abstract keyword and that contains at least one method which

is not implemented in the class itself is referred to as abstract class.  Means the abstract class contains at

least one method without a body, the class cannot be instantiated using the new keyword.  While declaring

an abstract class or abstract method the keyword 'abstract' should be used.  The abstract keyword is thus

an indicative of incompleteness.  As an abstract class is considered to be an incomplete class the JVM does

not permit the creation of objects of abstract classes. The JVM allows objects for concrete classes only.

Example 30:
-------------------
abstract class Common
{
abstract public void Project();

public void display()
{
System.out.println("This is a normal method in Abstract class");
}

}
class Btech extends Common
{
public void Project()
{
System.out.println("This is Btech Project");
}
}
class MCA extends Common
{
public void Project()
{
System.out.println("THis is MCA Project");
}
}
class A25
{
public static void main(String args[])
{

//shape s=new Btech();
Btech s=new Btech();
s.Project();
s.display();
MCA s1=new MCA();
s1.Project();
s1.display();
}
}

Example 30:
-------------------
abstract class shape
{
abstract public void draw();

public void display()
{
System.out.println("This is a normal method in Abstract class");
}

}
class Circle extends shape
{
public void draw()
{
System.out.println("Drawing a circle");
}
}
class Rectangle extends shape
{
public void draw()
{
System.out.println("Drawing a rectangle");
}
}
class A26
{
public static void main(String args[])
{

//shape s=new Circle();
Circle s=new Circle();
s.draw();
s.display();
Rectangle s1=new Rectangle();
s1.draw();
s1.display();
}
}


Interfaces:
========
An interface contains only abstract members.  Unlike an abstract class, an interface cannot

implement any method.  But similar to an abstract class, an interface cannot be instantiated.  An interface

can only be inherited by classes or other interfaces.  An interface is declared using the keyword interface

Interfaces does not allow the normal methods.  To inherit the interface “implements “ keyword should be

used.

Example 30:
-------------------

interface myinter
{
int sum(int x,int y);
                  int sub(int x,int y);
}
 interface myinter2
{
int mul(int x,int y);
                   int div(int x,int y);
}
class demo implements myinter,myinter2
{
public int sum(int x,int y)
                   {
            return x+y;
                  }
                 public int sub(int x,int y)
                 {
                  return x-y;
                 }
                 public int mul(int x,int y)
                 {
                  return x*y;
                 }
                 public int div(int x,int y)
                 {
                  return x/y;
                 }
}
class A26
{
public  static void main(String args[])
                   {
                  demo d=new demo();
                   
System.out.println("The Sum is "+d.sum(10,20));
System.out.println("The Subtraction is "+d.sub(50,40));
System.out.println("The Multiplication is "+d.mul(30,40));
System.out.println("The Division is "+d.div(20,10));
}
}

Example 30:
-------------------
interface A
{
public void aMeth();
}
interface B
{
public void bMeth();
}
class C implements A,B
{
public void aMeth()
{
System.out.println("a Method");
}
public void bMeth()
{
System.out.println("b Method");
}
}
class A27
{
public static void main(String args[])
{
C ob=new C();
ob.aMeth();
ob.bMeth();
}
}


Example 30:
-------------------
Class and Interfate
-------------------------

class A
{
public void Method()
{
System.out.println("Method  from Class");
}
}
interface B
{
public void Meth();
}
class C extends A implements B
{
public void Meth()
{
System.out.println("Method Definition of Interface");
}
}
class A28
{
public static void main(String args[])
{
C ob=new C();
ob.Method();
ob.Meth();
}
}

Super Keyword:
==============
The super can be used in two ways

As a keyword:-
-----------------
If used as a keyword it lets you access the immediate super class members
As a method:-
------------------
If used as a method it lets you execute your immediate super class constructors

A subclass and a super class may have the variables with the same name. However, in such a

case it becomes mandatory to precede the super classes’ members with the super keyword.

Example 30:
-------------------
class Test
{
int a = 100;
}

class Demo extends Test
{
int a = 200;
void show()
{
System.out.println(super.a);
System.out.println(a);
}
}
class A18
{
public static void main(String[] args)
{
new Demo().show();
//Demo s=new Demo();
//s.show();
}
}


Example 30:
-------------------
class Demo1
{
public void display()
{
     System.out.println("Method in Super Class");
}
}
class Derived extends Demo1
{
public void display()
{
                            super.display();
        System.out.println("Method in Sub Class");
}

}
class A19
{
public static void main(String args[])
{

Derived d=new Derived();
d.display();
}

}


protected access modifier:
===================
"protected" Access Modifier:-
--------------------------------------
The protected access modifier protects the data members that are declared using this modifier.

The protected modifier is specified using the protected keyword.  Variables or methods that are declared

as protected are accessed only by the class in which they are declared or by a class that is derived from

this class.

Example 30:
-------------------
class Animal
{
protected int sno;
protected String sname;
}
class A27 extends Animal
{
public static void main(String args[])
{
A27 C=new A27();
C.sno=101;
C.sname="Scott";
System.out.println("The Student No is  " + C.sno);
System.out.println("The Student Name is  " +C.sname);
}
}

Polymorphism:
===========

Polymorphism is derived from two Greek words, namely Poly and Morphos.  Poly means many

and Morphos means forms.  Polymorphism means existing in multiple forms.  Polymorphism is the ability

of an entity to behave differently in different situations.  The two methods in class having the same name

but different signatures performing the same basic operation but in different ways.


Example:
-----------
class Test
{
public void Hello()
{
System.out.println("Hello...");
}

public void Hello(String str)
{
System.out.println("Hello..."+str);
}

}
class A28
{
public static void main(String args[])
{
Test obj=new Test();
obj.Hello();
obj.Hello(" Uma");
}
}

Example:
-----------
 class demo
{
int sum(int x,int y)
                   {
return x+y;
                   }
                   String sum(String x, String y)
          {
                 return x+y;
                   }
                    double sum(double x, double y)
                   {
                return x+y;
                   }
int sum(int x,int y,int z)
                   {
                return x+y+z;
                   }
}
class A29
{
public static void main(String arg[])
                   {
                demo d=new demo();
System.out.println("The Sum of integer value is : "+d.sum(10,20));
System.out.println("The String value is : "+d.sum("Aptech Computer Education "," Dwarakanagar"));

System.out.println("The Sum of double value is : "+d.sum(10.23,20.54));
System.out.println("The Sum of multiple integer value is :"+d.sum(10,20,30));
              }
}

Method Overriding:
================
Method overriding is a feature that allows the sub class to override or redefine the methods of

the super class.  Overriding a method in the sub class can change the body of the method that was

declared in the super class.  Thus, the same method with the same name and signature declared in the

super class can be reused in the sub  class to define a new behavior.

Example:
-----------
 class baseclass
{
public void display()   // function
{
System.out.println("This is normal function is base class ");
                  }
}
class derived extends baseclass
{
public void display()
                  {
//super.display();
System.out.println("This is override function is derived class");
                   }
}

class A30
{
public static void main(String args[])
{
derived d=new derived();
d.display();
                  }
 }

Dynamic Method Dispatch:
=====================
Dynamic method dispatch is a concept where in we assign a subclass object to the super class

object reference.  The main advantage of dynamic method dispatch is Run Time Polymorphism

Example:
-----------
class vehicle
{
public void brake()
{
System.out.println("Vehicle's brakes applied....");
}
}
class Car extends vehicle
{
public void brake()
{
System.out.println("car's brakes applied....");
}
}
class Bike extends vehicle
{
public void brake()
{
System.out.println("bike's brakes applied....");
}
}
class A20
{
public static void main(String args[])
{
int ch=Integer.parseInt(args[0]);
vehicle V;
if(ch==1)
V=new Car();
else if(ch==2)
V=new vehicle();
else
V=new Bike();
V.brake();

}
}

Final keyword:
===========
Final keyword can be used at 3 different locations:
1. In front of variables
2. In front of methods
3. front of classes

1. In front of variables:
-----------------------------
If a variable is declared as final, it is converted to a constant and is prevented from further

modifications.

2. In front of methods:
----------------------------
If a method is declared as final, then the method is prevented from being overridden.

3. In front of classes:
-------------------------
If a class is declared as final, the class is prevented from being subclass(inherited).

Example:


-----------
// In front of variables
class A31
{
static final int max=5;
public static void main(String args[])
{
max = 10;
for(int i=0;i<=max;i++)
{
System.out.println("value at i :"+i);
}
}
}



Example:
-----------
/*In front of methods*/

class Proposal
{
public final void finalMemo()
{
System.out.println("This is final mamo");
}
}
class A32 extends Proposal
{
/*public void finalMemo()
{
System.out.println("This is final override method");
}*/

public static void main(String args[])
{
Proposal p=new Proposal();
p.finalMemo();
}
}

Example:
-----------
// In front of classes

final class superclass
{
public void sayHello()
{
System.out.println("Hello World");
}
}
class subclass //extends superclass
{
public void sayHelloAgain()
{
System.out.println("Hello World Again");
}
}
class A33
{
public static void main(String args[])
{
superclass supobj=new superclass();
subclass subobj=new subclass();
supobj.sayHello();
//subobj.sayHello();
subobj.sayHelloAgain();
}
}


Type Casting:
============
Need of TypeCasting:
----------------------------
Consider a payroll system of an organization.  The gross salary of  an employee calculated and

stored in varibles of float type.  Currently the output is shown as float values.  The payroll department

wants the salary amount as  a whole number and thus wants any digits after the decimal point of the

calculated salary to be ignored.  The programmer is able to  achieve this using the typecasting feature of

Java.  Typecasting allows you to change the datatype of a variable.

Type Casting is of two types
1. Implicit TypeCasting
2. Explicit Type Casting

1. Implicit TypeCasting:
-------------------------------
Implicit typecasting refers to automatic conversion of datatypes.  This is done by JVM.

Implicit typecasting is done only when the destination and source data types belongs to same hierarchy.  In

destination data type must hold a  larger range of values than the source data type.  So Implicit

typecasting prevents the loss of data.  If you have int type value to, you can assign long type of variable.

int -----> Implicit Typecasting ------>long

Example:
-----------
//Implicit Conversion

class A29
{
public static void main(String args[])
{
long   a = 10, result;
int   b = 7;

result = a + b;

System.out.println("a + b = "+ result);
}
}

Explicit Typecasting:-
--------------------------
Explicit typecasting refers to changing a data type of  higher precision into a data type of lower precision.

For example, using  explicit typecasting, you can manually convert the value of float type into int type.

This typecasting might result in loss of data, the digits after the decimal point are lost.

float----->Explicit Conversion----->int

Example:
-----------
class A35
{
    public static void main(String args[])
    {
        int x = 25;
      byte y = (byte) x;
        //byte y=x;
        System.out.println("y is : "+y);
    }
}


Example:
-----------
class A35
{
    public static void main(String args[])
    {
//Explicit
        /*int x = 25;
      byte y = (byte) x;
        //byte y=x;
        System.out.println("y is : "+y);*/

//Implicit

byte x = 25;
      int y =  x;
     System.out.println("y is : "+y);

    }
}

static keyword:
============
Class variables: -
---------------------
i. Class variables are variables that belong to the entire class and not to a specific instance of a class.

ii.Instance variables on the contrary are variables belongs to specific instance of the class.

iii.Class variables are declared with the static keyword.

iv.Class variables are allocated memory only once which can then be commonly accessed by all the

instances of the class.

v. Static variables are allocated memory on the static pool. They are allocated memory only once that to

when a class is loaded into the memory for the first time.

vi. Since memory for a class variable is allocated at the time of loading the class itself. We can access this

static variable directly with the class name itself without having to wait for the instantiation of the class.

vii. Static variables are given default values (zeroes in case of numbers, false in case of Booleans, null

incase of characters and other objects)

Example:
-----------

class A36
{
static int eno=101;
static String ename="Uma";

public static void main(String a[])
{
System.out.println("Employee ID is "+eno);
System.out.println("Employee Name is " + ename);
}
}


Static Block:-
-------------
i. A static block is a block of statements preceded by a static keyword.

ii.The main purpose of a static block is to initialize static members to non-zero values.

iii. We can have any number of static blocks defined in a java program.

iv.If there is more than one static block in a java program, the block are executed in a top-down approach

v.Static blocks are executed only once, when the class is loaded into memory for the very first time.

vi. Static blocks have a higher precedence than constructors and even the main method.


Static blocks are subject to the following restrictions:-
------------------------------------------------------------
i. They can access other static members only.

ii.They cannot make use of this and super keywords as this and super are used when an object is created

iii.But in static blocks we won’t create an object.

Not only variables if required , methods may also be declared as static the advantage of declaring methods

as static is one gets to execute the static methods directly with the class more itself rather than creating an

instance of the class.

Example:
-----------

class A
{
static
{
System.out.println("In static of A");
}
static int x;
static
{
System.out.println("In the other static of A");
x=20;
}
}
class A22
{
static
{
System.out.println("In static before main");
}
public static void main(String args[])
{
System.out.println("In  main");
System.out.println("A.x....."+A.x);
}
static
{
System.out.println("In static after main");

}
}


Packages in Java
==================================================
Packages:
--------------
A package represents a directory that contains related group of classes and interfaces.
eg:  import java.io.*;

java is directory name
io is another sub directory name.
* represents  all the classes and interfaces of that io sub directory.

Advantages of Packages:
---------------------------------
1. Packages hide the classes and interfaces in a separate sub directory, so that accidental deletion of

classes and interfaces will not take place.

2. The class and interfaces of a package are isolated from the classes and interfaces of another package.

This means that we can use same names for classes of two different package.  eg: There is Date class

java.util package and also there is another Date class available in java.sql package.

3.  The group of package is called a lilbrary.  The classes and interfaces of a package are like books in a

library and can be reused several times.

Two Different Types of Packages:
-------------------------------------------
1.Built-in packages
2.User-definced packages

Built-in Packages:
------------------------
eg:
1. import java.lang.*;

lang stands for language---- String , System, Thread, Exception etc.

2.  java.util
---------------
util stands for utility.  This package contains useful classes and interfaces like Stack, Linkdedlist,

Hashtable, Vector, Arrays etc. These are called collections.There are also classes  for handling date and

time operations.

3. java.io:
---------------
io stands for input and output.  This package contains streams.  A stream represents a flow of data from

one place to another place.   Streams are useful to store data in the form of files and also to perform

input-output related classes.

4. java.awt:
----------------
awt stands for abstract window toolkit. This package helps to develop GUI(Graphical User Interface)

where programs with colorful screens, paintings and images etc. can be developed.  It consists of an

important sub package, java.awt.event, which is userful to provide action for components like push

buttons, radio buttons, menus etc.

5. javax.swing:
--------------------
This package helps to develop GUI like java.awt. The 'x' in javax represents that it is an extended package

which means it is a package developed from another package by adding new features to it.  In fact,

javax.swing is an extended packge of java.awt.

6.java.net
--------------
net stands for network.  Client-Server programming can be done by using this package.  Classes related to

obtaining authentication for a network, creating sockets at client and server to establish communication

between them are also available in java.net package.

7. java.applet:
---------------------
Applets are programs which come from a server into a client and get executed on the client machine on a

network.  Applet class of thei package is useful to create and use applets.

8. java.text:
---------------
This package has two important classes, DateFormat to fromat or dates and times, NumberFormat which

is useful to format numeric values.

9. java.sql:
----------------
sql stands for structured query language.  This package helps to connect to databases like Oracle or

Sybase, retrieve the data from them and use it in a Java Program.



User-defined Packages:
===================

1.Packages offer different namespaces allowing two or more
programmers to make use of the same class name but with
different implementations without any problem.

2.Packages effective management of classes. They act as a
collection of interrelated classes and interfaces.

3. Packages are implemented by the JVM , using the
 operating systems file structure mechanisms.

4. Working with packages is a two step process, in the first
step , we intimate the JVM about the placement of a class in a
package by using the package statement.

5. Syntax :
--------------
 package packagename;

6.  The package statement must be the first statement in the
program. There is only one package statement for a program.

7. Whatever, the JVM understands as a package is
understood by the operating system as a directory i.e. every
package in java relates to a directory in the operating system.


8. This can be done in two ways : Either manually or by
using  -d option of the java utility.


9.  If we din’t place a class explicitly in a package the program
the class will be placed implicitly in the default package…..
by -d . option.

10. -d option if used will implicitly ensure that the respective
directories structures are created if requires and ensure that
the .class files are placed in them respectively.

11.Syntax for using javac
Javac –d .  programname.java
Ex:- javac –d . Employee.java

Compiles the employee.java creates directory
structures if required (as indicated by .) and places the .class
files in those directories.

12. To execute a class that has been placed in a package we
give the following command from the parent directory
containing the package directory.

Executing:
------------
java Packagename.classname


13. One must compulsorily declare a class placed in a package
public to be able to create its objects in other classes belonging
to other packages.

14.The import keyword is used.
eg: import packagename.*

15. Import packagename.classname
Imports only the specified class name into the current program

Sub-Packages:-
===========
A package within a package is a sub-package.

1. Sometimes placing classes in a package may not offer us the
required uniqueness in such cases we place classes in the
sub-packages.

2. To place a class in a subpackage
we use the below syntax:
java package packagename.subpackagename
3. To run a class placed in a sub-package we use the below
syntax
java packagename.subpackagename.classname

4. Import packagename.* imports only the classes and
interface placed directly in the package. To import classes and
interfaces belonging to sub-packages

5.we use the below syntax:

import packagename.subpackagename.*
import packagename.subpackagename.classname


Example I
====================
Creating Package
-------------------------------
package pack;

public class Addition
{
private double d1,d2;

public Addition(double a, double b)
{
d1=a;
d2=b;
}

public void Sum()
{
System.out.println("Sum= " + (d1+d2));
}
}

..............................................................
->  javac -d . Addition.java



Calling Package in Use.java:
------------------------------------

//import pack.Addition;

class Use
{
public static void main(String a[])
{
pack.Addition obj=new pack.Addition(10, 15.5);
//Addition obj=new Addition(10,15.5);
obj.Sum();
}
}

........................................................
->  javac Use.Java

-> java Use

============================================
Example II
====================
Creating Package with Interface:
------------------------------------------

// Package with Interface

package mypack;

public interface MyDateInterface
{
public void ShowDate();
}
..............................................................................

-> javac -d . MyDateInterface.java

------------------------------------------------------------
Calling package with Interface
-------------------------------------------------

import mypack.MyDateInterface;
import java.util.Date;

class DateImplinterface implements MyDateInterface
{

public void ShowDate()
{
Date D=new Date();
System.out.println("To day's Date is: "+D);
}
public static void main(String a[])
{

DateImplinterface obj=new DateImplinterface();
obj.ShowDate();
}
}
.............................................................................
->  javac DateImplinterface.java
->  java DateImplinterface

========================================

Example III
===============================
package EmpDetails;
public class Employee
{
int Empno;
String Ename;
double sal;
public Employee(int Empno,String Ename,double sal)
{
this.Empno=Empno;
this.Ename=Ename;
this.sal=sal;
}

public void PrintDetails()
{
    System.out.println("Empno.."+this.Empno);
    System.out.println("Ename.."+this.Ename);
    System.out.println("Sal.."+this.sal);
}

public static void main(String args[])
{
Employee emp=new Employee(100,"ABC",20000);
emp.PrintDetails();
}
}
...............................................................................................

import EmpDetails.Employee.*;
class EmpDemo
{
public static void main(String args[])
{
EmpDetails.Employee emp=new EmpDetails.Employee(111,"SSS",34343);
EmpDetails.Employee emp1=new EmpDetails.Employee(2222,"DDDD",55555);
emp.PrintDetails();
emp1.PrintDetails();
}
}
....................................................................................................

How to execute Packages Manully:-
===========================
->First create Pack1 folder in D drive and create file Employee.java.

->Compile (javac Employee.java) it creates a class file.

->In above program our package name is EmpDetails.

->In D:\pack1>md EmpDetails
It creates EmpDetails folder in pack1 folder

->D:\>pack1> move Employee.class EmpDetails

->Now execute the Employee file
D:\pack1>java EmpDetails.Employee

Then the progrma will be executed successfully.

How to execute Packages Automatically:
============================
->create a folder in pack2 in D drive

->Save Employee.java file in pack2 folder

->Compiling:
---------------
D:>pack2>javac -d . Employee.java

Executing:-
-------------
->java EmpDetails.Employee

Package Executing From Different Floders:-
==================================
->create pack3 folder in D drive
->copy above EmpDetails folder in pack3 folder
->D:>pack3>java EmpDetails.Employee

Package Executing From Different Floders:-
==================================
->create pack4 folder in D drive
->copy above EmpDetails folder in pack4 folder
->D:>pack4>java EmpDetails.Employee


Calling Package in another program using set classpath:
==========================================
-> First create D:>Pack5 folder.
->copy above Employee.java and EmpDetails folder in pack5 folder

-> First create D:>Pack6 folder.
->copy above Employee.java and EmpDetails folder in pack6 folder

->First create C:>Pack7 folder
->Save EmpDemo.java file in C:>Pack7.

->Compiling Program using classpath
------------------------------------------------

->C:>Pack7>set classpath=.;D:\Pack5;D:\Pack6;

->javac EmpDemo.java

->java EmpDemo

============================================
Example IV
================================
Creating Sub Package
----------------------------------------------

//creating a sub package tech in the package dream

package aptech.computers;

public class Sample
{
public void Show()
{
System.out.println("Welcome To Aptech Computers..");
}
}

//javac -d . Sample.java
----------------------------------------------------------------
Calling Sub Package:
---------------------------------------

// Using Sub Package aptech.computers

import aptech.computers.Sample;

class UseSubPack
{
public static void main(String a[])
{
Sample S=new Sample();
S.Show();
}
}

-> javac UseSubPack.java

->  java UseSubPack

======================================
Access Specifiers in Java:
===============================
package Same;

public class A
{
private int a=1;
public int b=2;
protected int c=3;
int d=4;  //default

}

//javac -d . A.java

-----------------------------------------------------------

package Same;
import Same.A;

public class B
{
public static void main(String a[])
{
A obj=new A();
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}
}

// javac -d . B.java

-------------------------------------------------------------

import Same.A;

//public class C
public class C extends A
{
public static void main(String a[])
{
//A obj=new A();

C obj=new C();
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}
}

//javac -d . C.java

===========================================

Exceptional Handling
================
Errors in Java Program:
-------------------------------
Three types of Errors
1. Compile-time errors
2. Run-time errors
3. Logical errors

Compile-time errors:
--------------------------
These are the syntactical errors found in the code, then a program fails to compile.
Eg: forgetting a semicolon at the end of the a java statement.

Run-time Errors:
-----------------------
Errors in programs that occurs during the program execution.
Eg: A user has entered invalid data.

Logical Errors:
--------------------
The programmer might be using a wrong formula or the design of program itself is wrong.  Logical errors

are not detected by Java compiler or JVM.  The programmer only responsible for them.

Exceptions:
=========
Basically, an exception is a runtime error.  All exceptions occur only at runtime but some exceptions are

detected at compile-time and some others at runtime.
An exception is an error which can be handled.  It means when an exception happens, the programmer can

do something to avoid any harm.  Actually exceptions are used for handling errors in programs that

occurs during the program execution. During the program execution if any error occurs and you want to

print your own message or the system message about the error then you write the part of the program

which generate the error in the try{} block and catch the errors using catch() block. Exception turns the

direction of normal flow of the program control and send to the related catch() block. Error that occurs

during the program execution generate a specific object which has the information about the errors

occurred in the program
An exception is a problem that arises during the execution of a program. An exception can occur for many

different reasons, including the following:

•A user has entered invalid data.
•A file that needs to be opened cannot be found.
•A network connection has been lost in the middle of communications, or the JVM         has run out of

memory.
Some of these exceptions are caused by user error, others by programmer error, and others by physical

resources that have failed in some manner.

Checked Exceptions:
---------------------------
The Exceptions are  checked at compilation-time by the Java Compiler are called “checked exceptions’.
Eg: public static void main(String a[]) throws IOException

Unchecked Exceptins:
----------------------------
The Exceptions , that are  checked by the JVM are called “Unchecked exceptions’

All Exceptions are declared as classes in java.  Even the errors are also represented by classes.

Throwable is a class that represent all errors and exceptions which may occur in Java.
Exception is the super class of all exceptions in Java.




try block:
-------------
The advantage of try block is that even if some exception arises inside it, the program will not be

terminated.  When JVM understands that there is an exception, it stores the exception details in exception

stack and then jumps into a catch block.
Syntax:
try
{
Statements;
}

catch block:
----------------

The catch block displays the exception details to the user.  This helps the user to understand that there is

some error in the program.
Syntax:
catch(Exceptionclassname obj)
{
}

finally block:
-----------------
The speciality of finally block is that the statements inside the finally block are executed irrespective of

whether there is an exception or not.  The programmer should perform clean up operations like closing

files and terminating the threads.

Syntax:
finally
{
}

throws Clause:
---------------------

The Java Compiler will not give any error related to runtime exceptions.  But the rule is that the

programmer should handle checked exceptions.  The programmer should throw them out using  ‘throws’

clause.  Otherwise there will be an error flagged by Java Compiler.

throw clause:
-----------------

throw clause can be used to throw out own exceptions also.  Exceptions available in java, we can also

create our own exceptions which are called ‘user-defined exceptions’.  We need to the throw clause to

throw these user defined exceptions.


Example I:
------------------------------------------------
class A31
{
public static void main(String args[])
{
int x,y;
x=10;
y=0;
int z=x/y;
System.out.println("The result is"+z);
}
}
-----------------------------------------------------------------------------
Example II
------------------------------------------------------------------------
class A32
{
public static void main(String args[])
{
int x,y;
x=10;
y=0;

try
{
   int z=x/y;
  System.out.println("The result is"+z);
}
catch(Exception e)
{
System.out.println("Number cannot be divided by zero..");
}

}
}
--------------------------------------------------------------------------------
Example III
---------------------------------------------------------------------------------


class Exp1
{
String empname;
int empid;

public Exp1()
{
empname="Scott";
empid=101;
}

public static void main(String args[])
{
Exp1 e=new Exp1();
Exp1 eobj=e;
e=null;

try
{
System.out.println("Exp1 Name: "+e.empname);
System.out.println("Exp1 No: "+e.empid);
}
/*catch(NullReferenceException ex)
{
System.out.println("Error: " +ex);
}*/
catch(Exception ex)
{
System.out.println("Value cannot be null: " +ex);
}
}
}
-----------------------------------------------------------------------------------------------
Example IV
------------------------------------------------------------------------------------------------

class Exp2
{
public static void main(String args[])
{
int x,y,z;


try
{
x=Integer.parseInt(args[0]);
y=Integer.parseInt(args[1]);
z=x+y;
System.out.println("The Result is  "+z);
}

/* catch(NumberFormatException ex)
{
System.out.println("Enter a Number..");
}
*/
catch(Exception ex)
{
System.out.println("Enter a Number..");
}
}
}

--------------------------------------------------------------------------------------------------
Example V
-------------------------------------------------------------------------------------
//Using throws clause
import java.io.*;

class Exp3
{

public static void main(String args[]) //throws Exception
{
BufferedReader B=new BufferedReader(new InputStreamReader(System.in));
int num;
System.out.print("Enter a number.... ");
num = Integer.parseInt(B.readLine());
System.out.println("U entered....."+num);
}
}

--------------------------------------------------------------------------------------------------
Example VI
-------------------------------------------------------------------------------------
class NumberException
{
public void test( String []number)
{
try
{
String num = number[0];
int numValue = Integer.parseInt(num);

System.out.println("The square is:"+numValue*numValue);

}
catch(ArrayIndexOutOfBoundsException ne)
{
System.out.println("No arguments given!");
}
catch(NumberFormatException nb)
{
System.out.println("Not a Number!");
}

}
}

class A34
{
public static void main( String args[])
{
NumberException obj=new NumberException();
obj.test(args);
}
}



/*
Output:
-----------
java A34
  No arguament given!

  java A34 dd
  Not a Number!

  java A34 4
  The square is 16
*/



--------------------------------------------------------------------------------------------------
Example VI
-------------------------------------------------------------------------------------
//User-defined Exception


import java.util.*;
class UsrdefExp extends Exception
{


UsrdefExp(String msg)
{
super(msg);
}
public static void main(String args[])
{
Scanner S=new Scanner(System.in);

int x=133;
int y;
int result=0;
System.out.print("Enter the value of y: ");
try
{
y=S.nextInt();
if(y == 0)
{
UsrdefExp exp= new UsrdefExp("\nZero not allowed here");
throw exp;
}
if(y < 0)
{
UsrdefExp exp= new UsrdefExp("\nPlease Enter Positive Value");
throw exp;
}

System.out.println("\nYou entered: " + y);

result=x/y;
}

catch(UsrdefExp exp)
{

exp.printStackTrace();

}

catch(InputMismatchException obj)
{
System.out.println("\nEnter Number only.." );
}
System.out.println("\nResult of division: "+result);
}
}
---------------------------------------------------------------------------------------------------
Multi Threading
========================
Thread:
----------
A thread represents a separate path of execution of a group of statements.  Java program is group of

statements is executed by JVM.  This execution is called a thread.  This means in every java program,

there is always a thread running internally.  This thread is used by JVM to execute the program.

To Find the Current Thread:
--------------------------------------------------
class Current
{
public static void main(String args[])
{
System.out.println("Let us find Current Thread");
Thread t=Thread.currentThread();
System.out.println("Current Thread: "+t);
System.out.println("Thread Name: "+t.getName());
}
}

/* output: Current Thread: Thread[main,5,main]
Thread Name: main  */
------------------------------------------------------------------------------
-> In above program currentThread() is static method in Thread Class.
-> So we called it as Thread.currentThread().
-> First main indicates the name of the thread running the current code.
-> 5 is priority of the thread.
Everty thread will have a priority number from 1 to 10. 1 is minimum priority, 10 is maximum priority of

a thread.  If the priority of a thread is more,  it is given more preference while execution by JVM.
The default priority number of a thread is 5.
-> The next main indicates the thread group name to which this thread belongs.


A thread represents execution of statements.  The statements executing is of two types.
1. Single Tasking
2. Multi Tasking

1. Single Tasking
---------------------
A task means doing some calculation or any processing.  In Single tasking environement only one task is

given to the processor at a time.  Here the processor time is wasted.

2. Multi Tasking:
---------------------
If we give several jobs to a processor at a time is called multi-tasking.  Here we can utilize the processor

time in an optimum way.

Multi-tasking is of two types:

a. Process-based multi-tasking:
--------------------------------------
In process-based multi tasking, several programs are executed at a time by the microprocessor.

b. Thread-based multi-tasking:
--------------------------------------
In Thread-based multi tasking, several parts of the same program is executed at a time, by

micorprocessor.

Uses of Threads:
---------------------
1. Threads are mainly used in server-side programs to serve the needs of multiple clients on a network or

Internet.  On Internet, a server machine has to cater the needs of thousands of clients, at a time.  If we use

threads in the server, they can do various jobs at a time, thus they can handle several clients.

2. Threads are also used to create games and animation.  Animation means moving the objects from one

place to another.  In many games, generally we have to perform more than one task simultaneously.

3. Threads are light-weight because they utilize minimum resources of the system.  This means they take

less memory and less processor time.

Creating Thread and Running it:
-----------------------------------------
In every Java Program, there is a main thread.  Apart from this we  can create our own thread.

1. Java supports concurrent programming.

2. We can create threads in two ways.
i. Thread class (extends)
ii. Runnable interface (implements)

Both are found in java.lang package.

3. By Default, run() method is executed by a thread.


------------------------------------------------------------
Example I (Without Thread)
--------------------------------------------
class Demo
{
public void display()
{

for(int i=1;i<100000;i++)
{
System.out.println(i);
}
}
}

class NoThread
{
public static void main(String args[])
{
Demo obj=new Demo();
obj.display();
}
}



---------------------------------------------------------------------------------------------
Example II(Creating Thread and Running it)
-----------------------------------------------------------------------------------

class Demo extends Thread

{
public void run()
{

for(int i=1;i<100000;i++)
{
System.out.println(i);
}
}
}

class MyThread
{
public static void main(String args[])
{
Demo obj=new Demo();
Thread t=new Thread(obj);
t.start();
//obj.start();
}
}

---------------------------------------------------------------------------------------------
Example III(Terminating Thread)
-----------------------------------------------------------------------------------


class Demo extends Thread
{
boolean stop=false;


public void run()
{

for(int i=1;i<100000;i++)
{
System.out.println(i);
if(stop)
return;
}
}
}

class TerminateThread
{
public static void main(String args[]) throws Exception
{
Demo obj=new Demo();
Thread t=new Thread(obj);
t.start();
System.in.read();
obj.stop=true;

}
}

-----------------------------------------------------------------------------------------
Example IV (Using Runnable Interface)
--------------------------------------------------------------------------

class Demo implements Runnable
{
public void run()
{
task1();
task2();
task3();
}
void task1()
{
System.out.println("This is task1..");
}

void task2()
{
System.out.println("This is task2..");
}

void task3()
{
System.out.println("This is task3..");
}
}

class SingleTaskThread
{
public static void main(String args[])
{
Demo obj=new Demo();
Thread t=new Thread(obj);
t.start();
}
}
--------------------------------------------------------------------------------------
Multi Threading:
------------------------
Using more than one thread is called MultiThreading.

Example V
----------------------------------
class Demo extends Thread
{
String str;
Demo(String str)
{
this.str=str;
}
public void run()
{
for(int i=1; i<=10; i++)
{
System.out.println(str +" : "+i);

/*try
{
Thread.sleep(2000);
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}*/
}
}
}
class MultiTaskThread
{

public static void main(String args[])
{
Demo obj1=new Demo("Cut the ticket");
Demo obj2=new Demo("Show the seat");

Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);

t1.start();
t2.start();
}
}
-----------------------------------------------------------------------------------------

Example VI
------------------------------------------------------------------

class ThreadName
{
public static void main(String args[])
{
Thread th=Thread.currentThread();
System.out.println("Hai "+th);
System.out.println("Default Thread Name is "+th.getName());
th.setName("Uma");
System.out.println("New Thread Name is "+th.getName());
System.out.println("Default Priority is "+th.getPriority());
th.setPriority(8);
System.out.println("New Priority is "+th.getPriority());
System.out.println(th.currentThread());
}
}

------------------------------------------------------------------------------------
Example VII (Using sleep method)
----------------------------------------------------------------
class sleepdemo
{
public void display()
{
try
{
for(int i=1;i<=5;i++)
{
Thread.sleep(1000);
System.out.println("Advance Happy Ugadi");
}
}
catch(InterruptedException ex)
{}
}
public static void main(String args[])throws Exception

{
for(int i=1;i<=5;i++)
{
Thread.sleep(1000);
System.out.println(i);
}
for(int i=5;i>=1;i--)
{
Thread.sleep(500);
System.out.println(i);
}
sleepdemo S=new sleepdemo();
S.display();


}
}

------------------------------------------------------------------------------------
Example VII
-------------------------------------------------------------------------
class ThreadDemo implements Runnable
{
public static void main(String args[])
{
ThreadDemo obj=new ThreadDemo();
obj.create();
for(int i=1;i<=10;i++)
{
System.out.println("This is main Thread");
}
}
public void create()
{
Thread objth=new Thread(this);
objth.start();
}
public void run()
{
for(int i=0;i<=5;i++)
{
try
{
Thread.sleep(500);
System.out.println("This is Child Thread");
}
catch(InterruptedException e){ }
}
}
}
---------------------------------------------------------------------------------
Example VIII
-------------------------------------------------------------------------------
//Multiple Threads Acting on Single Object

class Reserve implements Runnable
{
int available=1;
int wanted;

Reserve(int i)
{
wanted=i;
}
public void run()
{
                   System.out.println("Available Berths= "+ available);

if(available >= wanted)
{
String name=Thread.currentThread().getName();
System.out.println(wanted +" Berth reserved for " + name);
try
{
Thread.sleep(1500);
available=available - wanted;
}
catch(InterruptedException ex)
{}

}

else
{
System.out.println("Sorry, no berths..");
}
}
}

class UnsafeThread
{
public static void main(String args[])
{
Reserve obj=new Reserve(1);

Thread t1=new Thread(obj);
Thread t2=new Thread(obj);

t1.setName("First Person");
t2.setName("Second Person");

t1.start();
t2.start();
}

}

/* output:

Available Berths= 1
1 Berth Reserved for First Person
Available Berths= 2
1 Berth Reserved for Second Person

Note:
------
In above program it has allotted the same berth to both the passengers.
Here we have taken available berths as 1.  When thread t1 enters the run() method, it sees available

number of berths as 1 and it allots to the First Person. And it displays  1 Berth Reserved for First Person.
Then it enters try{} block inside tun() method, where it will sleep for 1.5 seconds.  In this time the ticket

will be printed on the printer.  When the first thread is sleeping, thread t2 also enters the run() method, it

also sees that there is 1 berth remaining.  The reason is, the available berths is not updated by thread t1.

So the second thread also sees 1 berth is available. And it allots the same berth to the Second Person also.

Then the thread t2 will also go into sleep state.

Thread t1 wakes up first, and then it updates the available number of berths as:
available=available - wanted;
Now available number of berths will become 0.  But the Second thread t2 has already allotted the same

berth to the Second Person also.  Since the both the threads are acting on the same object simultaneously,

the result is unreliable. (The solution is Synchronization).

*/

----------------------------------------------------------------------------------
Thread Synchronization:
------------------------------------
When a thread is already acting on an object, preventing any other thread from acting on the same object

is called 'Thread Synchronization' or 'Thread Safe'.  The object on which the threads are synchronized is

called 'synchronized object'.  Thread synchronization is recommended when multiple threads are used on

same object(in multithreading).

syntax:

synchronized(object)
{
statements;
}

eg:

synchronized void display()
{
statements;
}
------------------
Example IX
---------------------------------------------------------------------------
//Multiple Threads Acting on Single Object using Synchornization

class Reserve implements Runnable
{
int available=1;
int wanted;

Reserve(int i)
{
wanted=i;
}
public void run()
{

synchronized(this)
{
                   System.out.println("Available Berths= "+ available);

if(available >= wanted)
{
String name=Thread.currentThread().getName();
System.out.println(wanted +" Berth reserved for " + name);
try
{
Thread.sleep(1500);
available=available - wanted;
}
catch(InterruptedException ex)
{}

}

else
{
System.out.println("Sorry, no berths..");
}

}
}
}

class SynchronizeDemo
{
public static void main(String args[])
{
Reserve obj=new Reserve(1);

Thread t1=new Thread(obj);
Thread t2=new Thread(obj);

t1.setName("First Person");
t2.setName("Second Person");

t1.start();
t2.start();
}

}
-----------------------------------------------------------------------------------
Thread Priorities
--------------------------------------------------------------
Example X
----------------------------------------------------------------------------------------
class Demo extends Thread
{
int count=0;
public void run()
{
for(int i=1;i<=10000;i++)

count++;
System.out.println("\nCompleted Thread: "+Thread.currentThread().getName());
System.out.println("Its Priority is "+Thread.currentThread().getPriority());
}
}

class ThreadPriority
{
public static void main(String args[])
{
System.out.println("Default Thread Priorities\n-------------------------");
System.out.println("Minimum Priority of Thread is "+Thread.MIN_PRIORITY);
System.out.println("Maximum Priority of Thread is "+Thread.MAX_PRIORITY);
System.out.println("Normal Priority of Thread is "+Thread.NORM_PRIORITY);

Demo obj=new Demo();

Thread t1=new Thread(obj,"First Thread");
Thread t2=new Thread(obj,"Second Thread");

t1.setPriority(2);
t2.setPriority(Thread.NORM_PRIORITY);

t1.start();
t2.start();
}
}
----------------------------------------------------------------------------------------
Example XI
----------------------------------
//Suspending, Resuming and Stopping Threads

class NewThread implements Runnable
{
String name;
Thread t;

NewThread(String tname)
{
name=tname;
t=new Thread(this, name);
System.out.println("New Thread: "+t);
t.start();
}

public void run()
{
try
{
for(int i=15;i>0;i--)
{
System.out.println(name + ": " + i);
Thread.sleep(200);
}
}
catch(InterruptedException e)
{
System.out.println(name + " Interrupted.");
}
System.out.println(name + " exiting ");
}
}

class ResumeSuspend
{
public static void main(String args[])
{
NewThread obj1=new NewThread("one");
NewThread obj2=new NewThread("two");

try
{
Thread.sleep(1000);
obj1.t.suspend();
System.out.println("Suspending Thread One");
Thread.sleep(1000);
obj1.t.resume();
System.out.println("Resuming Thread One");

obj2.t.suspend();
System.out.println("Suspending Thread Two");
Thread.sleep(1000);
obj2.t.resume();
System.out.println("Resuming Thread Two");
}
catch(InterruptedException e)
{
System.out.println("Main Thread Interrupted..");
}

try
{
System.out.println("Waiting for Threads to finish.");
obj1.t.join();
obj2.t.join();
}
catch(InterruptedException e)
{
System.out.println("Main Thread Interrupted..");
}
System.out.println("Main Thread Interrupted.."); }
}

-----------------------------------------------------------------------------------
Example XII
------------------------------------------

//Using Join and isAlive Methods

/*
isAlive()
----------
The isAlive() method returns true if the thread upon which it is called is still running. Otherwise it returns

false.
 eg: final boolean isAlive()


*/
class NewThread implements Runnable
{
String name;
Thread t;

NewThread(String tname)
{
name=tname;
t=new Thread(this, name);
System.out.println("New Thread: "+t);
t.start();
}

public void run()
{
try
{
for(int i=15;i>0;i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(name + " Interrupted.");
}
System.out.println(name + " exiting ");
}
}

class JOinIsalive
{
public static void main(String args[])
{
NewThread obj1=new NewThread("One");
NewThread obj2=new NewThread("Two");
NewThread obj3=new NewThread("Three");

System.out.println("Thread One is alive: "+obj1.t.isAlive());
System.out.println("Thread Two is alive: "+obj2.t.isAlive());
System.out.println("Thread Three is alive: "+obj3.t.isAlive());

try
{
System.out.println("Waiting for Threads to Finish..");
obj1.t.join();
obj2.t.join();
obj3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Main Thread Interrupted");
}
System.out.println("Thread One is alive: "+obj1.t.isAlive());
System.out.println("Thread Two is alive: "+obj2.t.isAlive());
System.out.println("Thread Three is alive: "+obj3.t.isAlive());

System.out.println("Main Thread Exiting..");
}
}
--------------------------------------------------------------------------------------------
Ready    :
------------
 A thread does not immediately start running after it is  created; rather, it is in a ready to run state. It

waits for its start() method to be called.

Running :
-------------
The thread enters the running state when it start  executing. It starts running as soon as it gets the CPU

time

Sleeping :
------------
The execution of the thread can be halted temporarily for a period of time with the help of sleep() method.

The thread becomes ready  after the sleep time expires.

Waiting  :
------------
 Wait() causes the calling thread to sleep until it is interrupted with Thread.interrupt(),
the specified timeout elapses, or another thread wakes it up with notify() or
notifyAll().

Blocked :
------------
The thread enters a blocked stage when it waits for an event such as input/output operations.

Dead :
--------
 The thread enters a dead state after the run() method has finished execution. The thread should end on its

own by having a  run() method that terminates naturally.


===========================================================




===========================================================
String represents group of characters.

In C, C++ languages, a string represents an array of characters, where the last character being '\0'

represents the end of the string. But this is not valid in Java, a string is an object of String class.  It is not

a character array.  In java, we got character array also, but strings are given a different treatment

because of their extensive use on internet.  JavaSoft people have created a class separately with the name

'String' in java.lang(language) package with all necessary methods to work with strings.

Even though, String is a class, it is used often in the form of a data type
eg: String s="java";

Is String is class or datatype?

String is a class in java.lang package.   But in java, all classes are also considered as data

types.  So we can take String as a data type also.

Can we call a class as datatype?

Yes, a class is also called 'user-defined' data type.  This is because a user can create a class.

Creating Strings:
-----------------------
1.String S;
S="Hello";

2.String S="Hello";

3.String S=new String("Hello");

Character Array( to String object):
--------------------------------------------
char arr[]={'A','P','T','E','C','H'};

String S=new String(arr);

String S=new String(arr,2,4);


Example:I
----------------

//Using charAt()
//It returns character at given index
class A56
{
public static void main(String args[])
{
//charAt()
String empname=new String();
empname = "aptech computers";
System.out.println(empname.charAt(10));
}
}

//output is---   p

---------------------------------------------------------------------------------
Example II
-------------------------
//Using concat()
//It is used to concatinate  two given strings

class A57
{
public static void main(String args[])
{
String empname=new String();
empname = "Aptech";
System.out.println(empname.concat(" Grafx"));


}
}

--------------------------------------------------------------------------------
Example III
-------------------------------
//Using compareTo()
//It returns the difference between two given strins based on ASCII values

class A58
{
public static void main(String args[])
{

String empname=new String();
empname = "Aptech";

System.out.println(empname.compareTo("aptech"));


}
}

--------------------------------------------------------------------------------
Example IV
------------------------------------
class StrDemo1
{
public static void main(String a[])
{
String S1=new String("Hello");
String S2=new String("hello");

//compareTo()
int S=S1.compareTo(S2);
if(S==0)
{
System.out.println("Both are Same..Difference is: "+S);
}
else
{
System.out.println("Both not are Same..The difference is: "+S);
}


//compareToIgnoreCase()
int SS=S1.compareToIgnoreCase(S2);
System.out.println("The Result of compareToIgnoreCase() is Both are Same: "+SS);

//indexOf()

int x=S1.indexOf('l');
System.out.println("Index position of 'l' is: "+x);



}
}
---------------------------------------------------------------------------
Example V
-----------------------------------

class StrDemo3
{
public static void main(String a[])
{
String S1=new String("Hello");
String S2=new String("   Hello World    ");
System.out.println(S1.replace('H','Y'));
System.out.print(S2);
System.out.println(S1);
System.out.print(S2.trim());
System.out.println(S1);

}

}

---------------------------------------------------------------------------------
Example VI
-------------------------------------------

//Copying String to Character Array using getChars() method


class Strcpy
{
public static void main(String a[])
{
String str="Aptech Computer Education";
char arr[]=new char[20];

// copy from string to arr
str.getChars(7,15,arr,0);

System.out.println(arr);
}
}

//output is --   computer

---------------------------------------------------------------------------------
Example VII
-------------------------------------------
//using equals() method and == operator

class StrCmp
{
public static void main(String a[])
{
String s1="Hello";
//String s2="Hello";

String s2=new String("Hello");

//if(s1==s2)
if(s1.equals(s2))
{
System.out.println("Both are Same");
}
else
{
System.out.println("Not Same");
}


}
}


/* object reference:
-------------------------
Object reference is a unique hexadecimal number representing the memory adress of the object.  It is

useful to access the members of the object.

Difference between == and equals():
------------------------------------------------
== operator compares the references of the string objects.  It does not compare the contents of the objects.

equals() method compares the contents.  While comparing the strings, equals() method should be used as

it yields the correct result.

String constant pool:
----------------------------
String constant pool is a separate block of memory where the string objects are held by JVM.  If string

object is created directly, using assignment operator as: String s1="Hello", then is is stored in string

constant pool.



*/

---------------------------------------------------------------------------------
Example VIII
-------------------------------------------
//Using split()
//It Converts the string into pieces

class Strsplit
{
public static void main(String a[])
{
String str="Aptech Computer Education";
String s[];
s=str.split(" ");

for(int i=0; i<s.length; i++)
System.out.println(s[i]);
}
}

Output
-------------
Aptech
Computer
Education

---------------------------------------------------------------------------------
Example IX
-------------------------------------------
/*
Objects are divided into mutable and immutable.
Mutable Objects are those objects whose contents can be modified.

Immutable Objects are those objects, once created  can not be modified.

String class objects are immutable.*/

class StrImmut
{
public static void main(String a[])
{
String S1="Data";
String S2="Base";

S1=S1+S2;
System.out.println(S1);
}
}

---------------------------------------------------------------------------------
Example X
-------------------------------------------

/*
Differences between String and StringBuffer Class
------------------------------------------------------------------
String class objects are immutable, their contents cannot be modified.  StringBuffer class objects are

mutable, so they can modified.
*/
class StrBuff
{
public static void main(String a[])
{
StringBuffer sb=new StringBuffer("Data");
System.out.println(sb);

//append()
System.out.println(sb.append("Base"));

//indexOf()
int m=sb.indexOf("a");
System.out.println("The index position of 'a' is "+m);

//lastIndexOf()
int n=sb.lastIndexOf("a");
System.out.println("The last index position of 'a' is "+n);

//length()
System.out.println("The Length is " + sb.length());


//delete()
System.out.println("After Deleting: " + sb.delete(0,4));


//reverse()
System.out.println("The Reverse is " + sb.reverse());

//replace()
StringBuffer sb1=new StringBuffer("High Cost");
System.out.println(sb1.replace(0,4, "Low"));

//substring()
System.out.println("Substring of sb1 is: "+sb1.substring(4));

System.out.println("Substring of sb1 is: "+sb1.substring(0,3));
}
}

---------------------------------------------------------------------------------
Example XI
-------------------------------------------
//Palindrome or not

import java.io.*;

class StrBuff1
{
public static void main(String a[])throws IOException
{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter a String: ");
String str=br.readLine();
String temp=str;
StringBuffer sb=new StringBuffer(str);
sb.reverse();
System.out.println(sb);
str=sb.toString();
if(temp.equalsIgnoreCase(str))
{
System.out.println(temp+" is Palindrome");
}
else
{
System.out.println(temp+" is not a Palindorme");
}
}
}

---------------------------------------------------------------------------------
Example XII
-------------------------------------------
import java.io.*;

class StrBuff
{
public static void main(String a[]) throws Exception
{
StringBuffer sb=new StringBuffer();

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Surname: ");
String sur=br.readLine();
System.out.print("Enter middle name: ");
String mid=br.readLine();
System.out.print("Enter Last Name: ");
String last=br.readLine();

//append
sb.append(sur +" ");
sb.append(last+ " ");
System.out.println("Name: "+sb);

//insert
int n=sur.length();
sb.insert(n,mid+" ");

System.out.println("Full Name: "+sb);
System.out.println(" In reverse: "+sb.reverse());



}
}

---------------------------------------------------------------------------------
Example XIII
-------------------------------------------
class A59
{
public static void main(String args[])
{

StringBuilder  str=new StringBuilder("Java ");
System.out.println(str);

//append()
str.append("Progrmming Language");
System.out.println(str);

//insert()
str.insert(5,"is a ");
System.out.println(str);

//delete()
System.out.println(str.delete(5,9));

StringBuilder S1=new StringBuilder("Aptech");

//reverse()
System.out.println(S1.reverse());

//length()
System.out.println("The Length of S1 is "+S1.length());



}
}

---------------------------------------------------------------------------------
/*
Differences between StringBuffer and String Builder
----------------------------------------------------------------------
StringBuffer class is synchronized by default and StringBuilder class is not.  When the programmer wants

to use several threads, he should use StringBuffer as it gives reliable results.  If only one thread is used,

StringBuilder is preferred, as it improves execution time.

*/

Example XIV
-------------------------------------------
class A60
{
public static void main(String args[])
{

StringBuilder  str=new StringBuilder("Java Programming ");
str.insert(5," 6.0  ");
System.out.println(str);

}
}
---------------------------------------------------------------------------------
Example XV
-------------------------------------------

class A61
{
public static void main(String args[])
{
StringBuilder  str=new StringBuilder("Java Programming language 6.0");

System.out.println("Before Deletion :"+str);
str.delete(12,16);    //deleting “ming"
System.out.println("After Deletion :"+str);
}
}





//import java.lang.String.*;
class StrDemo
{
public static void main(String args[])
{
String s1="A book on Java  ";
String s2=new String("I like it ");
char arr[]={'C','o','m','p','l','e','t','e',' ','r','e','f'};
String s3=new String(arr);

System.out.println(s1);
System.out.println(s2);
System.out.println(s3);

System.out.println("Length of S1: "+ s1.length());
System.out.println("S1 and S2 joined: " + s1.concat(s2));
System.out.println(s1 + "from " + s3);

boolean x = s1.startsWith("A");

if(x)
{
System.out.println("s1 starts with 'A'");
}
else
{
System.out.println("s1 does not start with 'A'");
}

String p= s2.substring(0,7);
System.out.println(p);
String q= s3.substring(0,11);
System.out.println(q);
System.out.println(p+q);
System.out.println("Upper s1= "+s1.toUpperCase());
System.out.println("Lower s2= "+s2.toLowerCase());


}
}

==========================================================================
COLLECTIONS IN JAVA
==========================================================================

Inconveniencies of Arrays:
----------------------------------
1. Array can store only one datatype of elements.
2. Adding the objects at the end of an array is easy.  But inserting and deleting the elements in the middle

of array is difficult.

Collections or Collection Framework:
------------------------------------------------

Collection represents a group of objects, known as its elements. This framework is provided in

the java.util package. Objects can be stored, retrieved, and manipulated as elements of collections.

Collection is a Java Interface. Collections can be used in various scenarios like Storing phone numbers,

Employee names database etc. They are basically used to group multiple elements into a single unit. Some

collections allow duplicate elements while others do not. Some collections are ordered and others are not.

Interface Type Implementation Classes
------------------- -------------------------------
Set<T> HashSet<T>
LinkedHashSet<T>

List<T> Stack<T>
LinkedList<T>
ArrayList<T>
Vector<T>

Queue<T> LinkedList<T>


Map<K,V> HashMap<K,V>
Hashtable<K,V>

Sets:
------
A set represents a group of elements arranged just like an array.  The set will grow dynamically

when the elements are stored into it.  A set will not allow duplicate elements.  If we try to pass the same

element that is already available in the set, then it is not stored into the set.

Lists:
-------
Lists are like sets.  They store a group of elements.  But lists allow duplicate values to be

stored.

Queues:
-----------
A Queue represents arrangement of elements in FIFO(First In First Out) order.  This means

that an element that is stored as a first element into the queue will be removed first from the queue.

Maps:
--------
Maps store elements in the form of key and value pairs.  If the key is provided then its

corresponding value can be obtained.  But key should be unique.

The 'elements' refer to 'objects' only.  This means we cannot store primitive data types in the

collection objects.  We can store only objects.

How to Retrieve Elements from Collections:
--------------------------------------------------------
Using for-each loop.
Using Iterator interface.
Using ListIterator interface.
Using Enumeration interface.

1.for-each loop:
===========
for-each loop is like a for loop which repeatedly executes a group of statements for each

elements of the collection.

Syntax:
---------
for(variable : collection-object)
{
Statements;
}

2.Iterator interface:
===============
Iterator is an interface that contains methods to retrieve the elements one by one from a

collection object.  It has 3 methods.

boolean hasNext()
-----------------------
It returns true if the iterator has more elements.

element next():
-------------------
This method returns the next element in the iterator.

void remove():
------------------
This method removes from the collection the last element returned by the iterator.

 3.ListIterator Interface:
==================
It is an iterface.  It contains methods to retrieve the elements from a collection object, both in forward and

reverse directions.

boolean hasNext():
-----------------------
It returns true if the ListIterator has more elements when traversing the list in the reverse direction.

element next():
-------------------
It returns the next element in the list.

element previous():
------------------------
It returns the previous element in the list.

void remove():
-----------------
It removes from the list the last element that was returned by the next() or previous() methods.

4.Enumeration Interface:
===================
This interface is useful to retrieve one by one the elements like the Iterator.  It has 2 methods.

boolean hasMoreElements():
-------------------------------------
This method tests if the Enumeration has any more elements or not.

element nextElement():
-----------------------------
This returns the next element that is available in Enumeration.


Difference between Iterator and ListIterator:
=================================
Both are used to retrieve elements from a collection.  Iterator can retrieve the elements only in forward

direction.  But ListIterator can retrieve the elements in forward and backward direction also.

Difference between Iterator and Enumeration:
==================================
Both are useful to retrieve elements from a collection.  Iterator has methods whose names are easy to

follow and Enumeration methods are difficult to remember.  Iterator has an option to remove elements

from the collection which is not available in Enumeration.


HashSet class:
==========
A HashSet represents a set of elements(objects).  It does not guarantee the order of elements and also it

does not allow the duplicate elements to be stored.

eg:

1. class HashSet

2. class HashSet<T>

<T> represents the generic type parameter.  It represents which type of elements are being

stored into the HashSet.


Methods of HashSet Class:
===================
i. boolean add(obj)
------------------------
This method adds an element obj to the HashSet.  It returns true if element is added.  Otherwise it returns

false, if same eleement is already stored. Present element is not added.

ii. boolean remove(obj):
-------------------------------
It removes an element.  It returns true if the element is removed successfully.  Othewise it returns false.

iii. void clear():
-------------------
It removes all elements from HashSet.




Example on HashSet class:
-------------------------------------------------

import java.util.*;


class HashSetDemo
{
public static void main(String args[])
{

//HashSet hs=new HashSet();

HashSet<String> hs=new HashSet<String>();
hs.add("C");
hs.add("C++");
hs.add(".Net");
hs.add("Java");
hs.add("PHP");
hs.add("C");

System.out.println("Hash Set= "+hs);

Iterator it=hs.iterator();

System.out.println("Elements using Iterator");
while(it.hasNext())
{
String s=(String)it.next();
System.out.println(s);
}
}
}


-----------------------------------------------------------------------------------------------------

LinkedHashSet Class:
================
It is subclass of HashSet class and does not contain any additional members on its own.  It is a generic

class.


Stack Class:
=========
A Stack represents a group of elements stored in LIFO( Last-In-First-Out) order. The elements

which is stored as a last element into the stack removed first.  Inserting elements(objects) into stack is

called 'push' operation and removing elements from stack is called 'pop' operation.  Insertion and

deletion of elements take place only from one side of the stack, called 'top' of the stack.

Stack Class Methods:
===============
i. boolean empty():
-----------------------
This method tests the whether the stack is empty or not.  If stack is empty, it returns true otherwise false.

ii. element peek():
-----------------------
THis methods rtruns the top-most object from the stack without removing it.

iii. element pop():
----------------------
This method pops the top-most object from the stack without removing it.

iv. element push(element obj):
---------------------------------------
This method returns the position of an element obj from the top of the stack.  If the element(object) is not

found in the stack then it returns -1.

Auto boxing:
----------------
Converting a primitive data type into an object form automatically is called 'auto boxing'.  Auto boxing is

done in generic types.

Example of Stack Class:-
---------------------------------

import java.util.*;

public class StackImplementer
{
public static void main(String a[])
{
Stack bag=new Stack();
bag.push("one");
bag.push("two");
bag.push("three");
bag.push("four");
System.out.println("Top of Bag [Stack] : " + bag.peek());

while(!bag.empty())
{
System.out.println(bag.pop());
}
}
}

----------------------------------------------------------------------------------------------------------------------

ArrayList Class:
=============
An ArrayList is like an array, which can grow in memory dynamically.  We can store elements

into ArrayList, depending on the number of elements.  The memory is dynamically allotted and re-allotted

to accommodate all the elements.  ArrayList is not synchronized.    This means that when more than one

thread acts simultaneously on the ArrayList object,  the result may be incorrect in some cases.

ArrayList Class Methods:
====================
i. boolean add(element obj):
-----------------------------------
It appends the specified element to the end of the ArrayList. And returns true.

ii. void add(int position, element obj):
------------------------------------------------
This method inserts the specified element at the specified position in the ArrayList.

iii. element remove(int position):
-----------------------------------------
This method removes the specified element at the specified position in the ArrayList.

iv. boolean remove(Object obj):
---------------------------------------
This method removes the first occurrence of the specified element obj from the ArrayList, if it is present.

v. void Clear():
-------------------
This method removes all elements from the ArrayList.

vi. element set(int position, element obj):
------------------------------------------------------
This method replaces an element at the specified position in the ArrayList with the specified eleement obj.

vii. boolean contains(Object obj):
------------------------------------------
This method returns true if the ArrayList contains the specified element obj.

viii. element get(int position):
-------------------------------------
This method returns true if the ArrayList contains the specified element obj.

ix. int indexOf(Object obj):
------------------------------------
This method returns true if the ArrayList contains the specified element obj.

x. int lastIndexOf(Object obj):
---------------------------------------
This method returns the position of the first occurrence of the specified element obj in the list, or -1 if the

element is not found in the list.

xi. int size():
---------------
This method returns an Object class type array containing all the elements in the ArrayList in proper

sequence.


Example of ArrayList:
------------------------------

import java.util.*;

class ArrayListDemo
{
public static void main(String args[])
{

ArrayList<String> arl=new ArrayList<String>();

arl.add("Apple");
arl.add("Mango");
arl.add("Grapes");
arl.add("Guava");

System.out.println("Array Elements"+arl);

arl.remove(3);
arl.remove("Apple");
System.out.println("Array Elements"+arl);

System.out.println("Array Size is "+arl.size());

System.out.println("Extracting elements using Iterator");

Iterator it=arl.iterator();

while(it.hasNext())
{
System.out.println(it.next());
}


}
}




Vector Class:
==========
A Vector also stores elements (objects) similar to ArrayList, but Vector is synchronized.  It

means even if several threads act on Vector object simultaneously, the results will be reliable.

Example of Vector Class:
-----------------------------------

import java.util.*;

public class VectorImplementation
{
public static void main(String arg[])
{
Vector vect=new Vector();
vect.addElement("C");
vect.addElement("C++");
vect.addElement(".Net");
vect.addElement("Adv Java");
vect.addElement("PHP");
vect.insertElementAt("--------",0);

System.out.println("Size: "+vect.size());
System.out.println("Vector");

for(int i=0;i < vect.size(); i++)
{
System.out.println(vect.elementAt(i) );
}

vect.insertElementAt("Core Java",4);


System.out.println(" ");
System.out.println("Size : "+vect.size());
System.out.println("Vector\n ");

for(int i=0; i < vect.size(); i++)
{
System.out.println(vect.elementAt(i) );
}

vect.removeElement("PHP");
System.out.println("After Removing\n");
for(int i=0; i < vect.size(); i++)
{
System.out.println(vect.elementAt(i) );
}
         }
}


-----------------------------------------------------------------------------------------------------------------------


HashMap Class:
============
HashMap is a collection that stores elements in the form of key-value pairs.  If key is provided later, its

corresponding value can be easily retrieved from the HashMap.  Keys should be unique.  HashMap is not

synchronized and hence while using multiple threads on HashMap object, we get unreliable results.

Example of List, Set and Map:
---------------------------------------

import java.util.*;

public class CollectionsDemo {

   public static void main(String[] args) {
      List a1 = new ArrayList();
      a1.add("Krishna");
      a1.add("Varma");
      a1.add("Sangeeta");
      System.out.println(" ArrayList Elements");
      System.out.print("\t" + a1);

      List l1 = new LinkedList();
      l1.add("Sri Lakshmi");
      l1.add("Sagarika");
      l1.add("Pavani");
      System.out.println();
      System.out.println(" LinkedList Elements");
      System.out.print("\t" + l1);

      Set s1 = new HashSet();
      s1.add("Teja");
      s1.add("Haindavi");
      s1.add("Siva Ram");
      System.out.println();
      System.out.println(" Set Elements");
      System.out.print("\t" + s1);

      Map m1 = new HashMap();
      m1.put("Anil", "8");
      m1.put("Ajay", "31");
      m1.put("Akshy", "12");
      m1.put("Anand", "14");
      System.out.println();
      System.out.println(" Map Elements");
      System.out.print("\t" + m1);


   
   }
}


-------------------------------------------------------------------------------------------------------------------------


Hashtable Class:
============
Hashtable is similar to HashMap which can store elements in the form of key-value pairs.  But Hashtable

is synchronized assuring porper results even if multiple threads act on it simultaneously.

eg: class Hashtable<k,v>

Example of Hashtable:
------------------------------

import java.util.*;

public class HashTableImplementer
{
public static void main(String arg[])
{

Hashtable ht=new Hashtable();

ht.put(101,"Scott");
ht.put(102,"Tiger");
ht.put(103,"James");
ht.put(104,"Smith");

System.out.println("Initially: " + "\n" + ht.toString());
System.out.println("After Removing");
ht.remove("Scott");
System.out.println(ht.toString());
}
}

------------------------------------------------------------------------------------------------------------------------

There k represents the type of key element and v represents the type of value element.

Properties:
========
The Properties class extends the Hashtable and adds the capability to read and write a Hashtable.  It is a

sub class of Hashtable.

Example of Properties Class:
-------------------------------------

import java.util.*;

public class PropertiesImplementer
{
public static void main(String a[])
{
Properties p=System.getProperties();
p.list(System.out);
}
}
----------------------------------------------------------------------------------------------------------------------

StringTokenizer Class:
=================
This class is useful to  break a string into pieces, called "tokens.  These tokens are stored in

StringTokenizer object.

StringTokinizer Class:
================
int countTokens():
-----------------------
This method counts and returns the number of tokens available in a StringTokenizer object.

boolean hasMoreTokens():
----------------------------------
It tests if there are more tokens available in the StringTokenizer object or not.  If next token is there then

it returns true or false.

String nextToken():
-------------------------
This method returns the next token from the StringTokenizer.


Example of StringTokinizer Class:
--------------------------------------------

import java.util.*;

public class StringTokenizerDemo
{
public static void main(String a[])
{
String str = "Father of the JAVA is JAMES GOSLING";
System.out.println("Given String: "+str);

StringTokenizer  st=new StringTokenizer(str);

int count= st.countTokens(); //count the Tokens

System.out.println("\nNumber of Tokens :  "+count);


System.out.println("\nThe Tokens are\n--------------");
while(st.hasMoreTokens())
{
String one=st.nextToken();
System.out.println(one);
}
}
}

---------------------------------------------------------------------------------------------------------------

Calendar Class:
============

1. It helps in knowing the system date and time.
2. It helps in storing a date and time value so that it can be transported to some other application.

eg:
Calendar C =new Calendar.getInstance();


Methods of Calendar Class:
------------------------------------
i. int get(int field):
-----------------------
This method returns the value of the given Calendar field.

ii. Calendar.DATE:
-------------------------
Gives the date number from 1 to 31.

iii. Calendar.MONTH:
-----------------------------
Gives the month number from 0 to 11( January taken as 0).

iv. Calendar.YEAR:
--------------------------
Gives the year.

v. Calendar.HOUR:
-------------------------
Gives the hour number from 0 to 11.

vi. Calendar.MINUTE:
-----------------------------
Gives the  minutes from 0 to 59.

vii. Calendar.SECOND:
-------------------------------
Gives the  seconds from 0 to 59.

viii. Calendar.AM_PM:
------------------------------
Gives 0, if it is AM, 1 if it is PM.

ix. void set(int field, int value):
--------------------------------------
We can set our own date.




Example of Calendar Class:
-----------------------------------------
import java.util.*;

class CalendarDemo
{
public static void main(String args[])
{
Calendar C1=Calendar.getInstance();

/*C1.set(Calendar.DATE,15);
C1.set(Calendar.MONTH,9);
C1.set(Calendar.YEAR,2000);   */


System.out.print("Current Date: ");
int dd=C1.get(Calendar.DATE);
int mm=C1.get(Calendar.MONTH);
mm++;
int yy=C1.get(Calendar.YEAR);
System.out.print(dd + "-" + mm + "-" + yy);

System.out.print("\nCurrent Time: ");
int h=C1.get(Calendar.HOUR);
int m=C1.get(Calendar.MINUTE);
int s=C1.get(Calendar.SECOND);
System.out.print(h + ":" + m + ":" + s);

int x=C1.get(Calendar.AM_PM);
if(x==0)
{
System.out.println("\n Good Morning.");
}
else
{
System.out.println("\n Good Evening.");
}


}
}
--------------------------------------------------------------------------------------------------------

Date Class:
==========
Date class is useful to display the date and time at a particular moment.  When we create an object to

Date class, it contains system date and time by default.

DateFormat.FULL
DateFormat.MEDIUM
DateFormat.LONG
DateFormat.SHORT

Locale.US
Locale.UK
Locale.KOREA
Locale.JAPAN etc.

Example of Date class:
---------------------------------

import java.util.*;
import java.text.*;

class DateDemo
{
public static void main(String args[])
{
Date d=new Date();

DateFormat fmt=DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.SHORT,

Locale.US);//UK

String str=fmt.format(d);
System.out.println(str);
}
}

=======================================================================
AWT in Java (Abstract Window Toolkit)
========================================================================

Abstract Window Toolkit (AWT) represents a class library to develop applications using GUI.

The Java.awt package contains all classes  for creating user interfaces and for painting ,graphics and

images.  It is a part of Java Foundation Classes(JFC).  A Graphical User Interface(GUI) is used to accept

inputs in a user-friendly manner.  A GUI may consist of textboxes, labels,  listboxes etc.  Different

programming languages provide different ways  to create a GUI application.  VB or .Net provide drag and

drop approach for creating GUI.

Containers:
----------------
A container object is a component that can contain  other AWT components.

Components:
------------------
A component is an object that has graphical  representation and can be displayed on the

screen.  It allows user interaction.

Window and Frame:
-------------------------
A window is a frame without any borders and title, whereas a frame  contains borders and title.

Event Delegation Model:
------------------------------
When we create a component, it displayed on the screen but it is not capable of performing any actions.

An event represents a specific action done on a component. Eg. Clickng, double clicking, mouse over etc.

When an event is generated on the component, the component will not know about it because it cannot

listen to the event.  So we should add some listener to the component.
A listener is an interface which listens to an event coming from a component.
A listener will have some abstract methods which need to be implemented by the programmer.

When an event is generated by the user on the component, the event is not handled by the

component.  On the other hand, the component sends (delegates) that event to the listener attached to it.

The listener will not handle the event.  It hands over(delegates) the event to an appropriate method.

Finally, the method is executed and the event is handled.  This is called ‘event delegation model’.

Layout Managers:
------------------------
A Layout manager defines the location and size of the  Graphical User Interface components.


Example:
-----------
import java.awt.*;
class A43
{
public static void main(String args[])
{
Frame f=new Frame("This is my First AWT Program");
f.setSize(200,200);
f.setVisible(true);
//f.setTitle("Frame Demo ");
System.out.println("press Ctrl+C ");
}
}

Example:
-----------
import java.awt.*;
class A44
{
public static void main(String args[])
{
Frame f=new Frame("This is my First AWT Program");
f.setSize(200,200);
f.setVisible(true);

TextField txt=new TextField();
f.add(txt);

Button btn=new Button("Show");
f.add(btn);


System.out.println("press Ctrl+C ");
}
}

Example:
-----------
import java.awt.*;
class A45
{
public static void main(String args[])
{
Frame f=new Frame("FirstFrame");
f.setSize(300,100);
f.setVisible(true);

Panel p=new Panel();
Label l=new Label("Enter Name");
TextField t=new TextField("aptech",10);
//t.setEchoChar('*');
//t.setText("aptech");
System.out.println(t.getText());
//System.out.println(t.getEchoChar());
Button b=new Button("Click Me");
//b.setLabel("Username");
//System.out.println(b.getLabel());

t.setForeground(Color.green);
t.setBackground(Color.red);

f.add(p);
p.add(l);
p.add(t);
p.add(b);
}
}

Example:
-----------
import java.awt.*;

class TestFrame extends Frame
{
TestFrame(String Title)
{
super(Title);
setBackground(Color.black);
setForeground(new Color(0,255,0));
setFont(new Font("Times New Roman",Font.BOLD+Font.ITALIC,36));
setSize(400,100);
setVisible(true);
}
public void paint(Graphics g)
{
g.drawString("APTECH",70,70);
}
}
class A46
{
public static void main(String args[])
{
new TestFrame("SampleWIndow");
}
}

Example:
-----------
import java.awt.*;
class A47 extends Frame
{
public void paint(Graphics g)
{
Font f=new Font("Helvetica",Font.BOLD,24);
g.setFont(f);
g.drawString("This is my Frame",75,100);
}
public static void main(String args[])
{
A47 f=new A47();
f.setSize(300,250);
f.setVisible(true);
}
}

Example:
-----------
//ListBox Demo
import java.awt.*;
class A48 extends Frame
{
//A48(String name)
A48()
{
//super(name);
Button b=new Button("Click");
List c=new List();
//c.setMultipleSelections(true);
c.add(".net");
c.add("Java");
c.add("PHP");
add("North",b);
add("South",c);
setVisible(true);
setSize(200,200);
setTitle("THis is ListBox");
}
public static void main(String args[])
{
A48 ld=new A48();
}
}

==============================================================================Layo

ut Managers:
==============================================================================

A layout manager is a class that is useful to arrange components in a particular manner in a

frame or container.

i. FlowLayout
ii. BorderLayout
iii. CardLayout
iv. GridLayout
v. GrdiBagLayout
vi. BoxLayout(In Swings Only)

i. FlowLayout:
===========
FlowLayout is useful to arrange the components in a line one after the other.  When a line is filled with

components, they are automatically placed in the next line.  This is default layout in applets and panels.

Example of FlowLayout:
----------------------------------

// FlowLayout Demo

import java.awt.*;
class FlowLayoutDemo extends Frame
{
FlowLayoutDemo()
{
FlowLayout obj=new FlowLayout(FlowLayout.CENTER,10,10);
setLayout(obj);
Button b1,b2,b3,b4;
b1=new Button("Button1");
b2=new Button("Button2");
b3=new Button("Button3");
b4=new Button("Button4");

add(b1);
add(b2);
add(b3);
add(b4);
}
public static void main(String args[])
{
FlowLayoutDemo demo = new FlowLayoutDemo();
demo.setSize(400,400);
demo.setTitle("Flow Layout");
demo.setVisible(true);
}
}

-----------------------------------------------------------------------------------------------

ii. BorderLayout:
=============
BorderLayout is useful to arrange the components in the 4 borders of the frame as well as in

the center.  The borders are identified with names of directions.  The top border is specified as 'North', the

right side border 'East', the bottom one as 'South' and the left one as 'West'.  The center is represented as

'Center'.

Example of BorderLayout:
--------------------------------

// FlowLayout Demo

import java.awt.*;
class FlowLayoutDemo extends Frame
{
FlowLayoutDemo()
{
FlowLayout obj=new FlowLayout(FlowLayout.CENTER,10,10);
setLayout(obj);
Button b1,b2,b3,b4;
b1=new Button("Button1");
b2=new Button("Button2");
b3=new Button("Button3");
b4=new Button("Button4");

add(b1);
add(b2);
add(b3);
add(b4);
}
public static void main(String args[])
{
FlowLayoutDemo demo = new FlowLayoutDemo();
demo.setSize(400,400);
demo.setTitle("Flow Layout");
demo.setVisible(true);
}

}
------------------------------------------------------------------------------------------------

iii. CardLayout:
============
A CardLayout object is a layout manager which treats each component as card.  Only one card

is visible at a time, and the container acts as a stack of cards.  The first component added to a CardLaout

object is the visible component when the container is first displayed.

Example of CardLayout:
-------------------------------

// CardLayout Demo

import java.awt.*;
import java.awt.event.*;

class CardLayoutDemo extends Frame implements ActionListener
{
CardLayout obj;
Button b1,b2,b3,b4;
CardLayoutDemo()
{
obj=new CardLayout(50,10);
setLayout(obj);

b1=new Button("Button1");
b2=new Button("Button2");
b3=new Button("Button3");
b4=new Button("Button4");

add("First Card",b1);
add("Second Card",b2);
add("Third Card",b3);
add("Fourth Card",b4);

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
obj.next();
}
public static void main(String args[])
{
CardLayoutDemo demo = new CardLayoutDemo();
demo.setSize(400,400);
demo.setTitle("Card Layout");
demo.setVisible(true);
}
}

-----------------------------------------------------------------------------------------

iv. GridLayout:
============
GridLayout is useful to divide the container into a two-dimensional grid form that contains

several rows and columns.  The container is divided into equal-sized rectangles, and one component is

placed in each rectangle.

Example of GridLayout:
==================

// GridLayoutDemo.java

import java.awt.*;

class GridLayoutDemo extends Frame
{
GridLayoutDemo()
{
GridLayout grid = new GridLayout(2,3,50,50);
setLayout(grid);

Button b1=new Button("Button1");
Button b2=new Button("Button2");
Button b3=new Button("Button3");
Button b4=new Button("Button4");
Button b5=new Button("Button5");


add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
}
public static void main(String args[])
{
GridLayoutDemo demo = new GridLayoutDemo();
demo.setSize(500,400);
demo.setTitle("Grid Layout");
demo.setVisible(true);
}
}

---------------------------------------------------------------------------------------------
v. GrdiBagLayout
=============
GridBagLayout class represents grid bag layout manager where the components are arranged in rows and

columns.  This layout is more flexible as compared to other layouts since in this layout, the components

can span more than one row or column and the size of the components can be adjusted to fit the display

area.  The intersection of rows and columns where a component can be placed is called a 'grid' or display

'area'.
=========================================================================



Events  and their Description:
======================
Event Classes
-------------------
ActionEvent:
-----------------
When a button is pressed, a list item is double clicked or a menu is selected.

AdjustmentEvent:
------------------------
When a scrollbar is used .

ComponentEvent:
----------------------
When a component is resized, moved, hidden or made visible.

FocusEvent:
----------------
When a component loses or gains keyboard focus.

ItemEvent:
--------------
When a menu item is selected or deselected or when a checkbox or list item.

WindowEvent:
-----------------
When a window is activated, closed, opened or quit.

TextEvent:
--------------
When the value of a text field or text area is change.

MouseEvent:
----------------
When mouse is moved, clicked, dragged or released.

KeyEvent:
--------------
When input is received from the keyboard.


The interfaces that are implemented to handle each of them are:
--------------------------------------------------------------------------------
ActionListener
AdjustmentListener
ComponentListener
FocusListener
ItemListener
WindowListener
TextListener
MouseListener
MouseMotionListener
KeyListener


ActionListener:
-------------------
void actionPerformed(ActionEvent ae)

Button, TextField, List and Menus.

ItemListener:
------------------
void itemStateChanged(ItemEvent ie)

Choices, Checkbox, menu etc.

AdjustmentListener:
-----------------------------
adjustmentValueChanged(AdjustmentEvent ae)

Scrollbar

TextListener:
-----------------
void textValueChanged(TextEvent ae)

ComponentListener:
---------------------------
componentResized(ComponentEvent ae)
componentMoved(ComponentEvent ae)
componentShown(ComponentEvent ae)
componentHidden(ComponentEvent ae)

WindowListener:
----------------------
windowActivated(WindowEvent ae)
windowClosed(WindowEvent ae)
windowClosing(WindowEvent ae)
windowDeactivated(WindowEvent ae)
windowDeiconified(WindowEvent ae)
windowIconified(WindowEvent ae)
windowOpened(WindowEvent ae)

FocusListener:
-------------------
focusLost(FocusEvent ae)
focusGain(FocusEvent ae)

ContainerListener:
------------------------
componentAdded(ContainerEvent ae)
componentRemoved(ContainerEvent ae)

KeyListener:
-----------------
keyPressed(KeyEvent ae)
keyReleased(KeyEvent ae)
keyTyped(KeyEvent ae)

MouseListener:
----------------------
mouseClicked(MouseEvent me)
mousePressed(MouseEvent me)
mouseReleased(MouseEvent me)
mouseEntered(MouseEvent me)
mouseExisted(MouseEvent me)

MouseMotionListener:
----------------------------
mouseMoved(MouseEvent me)
mouseDragged(MouseEvent me)


Example:
-----------
import java.awt.*;
import java.awt.event.*;

class ButtonEventDemo extends Frame implements ActionListener
{
ButtonEventDemo()
{

Frame frm=new Frame("Button Event Frame");
Panel pnl=new Panel();
Button btn=new Button("Click Me");

//Adding Event to the Button
btn.addActionListener(this);


frm.add(pnl);
pnl.add(btn);
frm.setVisible(true);
frm.setSize(300,200);
}


public void actionPerformed(ActionEvent ae)
{

System.out.println("Welcome to AWT Programming");
}

}
class A50
{
public static void main(String args[])
{

ButtonEventDemo B=new ButtonEventDemo();

}
}


Example:
-----------
import java.awt.*;
import java.awt.event.*;
class TestFrame extends Frame implements ItemListener
{
TextField UserName,Email;
Checkbox UseEmail;
TextField Password;

TestFrame()
{
super("Sample Window");
setLayout(new FlowLayout());
UserName = new TextField(20);
Email = new TextField(30);
Email.setEnabled(false);

Email.setBackground(Color.LIGHT_GRAY);
Password = new TextField(30);
Password.setEchoChar('*');
UseEmail = new Checkbox("use Email as UserName");
UseEmail.addItemListener(this);
add(new Label("UserName"));
add(UserName);
add(UseEmail);
add(Email);
add(new Label("Email ID"));
add(new Label("Password"));

add(Password);
setSize(400,100);
setVisible(true);
}
public void itemStateChanged(ItemEvent ie)
{
if(UseEmail.getState()==true)
{
UserName.setEnabled(false);
UserName.setBackground(Color.LIGHT_GRAY);
Email.setBackground(Color.WHITE);

Email.setEnabled(true);
Email.requestFocus();
}
else
{
UserName.setEnabled(true);
UserName.setBackground(Color.WHITE);
Email.setEnabled(false);
Email.setBackground(Color.LIGHT_GRAY);
UserName.requestFocus();
}
}
}
class A49
{
public static void main(String args[])
{
new TestFrame();
}
}




Example:
-----------
import java.awt.*;
import java.awt.event.*;
class MouseDemo extends Frame implements MouseListener
{

MouseDemo()
{
setSize(400,400);
setVisible(true);
setTitle("Example for MouseListener");
addMouseListener(this);
MyAdapterdemo a=new MyAdapterdemo();
addWindowListener(a);
}
public void mouseClicked(MouseEvent m1)
{
System.out.println("Mouse clicked");
}
public void mouseEntered(MouseEvent m2)
{
System.out.println("Mouse Entered");
}
public void mouseExited(MouseEvent m3)
{
System.out.println("Mouse Exited");
}
public void mousePressed(MouseEvent m4)
{
System.out.println("MousePressed");
}
public void mouseReleased(MouseEvent m5)
{
System.out.println("MouseReleased");
}


class MyAdapterdemo extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}

}
class A52
{

public static void main(String args[])
{
new MouseDemo();
}
}


Example:
-----------
import java.awt.*;
public class A53 extends Frame
{
public static void main(String args[])
{
Frame f=new Frame();
f.setTitle("choicedemo");
f.setSize(100,100);
f.setVisible(true);
Panel p=new Panel();
f.add(p);
Choice ch=new Choice();
ch.addItem("India");
ch.addItem("Russia");
ch.addItem("Japan");
p.add(ch);
}
}



Example:
-----------
import java.awt.*;
import java.awt.event.*;
class MousemotionDemo extends Frame implements MouseMotionListener
{
MousemotionDemo()
{
setVisible(true);
setTitle("MousemotionExample");
addMouseMotionListener(this);
setSize(200,200);
}
public void mouseDragged(MouseEvent me)
{
System.out.println("Mouse dragged to :"+me.getX()+","+me.getY());
}
public void mouseMoved(MouseEvent me)
{
System.out.println("Mouse moved to :"+me.getX()+","+me.getY());
}


}
class A54
{
public static void main(String args[])
{
new MousemotionDemo();
}
}


Example:
-----------
Using ScrollBar
=========================
import java.awt.*;
import java.awt.event.*;

class MyScroll extends Frame implements AdjustmentListener
{
String msg="";
Scrollbar s1;

MyScroll()
{
setLayout(null);
s1=new Scrollbar(Scrollbar.VERTICAL,0,30,0,400);
s1.setBounds(250,50,30,200);

add(s1);

s1.addAdjustmentListener(this);

addWindowListener(new WindowAdapter()
  {
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
repaint();
}
public void paint(Graphics g)
{
g.drawString("SCROLLBAR POSITION: ",20,150);
msg+=s1.getValue();
g.drawString(msg,20,180);
msg="";
}
public static void main(String args[])
{
MyScroll ms = new MyScroll();
ms.setTitle("My Scroolbar");
ms.setSize(400,400);
ms.setVisible(true);
}
}

===============================

Using  List Box
===========================
import java.awt.*;
import java.awt.event.*;

class MyList extends Frame implements ItemListener
{
int[] msg;
List lst;

MyList()
{
setLayout(new FlowLayout());
lst=new List(4,true);

lst.add("English");
lst.add("Hindi");
lst.add("Telugu");
lst.add("Sanskrit");
lst.add("French");

add(lst);

lst.addItemListener(this);

addWindowListener(new WindowAdapter()
  {
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
g.drawString("Select Language: ",100,200);
msg=lst.getSelectedIndexes();

for(int i=0;i<msg.length;i++)
{
String item=lst.getItem(msg[i]);
g.drawString(item,100,220+i*20);
}
}
public static void main(String args[])
{
MyList ml = new MyList();
ml.setTitle("My List box");
ml.setSize(400,400);
ml.setVisible(true);
}
}

===================================

Using  Choice
=========================
import java.awt.*;
import java.awt.event.*;

class MyChoice extends Frame implements ItemListener
{
String msg;
Choice ch;

MyChoice()
{
setLayout(new FlowLayout());
ch=new Choice();

ch.add("English");
ch.add("Hindi");
ch.add("Telugu");
ch.add("Sanskrit");
ch.add("French");

add(ch);

ch.addItemListener(this);

addWindowListener(new WindowAdapter()
  {
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
g.drawString("Select Language: ",10,100);
msg=ch.getSelectedItem();
g.drawString(msg,10,120);
}
public static void main(String args[])
{
MyChoice mc = new MyChoice();
mc.setTitle("My Choice box");
mc.setSize(400,350);
mc.setVisible(true);
}
}

===============================


Using TextField and Label
==========================

import java.awt.*;
import java.awt.event.*;

class MyText extends Frame implements ActionListener
{
TextField name,pwd;

MyText()
{
setLayout(new FlowLayout());

Label n=new Label("User Name: ",Label.LEFT);
Label p=new Label("Password: ", Label.LEFT);

name=new TextField(10);
pwd=new TextField(10);
pwd.setEchoChar('*');

name.setBackground(Color.yellow);
name.setForeground(Color.green);
Font f=new Font("Arial", Font.PLAIN,25);
name.setFont(f);
pwd.setBackground(Color.yellow);
pwd.setForeground(Color.green);
//Font f=new Font("Arial", Font.PLAIN,25);
pwd.setFont(f);

add(n);
add(name);
add(p);
add(pwd);

name.addActionListener(this);
pwd.addActionListener(this);

addWindowListener(new WindowAdapter()
    {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
    });

}

public void actionPerformed(ActionEvent ae)
{
Graphics g=this.getGraphics();

g.drawString("Name:  "+name.getText(), 10, 200);
g.drawString("Password: "+pwd.getText(),10,240);
}

public static void main(String args[])
{
MyText mt=new MyText();
mt.setTitle("Hai");
mt.setSize(300,300);
mt.setVisible(true);
}
}




======================================================


Using Checkboxes:
===============

//CheckBox Demo

import java.awt.*;
import java.awt.event.*;

class MyCheckbox extends Frame implements ItemListener
{
String msg="";
Checkbox c1,c2,c3;

MyCheckbox()
{
setLayout(new FlowLayout());

c1=new Checkbox("Bold",true);
c2=new Checkbox("Italic");
c3=new Checkbox("Underline");

add(c1);
add(c2);
add(c3);

c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);

addWindowListener(new WindowAdapter()
    {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
    });

}

public void itemStateChanged(ItemEvent ie)
{
repaint();
}

public void paint(Graphics g)
{
g.drawString("Current State\n-------------",10,100);
msg="Bold: " + c1.getState();
g.drawString(msg, 10, 120);
msg="Italic: " + c2.getState();
g.drawString(msg, 10, 140);
msg="Underline: " + c3.getState();
g.drawString(msg, 10, 160);
}

public static void main(String args[])
{
MyCheckbox ch=new MyCheckbox();
ch.setTitle("CheckBox Demo");
ch.setSize(400,400);
ch.setVisible(true);
}
}


==========================================================
Using Radiobuttons
===========================

import java.awt.*;
import java.awt.event.*;

class Myradio extends Frame implements ItemListener
{
String msg="";
CheckboxGroup cbg;
Checkbox y,n;

Myradio()
{
setLayout(new FlowLayout());

cbg=new CheckboxGroup();

y=new Checkbox("Yes",cbg,true);
n=new Checkbox("No",cbg,false);

add(y);
add(n);

y.addItemListener(this);
n.addItemListener(this);

addWindowListener(new WindowAdapter()
    {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
    });

}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}

public void paint(Graphics g)
{
msg="Current Selection: ";
msg+= cbg.getSelectedCheckbox().getLabel();
g.drawString(msg, 10, 100);
}

public static void main(String args[])
{
Myradio M=new Myradio();
M.setTitle("My RadioButtons");
M.setSize(400,400);
M.setVisible(true);
}
}

==========================================================


// Knowing the available fonts

import java.awt.*;

class Fonts
{
public static void main(String args[])
{
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();

String fonts[]=ge.getAvailableFontFamilyNames();
System.out.println("Available Fonts on this System");

for(int i=0;i<fonts.length;i++)
{
System.out.println(fonts[i]);
}
}
}

--------------------------------------------------------------------------------------------------

Drawing Face:
-----------------------
import java.awt.*;
import java.awt.event.*;

class Draw1 extends Frame
{
Draw1()
{
                         this.addWindowListener(new WindowAdapter()
    {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
    });
}

public void paint(Graphics g)
{
g.setColor(Color.green);

g.drawRect(40,40,200,200);

//face
g.drawOval(90,70,80,80);

//eyes
g.drawOval(110,95,5,5);
g.drawOval(145,95,5,5);

//nose
g.drawLine(130,95,130,115);

//mouth
g.drawArc(113,115,35,20,0,-180);

}
public static void main(String args[])
{
Draw1 d=new Draw1();
d.setSize(400,400);
d.setTitle("My Drawing");
d.setVisible(true);
}
}

-----------------------------------------------------------------------------------------------
Filling face with colors
-------------------------------------------

import java.awt.*;
import java.awt.event.*;

class Draw2 extends Frame
{
Draw2()
{
                         this.addWindowListener(new WindowAdapter()
    {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
    });
}

public void paint(Graphics g)
{
g.setColor(Color.blue);

g.fillRect(40,40,200,200);

g.setColor(Color.yellow);
g.drawOval(90,70,80,80);

//face
g.fillOval(90,70,80,80);

g.setColor(Color.black);
//eyes
g.fillOval(110,95,5,5);
g.fillOval(145,95,5,5);

//nose
g.drawLine(130,95,130,115);

//mouth
g.setColor(Color.red);
g.fillArc(113,115,35,20,0,-180);

}
public static void main(String args[])
{
Draw2 d=new Draw2();
d.setSize(300,300);
d.setTitle("My Drawing");
d.setVisible(true);
}
}




-----------------------------------------------------------------------------------
Using Buttons with setBounds Method
--------------------------------------------------------
import java.awt.*;
import java.awt.event.*;

class Mybutton extends Frame implements ActionListener
{
Button b1,b2,b3;

Mybutton()
{
this.setLayout(null);

b1=new Button("Yellow");
b2=new Button("Green");
b3=new Button("Red");

b1.setBounds(100,100,70,40);//(x,y,width,height)
b2.setBounds(100,160,70,40);
b3.setBounds(100,220,70,40);



this.add(b1);
this.add(b2);
this.add(b3);


b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});

}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();

if(str.equals("Yellow"))this.setBackground(Color.yellow);
if(str.equals("Green"))this.setBackground(Color.green);
if(str.equals("Red"))this.setBackground(Color.red);

}
public static void main(String args[])
{
Mybutton mb=new Mybutton();
mb.setSize(400,400);
mb.setTitle("MyButtons");
mb.setVisible(true);
}
}

-----------------------------------------------------------------------------------
Displaying Image:
---------------------------------------------------
import java.awt.*;
import java.awt.event.*;

class ImageDemo extends Frame
{
static Image img;

ImageDemo()
{
img=Toolkit.getDefaultToolkit().getImage("e.gif");
MediaTracker track=new MediaTracker(this);

track.addImage(img,0);

try
{
track.waitForID(0);
}
catch(InterruptedException ie){}
}

public void paint(Graphics g)
{
g.drawImage(img,50,50,null);
//g.drawImage(img,50,50,250,250,null);
}
public static void main(String args[])
{
ImageDemo i=new ImageDemo();
i.setSize(500,500);
i.setTitle("My Images");
i.setIconImage(img);
i.setVisible(true);
}
}


--------------------------------------------------------------------------------------
Buttons with FlowLayout
-------------------------------------------------

import java.awt.*;
import java.awt.event.*;

class MyBut extends Frame implements ActionListener
{
Button b1,b2,b3;

MyBut()
{
setLayout(new FlowLayout());

b1=new Button("Yellow");
b2=new Button("Green");
b3=new Button("Red");

add(b1);
add(b2);
add(b3);


b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});

}
public void actionPerformed(ActionEvent ae)
{

if(ae.getSource() == b1) setBackground(Color.yellow);
if(ae.getSource() == b2) setBackground(Color.green);
if(ae.getSource() == b3) setBackground(Color.red);

}
public static void main(String args[])
{
MyBut mb= new MyBut();
mb.setSize(400,400);
mb.setTitle("MyButtons");
mb.setVisible(true);
}
}
==========================================================
APPLETS
==========================================================

Applet:
---------
When a HTML(HyperText Markup Language) page wants to communicate with the user on Internet, it

can use a special java program, called 'applet'.

Applet = Java byte code + HTML page.

Methods of Applet:
==============
public void init():-
---------------------
This method is the first method to be called by the browser and it is executed only once.  So we can

initialize any variables, creating components and creating threads etc.  When this method execution is

completed, browser looks for the next method: start()

public void start():
-----------------------
This method is called after init method and each time the applet is revisited by the user.  For example, the

user has minimized the web page that contains the applet and moved to another page then this methods

execution is stopped.when the user comes back to view the web page again, start() method execution will

resume.Any calculations and processing of data should be done in this method and results are also

displayed.

public void stop():
-----------------------
This method is called by the browser when the applet is to be stopped.If the user

minimizes the web page,then this method is called and the user again comes back to this page,then start()

method is called. In this way,start() and stop() methods called repeatedly. For example,an applet with

some animation might want use the start() method to resume animation,and the stop() method to suspend

the animation.

public void destroy():
--------------------------
This method is called when the applet is being terminated from memory.The stop()

method will always be called before destroy(). The code related to releasing the memory allocated to the

applet and stopping any running threads should be written in this method.
    executing init(),start(),stop() and destroy() methods in that sequence is called "Life cycle of an applet".

Apart from these fundamental methods, there are methods called
paint(), repaint()

paint():
---------

The paint()n method is used to display a line, text or an image on the
screen.  It takes an argument of the class "Graphics".  This class
Graphics is a part of the java.awt package.

eg: import java.awt.Graphics;


Uses of Applets:
--------------------

Applets are used on Internet for creating dynamic web pages.There are two types of web pages

Static and Dynamic.Static web pages provide some information to the user but the user cannot interact

with the web page other than viewing the information.Dynamic web pages interact with the user at the run

time.For example, a student can type his hall ticket number in a text field and click the retrive button to

get back his results from his university server.Applets are useful to provide such interaction with the user

at run time.

Another use of Applets is for creating animation and games where the images can be displayed

or moved giving a visual impression that they are alive.


=======================================================
Example I
===================================================
// MyApp.java

/** <applet code="MyApp.class" Width=400 Height=300></applet> */


import java.awt.*;
import java.applet.*;
public class MyApp extends Applet
{
public void init()
{
setBackground(Color.blue);
setForeground(Color.white);
}
public void paint(Graphics g)
{
g.drawString("Hello Applets!",100,100);
}
}

//javac MyApp.java
// appletviewer MyApp.java

========================================================
Example II
========================================================

// App1.java


// <applet code="App1.java" width=400 height=400></applet>



import java.awt.*;
import java.applet.*;
public class App1 extends Applet
{
String msg="";
public void init()
{
setBackground(Color.yellow);
setForeground(Color.red);
Font f=new Font("Arial",Font.BOLD,20);
setFont(f);
msg+="   init   ";
}
public void start()
{
msg+="   Start   ";
}
public void stop()
{
msg+="   Stop   ";
}
public void destroy()
{
msg+="    Destroy   ";

}
public void paint(Graphics g)
{
g.drawString(msg,50,150);
}
}


//javac App.java
//appletviewer App.java
==========================================================







Example:
-----------












==========================================================================
STREAM
==========================================================================

The literal meaning of stream is a flow.  In technical terms, a stream is a path by which the

data travels in a program.  One application of streams that we are familiar with is the “ System.in “ input

stream.


The Concept of Streams:
-----------------------------------
Streams are pipelines for sending and receiving information in Java Programs.  When a

stream of data is being sent or received, we refer to it as ‘ writing ‘ and ‘ reading ‘ a stream respectively.

When a stream is read or written, the other threads are blocked.  While reading or writing a stream if an

error occurs, an IOException is thrown.  So the stream statements must consist of a try-catch block.

The class ‘ java.lang.System’ defines the standard input and output stream.  These are the major classes of

byte streams procided by java.

System.out class  :
------------------------
 The standard output stream is used to typically display the output on the screen.

System.in class    :
------------------------
 The standard input stream usually comes from the keyboard and is used for reading characters of data.

System.err class    :
-------------------------
This is standard error stream.

The java.io Package:
-----------------------------
All streams are available in java.io package.

The InputStream Class:
---------------------------------
The class ‘InputStream ‘ is an abstract class.  It defines how data is received.  It defines how

data is received.  The important point is not where the data comes from, but that it is accessible.  The class

InputStream provides a number of methods fro reading and taking streams of data as input. Eg: read()

method

The OutputStream Class:
---------------------------------
The class ‘OutputStream’ is also abstract.  It defines the way in which outputs are written to

streams.  This class provides a set of methods that help in creating, writing and processing output streams.

Eg: write() method

The File Class:
----------------------
The File class is used to access file and directory objects.


Example I
--------------------
import java.io.*;
class FileDetails
{

public void display()
{
File f=new File("f:/uma/io streams/one.txt");
System.out.println("it is file:"+f.isFile());
System.out.println("File Name:"+f.getName());
System.out.println("File Path:"+f.getPath());
System.out.println("size of file:"+f.length());
System.out.println("parent of file:"+f.getParent());
System.out.println("modify time:"+f.lastModified());
System.out.println("file is hidden:"+f.isHidden());
System.out.println("can write:"+f.canWrite());
}
}
class FileDemo
{
public static void main(String args[])
{
new FileDetails().display();
}
}

Example II
------------------------------------------------------------
import java.io.*;
class ReadFile
{
public static void main(String args[])throws IOException
{
//It reads the data in binary format(Binary Stream (ASII Codes))
FileInputStream f1 = new FileInputStream("one.txt");
int x = f1.read();
while(x!=-1)
{
System.out.print((char)x);
x=f1.read();
}
f1.close();

}
}

Example III
------------------------------------------------------------
import java.io.*;
class SequenceDemo
{
public static void main(String args[])throws IOException
{
FileInputStream f1 = new FileInputStream("one.txt");
FileInputStream f2 = new FileInputStream("two.txt");

SequenceInputStream sis = new SequenceInputStream(f1,f2);
int x = sis.read();
while(x!=-1)
{
System.out.print((char)x);
x=sis.read();
}
sis.close();
f1.close();
f2.close();
}
}


Example IV
------------------------------------------------------------

import java.io.*;

class FileWriterDemo {

  public static void main(String args[]) {

    try {

      // Create a file writer
      FileWriter fw = new FileWriter("three.txt");

      // Write strings to the file
      for(int i = 0; i < 12; i++) {
        fw.write("Line " + i + "\n");
      }

      // Close file writer
      fw.close();
    }
    catch(Exception e) {
      System.out.println("Exception: " + e);
    }
  }
}            


Example V
------------------------------------------------------------
import java.io.*;

class BufferedInputStreamDemo {

  public static void main(String args[]) {

    try {

      // Create a file input stream
      FileInputStream fis =
        new FileInputStream("one.txt");

      // Create a buffered input stream
      BufferedInputStream bis =
        new BufferedInputStream(fis);

      // Read and display data
      int i;
      while((i = bis.read()) != -1) {
        System.out.print((char)i);
      }

      // Close file input stream
      fis.close();
    }
    catch(Exception e) {
      System.out.println("Exception: " + e);
    }
  }
}                    

No comments:

Post a Comment

PHP Notes

The Characteristics of PHP:- ----------------------------------- 1.PHP is a high level programming language. 2.It is a server-side scrip...