Friday 20 March 2015

Java Basic Tutorial




 

Introduction:


Java in an object-oriented, multi-threaded programming language developed by sun Microsystem in 1991.  It is designed to be small, siple and portable across different platforms. As well as operating systems.

The popilarity of java in due tio its unique technology that is designed on the basic of three 3 key elements. They are the usage of applets, powerful programming language. Constructs and a rich set of significant object classes.

In the java development environment there are 2 Parts: a java compiler and a java interpreter.  The compilter generates bytecode (a set of instructions that resemble machine code but are not specific to any processor instead of machiine code and the interpreter executes the java program.  In order to write a java program, an editor, a java compiler amd a java Runtime Environment are needed.
           
The editor can be a notepad,wordpad,MS-Dos editor etc. The easiest way to get a Java Compiler and Runtime Environment is to download Sun’s Java development kit.  This provides system input and output capabilities and other utility functions in addition to classes that support networking, common internet protocals and user interface toolkit functions.

How a Java Program works



Source code
 

Byte code
 

Machine code
 
 






Featutes of java

1)    Simple and powerful:
Java was designed to be easy for the professional programmer to learn and use effectively. Java makes itself simple by net having surprising features. Since it exposes the inner working of a machine, the programmer can perform his desired actions without fear.                                                                             

      2) Secure:             
To conduct commerce over the interent is an safe as                                                   Printing their credit card number on the first page of a    newspaper.Threatening of virus and system hackers also exists.To overcome all these fears java has safety and security as its key design principle.

3) Portable:
Many types ofcomputers and operating systems are in use throughout the world and are conneted to the internet for downloading programs through different platforms connected to the interent, some portable,executable code is needed. Java’s  answer to these problems is its well- designed architecture.

    4) Object- oriented:
Java was not designed to be source code compatible with any other language. Java team gave a clean,usable,realistic approach to objects. The object model in java is simple and easy to extend,while simple types,such as integers are kept as high- performance non-objects.

    5) Robust:
The ability to create robust programs was given a high priority in the design of java.   Java forces the user to find mistakes in the early stages of program development.Java checks code at compilation.  It virtually rectifies the problem of memory management by managing memory.
Allocation and automatic memory deallocation by providing garbage collection for unused objects.  Java also handles exceptional condtions by providing object-oriented exception handling.  In a Well-written Java program, all run-time errors can and should-be managed by the program itself.

  6) Multithreaded:
Java was designed to meet the real-world requirements of creating inheractive,        networked programs. So achieve this, java supports multithreaded programming, which allows the user to write programs that perform many functions simultaneously.

7) Architecture- neutral:
A main issue for the java designers was that of code longevity and portability. One of the main problems is the execution speed of the program.since java is architecture – neutral it generates bytecode that reaembles machine code, and are not specific to any processor.

8) Interpreted and high performance:
Java enables the creation of cross-platform programs by compiling the code into an intermediate representation called java bytecode. This code can  be interpreted on any system that has a java virtual machine.Java bytecode was carefully designed so that it can be easily translated into native machine code  for very high performance by using a just-in-time compiler.

9) Distributed:
Java is designed for the distributed environment of the internet, because it handles TCP/IP protocob. The original version of java (OAK) included features for intra- address- space messaging. This allowed objects on 2 different computers to execute procedures remotely. Java has recently revived these interfaces in a package called remote method invocation (RMI).

10) Dynamic:
Java programs carry with them extensive amounts of run- time information that is used to verify and resolve accesses to objects at runtime.using this concept it is possible to dynamically link code. Dynamic property of java adds strength to the applet environment, in which small fragments of byte code may be dynamically updated on a running system.
          
Structure of a Java  Program

    public class
               { public static void main (string [ ] arguments)
                       {
                             statements;
                             - - - - - - - - - -
                             - - - - - - - - - -  
                           }
                       }   
How to compile and Run a code:

Once the file has been saved, we have to compile it and convert it in to bytecode. The java compilation does not creat direct executable format (.exe in MSDOS or Mswindows) Instead bytecode for the source is generated which is run by java virtual machine or JVM.

To compile a .java file:

                                  javac < filename>.java

this generates a file called class file.
To run a bytecode(for a class),it must contain a static main() method as described above.

java .

This runs the main method in that class.if no main method is found an error message saying,”no main method found “ is displayed.

Variables

A variable is an entity that can change values during the program execution.all variables in java must be clearly declared and initialised before using it.

Datatypes:

All variables in the java language must hava a datatype.a variable’s datatype  determnes the   values that the variable can contain and the operation theat can be performed on it.
There  are two major categories of datatypes in the java language.

 1. Primtive
Type
Size
Range
description
Byte
8 bits
-128 to 127
byte-length integer
Short
16 bits
-32768 to 37767
short integer
Int
32 bits
-2147483648 to 2147483647
integer
Long
64 bits
-223372036854775808 to 9223372036854775807
long integer
Float
32 bits
IEEE754
Single precision floating point
It is used to store
Numbers with
Decimal part.

Char
16 bits
Unicode character
A single character
It is used for
Storing
Individual
Characters
Boolean
True/false

A boolean value(T/F)
Double
64 bits
IEEE754
Double precision floating point

Operators

Operators perform some function on either one or two operands or 3 operands. Operators that require one operand are called unary operators. Ex: ++ is a unary operator that incrments the value of it’s operand by 1. operators that require two operands  are binary operators.
Ex:= is a binary operator that assings the value  from it’s right-hand operand to it’s left-hand operand and finally ternary operators are tose that require 3 operands. The java language has one ternary operator ,?:,which is a short hand if-else statement.

Arithmetic operator

      +      addition
      -       subtraction 
      *      multiplication
      /       division
     %      modulo(gives remainder)

Note:Java extends + operator to include string concatenation.

++   ->a++   ->increments a by 1;evaluates to value before incrementing.
++   ->++a   ->increments a by 1;evaluates to value after incrementing.
--   ->a--   ->decrements a by 1;evaluates to value before decrementing.
--   ->--a   ->decrements a by 1;evaluates to value after decrementing.

Relational  and  conditional operator

 >,>=,<,<=,==,!=

A relational operator compares two values  and determines the relationship between them.
Logical Operators

&&  - and
||       - or
!       -not

Assignment  operators

Java also providesc several shortcut assignment operators that allow you to perform an arithmetic ,logical  or bitwiseoperation and an assignment operation all with one operator.
+=     ->a=a+1
-=      ->a=a-1
*=     ->a=a*1
/=      ->a=a/1
%=    ->a=a%

Literals

A literal represents a vlaue of certain type where the type describes the behaviour of the value.

There are different types of literals. They are

1. Number literals

There are several integer literals such as  int,long,octal,hexadecimal etc.if a decimal integer literal is larger than the int ,it is declared to be of type long.A number can be made long by appending L or l to it.negative integers are preceded by the minus sign.these integers can also be expressed as octal or hexadecimal.A leading 0x to the integer indicates that the number is a hexadecimal integer.

2. Character literals

Character literals are expressed by a single character enclosed  within single quote.character are stored as unicode character.some of the non-printable characters.

Escape                                  Meaning
\n                                             newline
\t                                              tab
\b                                             backspace
\ddd                                        octal
\xdd                                         hexadecimal
\udddd                                    unicode character

3.boolean literals

Boolean literas consists if the keywords true or false.

4. String literals

A string is a combination of characters.string literals are a set of characters that are enclosed within double quotes.
           
Output  statement

This statement is used to print any message or variable value on the screen.

System.out.println(+=);

Input statement

This statement is used to get the user input value.

Nummeric Input: =System.in.read()
Character Input: =(Char)System.in.read()
 
Programing Constructs

Programing constructs in  Java are the following:

  1. If Statement
  2. Ternary Operator(Conditional Operator)
  3. Switch Statement
  4. While Statement
  5. Do While Statement
  6. For loop Statement

If Statement

If (Condition)
;
else
;

The if else constructs executs different bits of code based on successful complation of a condition, that reutrn only boolean values.  If the excutes is unsuccessful, the sets of instructions under else are executed.

EG: Program to find Negative or Passitive or Zero

Class check
{
    Public static void main(string a[])
    {
              int n=5;
              if(n>0)
                          System.out.println(“possitive”);
              Else if(n<0 o:p="">
              {
                          System.out.println(“Negative”);

              Else
                          System.out.println(“Zero”);
    }
}

Ternary Operator

? : ;
 
          The conditional operator in otherwise known as the ternary operator and is considered to be an alternative to the if else constructs.  If returns a value.

EG: Program to check the biggest number:

Class ternary
{
     public static void main(String a[])
     {
          int a=100,b=200;c=0;
          z=a>=b?a:b;
              System.out.println(“Valeus assigned is” +z)
              }
      }

Switch Statement

                        switch(test)
            { case :
                        ;
                        :
              case:
                    ;
                    :
              case:
            default:
                  ;
                  ;                          
            }
The switch staement dispatches control to the different parts of the code based on the value of a single variable or expression.  The value of expression is compared with each of the literal values in the case statements.  If they mach the following code requence is executed.  Otherwise an optional default statement is executed.

EG: Program to show the color names:

Class colour
{
      public static void main(String a[])
      {
            int c=3;
            switch(3)
            {
                                      case1: System.out.println(“Red”); break;
                                      case2: System.out.println(“Blue”); break;
                                      case3: System.out.println(“Green”); break;
                                      Default:System.out.println(“Invalid Color”); break;
              }           }           }

While Statement

            while (condition)
                  { ;
                    - - - -  - - - - -
                    - -- - - - - - - -   
                         ;
                      ;
                      }
The while loop executes a set of code repeatedly until the condition returns false.If the condition returns true then the statements inside the whilw are executed.

Eg: Program to print the Fibonacci numbers.
            Class Fibo
{ Public static void main(String dc [ ] J)
   { int max= 25;
      int prev = 0;
      int next = 1;
      int sum;
      while (next < = max)
          { System.out.println(“Fibonacci series is:” + next);
               sum = prev +next; 
               prew = next;
               next = sum;          
            }             }           }

Do While Statement

do { ;
              - - - - - - - - - - -
              - - - - - - - - - - -
               ;
              ;   
} while (condition);
The do while loop is similar to the while loop except that the condition to be evaluated is given at the end.Hence the loop is executed at least once even when the condition is false.

Eg: Program to print 1 to 10 numbers
Class num
{ public static void main (String a[ ] )
   { int n = 10, m= 1;
       do { System.out.println (“numbers are:” +m);
                      m= m + 1;
                   } while (m < = n);
               }        }

For Statement

For (initialization; condition; exprssion)
            { ;
            - - - - - - - - - - -
             - - - - - - - - - - - 
         }
The for loop repeats a set of statements a certain number of times until a condition is matched. It is commonly used for simple iteration.

Eg: program to print 0 to 10 add numbers or even numbers.

Class oe
{ public static void  main (String a[ ] )
       { int i ;
            for ( i =0; i < = 10 ; i + + )
        { if ( ( i% 2) = = 0)
                      System.out.println (“ numbers are even:” + i);        
                     else
                                   System.out.println (“ numbers are odd:” + i );
                     }              }          }

Break and continue statements:

The break keyword halts the execution of the current loop forces control out of the loop.
                                   
The continue is similar to break,except that instead of latting the execution of the loop, it starts the next iteration.



Classes
      
A class defines the shape and behaviour ofan object and is a template for multiple objects with similar features.

Any concept represented in a program is encapsulated in a class. When an application is written, classes of objects are defined  to create a class,a source file with the class keyword in it, followed by a legal identifier and a pair of early braces for the body is required.
Syntax
                   Class
                            { ;
                                - - - - - - - - - - - - -  - - - - -
                             }
Eg: Class to create Book members
 
class Book
            {           String name;
                        String  author;
                        String edition;  
                        int rate;

String display name( ) 
           { System.out.println(“ name of the book is :” +name);
                         }  
               }
Attributes

Attributes  are individual properties that differentiate one object from another and determine appearance,state and other qualition. Each attribute has a correspending instance variable.
   
Instance variable
Data is encapsulated in a class by declaring variables inside the class  declaration. Variables declared in this scope are known as instance variable. They are declared in the same way as local variables except that they are declared outside the scope of any particular method such as main.

class Book
          { int rate, quantity;       } 

Dot operation

The dot notation is used to obtain the value of the instance variables. It  has 2 parts namely the object on the left side of the dot and the variable on the right side of the dot.
Dot expression are evaluated from left to right.
           .
Where is the name  of the object and   to the instance variable.

Eg: p.x=oj p.y=20j
System.out.printen(“s=” +p.x);

New operater

The new operatar creater a usingle instance of a named class and returns a reference to that object.
Eg: an instance of the class “ point” can be created as shown:
            Point p = new point ();
Here p is a reference to an instance of  point.


Example
class X
{ int a = a=10; int b=20;
                 Public static vrid main (String a[])
                                    { x num = new x ();
                System.out println( A”=+num. a+”B”=”+num.b);
            }       }

Methods

Methods are functions that operate an erstances of clases in whicl they are defined. Objects can commenicate with each other using mehod and can cll methods in other clases.Juot as there are class instance methods apply and operate on  an instance of the class while class methods operate on the class.

Defining methods

Method definiction has 4 parts.  They are
    (1)   Name of the method.           (2)     Type of object or primitive type that returns
    (3)    A list of Rarmetes   (4)      Body of the mehod.

A methods is signature is a combination of the first there parts menitioned above. Java parmits different methods to have the same name as the argament list is different .
This is called method oveloadeing.
  (  ,   arg2>.....)
                          {   ;
                                           --------       }
The return type is the primitive type or class of the value that this method returns.  It should be vrid if the method does not return a value atall.

Calling methods

Calling a method is similan to calling or referring to an instance variable. The methods are accssed using the dot notation.  The object whose method is called is on the left of the dot, while the name of the method and its arguments are or the right.

            Object.   Method name (paramethter1, parameter2);

Example

            Class area
            { int len = 10;
  int bre = 10;
  void cal(c)
  { int ara = len+bre;
   System.out.println (Area;”+ara+”sq.cms”);
  }
public static void main (String a[])
   {
area a = new area();
a.calc();
}           }

Class Methods

Class methods like class variable, are available to other classes Methods that operate ona particular object should be dfired as instance methods.

            Static   (type arg1, type2 arg2,...)
            {statements;
              --------- }
The static keword indicater that it is a class method and can be accessed without creating an object.

Passing Argements to Methods

The objects that are passed to the body of the method are  passed by reference and the basic typer are passed bt value .  This result in achange in original value . This result ina changein original value of the object if the value is modified in the method.
Eg.
            Class rn
            {void calc (int x)
                        {int square = x*x;
                           System.out.println(square of ; “ + x+” sqcme”);
                             }
                        Public static void main (String a[])
                        {           rn Q = new m();
                                    Q.calc(15);
}         }
The this keyword
A special reference value called ‘ this’ is included in Java. The this keyword is used inside any instance method to refer to the vcurrent object. The value of This refers to  the object on with the current metod has been called. The this  keyword can be used where a reference to an object of the current class type  is required. Methods  doclared with the keyword static ( class methods)  cannot use  this.          
Eg: 
            Class point
  {         int X,Y;
void init (int x, int y)
            {           this.X = x;
            this.Y  = y;
            }
      void disp()
            { System.out println( “x=” +x);
              System.out println( “y=: +y);
}         }
            Class  pp
{ public tatic void main (Strings a[])
{ point a = new point  ( ) ;
              a. init (4,3);
  a.disp();
               }             }

Overloding Methods

To create an overloaded method, different method difinitions each with the same name but different parameter  lists are created.  Java allows  methods overloding an along as the each parameter  list is uniqe for the same method name.  Java differentiates  overloded methods with the same name, pased on the number and type of parameters  to that method and not on the return type

More about classes

Accces control is the processof controlling visibility of a varible or method  When a method  or varible is visible to another class. Its methods can reference the method or variable . there are 4 levels of  visibility that are used.

Public

Any  method or variable is visible to the class in which it is defined.  If the method or variable must be visible to all classes,  then it must be declared  as public.  A visvarible or method with public access has the wident possible visibility.  Any class can be use it.

Package

Package is indicated by the lack of any access modifier in a declaration.  It has an increased protection and narrowed visibility and is the default protection when none has been specified.

Protected

This specifier is a relationohip  between a class and its present and future subclass.  The subclasses are closer to the parent class than any other class.  This level givies more protection and narrows visibutity.

Note: The pockage and protected access specifiers specifiers have been deatt with while deeling with packages in the latter  half of the book.

Private:

 

It is narrowly visible and the higrest, level of protection that can possible be obtained.  This methods and variabler cannot be seen by any class other than the one in which they are defined.  They are extnemely reatrictive but are most commonly used.


Eg:

Class priv

            {  private  int x = 10;
               void var( )
                { System.out .println(“The private value is: “ +x);    }
               Public static void main (string a[])
                    {     priv p= new priv ( );
              p. var ( )
                        }           }

Java Class libary

The Java class library provides at sed of class guranted as avao;able in any commecial Java  environment.
A list of the class packages that are past of the Java class library are:
(1)    java.lang: classes that apply to the language itself which inclides tje object class, the string class and the system class It a;sp centains the special classes for the primitive tu[es (int, char float).
(2)    java util: utility classes such as date as well as simple collection classes such as vector and Hah table.
(3)    Java.io: Input & output classes for usiting to and reading from sheams and for handling files.
(4)    java.net: classes for  networking support, including  socket and uRL.
(5)    Java.awt: (Abstract Window Toolkit) class  to implement a graplical uses intesfaces for window, meny button fong, Check box. This package who includes classes for processing images.

Constructor
                                                     
A constrictor method is a special kind of method that ditermines how an object is initialized when created they have the same name as the same  name as the class and do not have ant return type. Every class has a defult constructor that doses not take any argument and the body of it does not have any statements. Constuctors can also be overloaded.

Eg:
Class cons
{           int i,j;
cons (int a, int b)
{ i = a;
  j=b,   }
void print( )
            { System.out.println(“addition:”+;+j);   }          
public static void main(Sring a[])
{           cons c = new cons (10,10);

c.print ( );
System.out.println(“ “);
c= new cons (50,60  );
c= print( );
System.out.println ( “ “ );
   }        }

Calling another constuctor

A constructor can be called from another constructor.  When a constructor  in writen, thefunctonalities of another defined constractor can be used.  To call a corptuctor defined in the current class use this (arg1, arg2, arg3, ....   ) 

Eg:
            Class point
{           int X,Y;
point(int x, int y)
{           this, x= x;
 this. y=y;        }
point ( )
{          this (-1,-1);                       }
            public static void main (String a[])
            { point p= new point ( ) ;
              System.out.println( “ x =”+p.x “y=”+ p.y);
              P= new print ( 10,10);
              System.out.println(“x=”+p.x+”y=”+p.y);
               }        }

Overloding constuctor

Constructors can also take varying number and types oif parameters. This enables creation of objects with the properties required.

Eg.
Class cload
{           String pname;
int gty; price;
cload (int prodqty,String prodname, int prod price)
{           pname= prodname;
            qty = prodqty;
            price= prod price;
}
cload (int q, string plname)
 {          pname = plname;
price = q,j
qty= price /10;
}
clrael( String p pname , int pprice)
{           pname = ppname;
price= (in+) pprice - 0.1));}
 }
void  print( )
{ System.out.println(“prg dcoduct Name : + pname );
  System.out.println(Quanntity : “+qty);
  System.out.println(“price:” +price);
            }
          public static void main (String  a[])
{           cload  prods;
             prods= new cload (10,”Apple” 10);
             prods.print( );
                         prods=new cload (10, “Orange”);
             prods.print( );
                         prods= new cload(“Grapes”,25);
                         prods.print( );
            }          }



Vector

A vector is an array of object refernce. Internally, a vector implements a strategy to minimize reallocation and wasted space. Objects can be stored at the and oif a vector by using the add element method or inserted at a iven index by the insert element At method. An array of objects can be stored in a vector using the coppy Into method.

Eg:
            import java.util.*;
            class cat
            {           private int catnumber;
                        cat (int i)
            { catnumber = i ;         }
            void print ( )
                        { System.out.println( “ cat # “ + catnumber);  }
            }          
            class dog
            {
                        private int dognumber;
dog ( int i)
{           dog number = i;           }
void print( )
{ System.out.prinln(“Dog #  “+ dognumber);  }
            }
public class catsanddogs
{ public static void main (String a[])
{           Vector cats = new Vector ( );
for (int i=0; i<7 i="" o:p="">
            cats.addElement(new cat(i));
                                    cats.addElement( new dog(7));

            for (int i = 0; i
                        (cat) cats.elementAt(i).print( ) ;
            }       }

Strings

A combiration of characters is a string. Strings are instances of the class Strings. The are and hence, enable combination testing and modification.  When a string literal is used in the program, Java automatically creates instances of the Strings literal is used in the program, Java automatically creter instance of the sting  class. Stings are unusual in this respect.

Eg:
class stings
{           int i;
Stings names[] = {“AAA”, “BBB”, “CCC”, “DDD”};
Void show ( )
{System.out.println(“My favourite names are:”);
for (i=0;i<5 i="" o:p="">
            System.out.println(names[i]);
}
public static void main(String a[])
{ strings s = new stirngs( );
  s.show() ;
}        }

String Methods

The string  class provides a number of methods to compare andsearch strings.

Method                                               Use

(1) length ( )                                        - Number of characters in tring.
(2) charAt( )                                        - The char at a laocation in the strings.
(3) getchars( ), getBytes( )                 - Copy chars or bytes into an external array.
(4) To char Array ( )                            - produces a char [ ] containing the characters in the string.
(5) equals( ) equalsignoveCase( )      - An equality check onthe contents of the two strings.
(6) compareTo( )                                            - Result is nagative,2 zero or positive depending on the                 
                                                             lescicographical ordering of the string and the argument.
                                                             Upeper and lowercase are not equal.
 (7) substing( )                                     - Returns a new string object containing the specifed
                                                              charater set.
(8) concat( )                                        - Returns a new string object untaining the original stings
                                                              characters. Followed by the character in the argument.
(9) tolowerCase( ), toupperCase( )     - Returns a new string  object with the the case of all letter
                                                              changed.Uses the old shing if no changes made.
(10) trim( )                                           - Returns a new string object with the white space.
                                                              Removed from each end uses the old string is no
                                                              changes need to be made.
(11) valueOf( )                                                - Returns a sting containing a character represtntation of
                                                              the arugument.
(12) indexOf( )                                                - Returns -1 if the argument is not found within this string,
                                                             otherwise returns the index where the argument starts.
                                                             Last I IndexOf ( ) search back wards from end.

Eg:
            class st
            { public static void main (String a[] )
            {          
Srting s= “Now is the time for all good men “+” to come to the aid of their country “+” and
                        pay their taxes”;
            String s1 = “Hello world :;
            String s2 =  “Hello”;
            String s3 =  “HELLO”;
            System.out.println(s);
            System out println (“index of t = “+ s.indexOf(“t”));
            System.out.println (“last index of t=”s.lastIndexOf(‘t’));
            System.out.println (“index of (t,10) = “ + s.indexOf(‘t’,10) );
            System.out.println (“last index of (t, 60)=” +s.lastindexOf(‘t’,60) );
            System.out.println (“sl.substring (3,8,));
            System.out .println(s2.concat( “World”));
System.out.println( s2.replace (‘l’,w’));
            System.out.println(s3 tolowerCase()) ;
            System.out.println(s1.trim());
            }         }

String Buffer

Sting Buffer represents varied length character sequences. String Buffer may have character and substrings inserted in the middle. Or appended at the end.  The compiler automatically creater a String Buffer  to evalute certain expression,in particular when the overloaded operators + and + = are used with string objects.
Eg:
            public class buf
            {  public static void main (string dc [])
                        {String foo = “foo”;
             String s= “abc”+ foo+ def” + Integer.toString (47);
            System.out.println(s);
            StringBuffer sb = new StringBuffer( “abc”);
                        sb.Appened(foo);
            sb.Append(Integes.toString  (47));
            System.out.println(sb);
            }                    }

String Buffer Methods
Method                                                           use
(1) toString( )                           - Creates a string from this string Buffer.
(2) length( )                             - Return the number of character in the sting Buffe
(3) capcity( )                           - Return curren number of spaces allocated
(4) charAt ( )                           - Returns the char at that location int the buffer.
(5) Append( )                           - The argument is converted to a string and appended at end
                                                  of the current buffer, increasing the buffer if necessary.
(6) insert( )                              - The second argument is converted to a string and inserted  into
                                                  the currebt buffer. Begining at  the  offset. The size of the buffer                                                     is increased , if necessary.
(7) reverse( )                           - The order of the characters in the buffer is reversed.
Inheritance

Inheritance is the process of deriving a class from a super class or a base class. Inheritance refers to the properties of a class being available to many other classes. A derived class/ syo class is one that has been created from an existing class.The original class is called as base class/super class

Advantages Inheritance

The most important of is rescsability of code. Once a class is defined and debugged it can be used to create new subclasses.  This means it can be extended more than are derived class without affecting the properties or members of it’s existing base class.  The reuse of existing clasess sawes time and effort.

Base class or Super class:

The class which get the properties from another class is claaed derived class which contains the properties of base class as well as it’s own properties.

Types of Inheritance:

They ae of 5 types.  

Single Inheritance

A class can be derived from a single base class is called single inheeritance.

Derived
 

Base
 

j
 

i
 
                                                    
               A                               B
                                                                                   
                                                                                       Base                                                      Derived
Eg:
            class base
            { public int x = 10000, y,2;      }
            class derive exterds base
            { public int n,m;           }
            class singlein
            { public static void main (string a[])
{
derive d = new derve ( );
            System.out.println(“Result  is. “ d/x);
    }       }

Multilevel Inheritance

Deriving new class from anold derived class is called multivel inheritance.

Derived 2
 

Derived1
 

Base
 
   

i
 
 




A                                         B                                         C

Eg:
    Class base
    { void base message ( )
      { System out. Println (“Welcome to base class”);
        }           }
class derive 1 extends base
{void derive 1 message ( )
                     
         {System out. Printlb (“Welcome to derive 1 class”);     }
class derive 2 extends derive1
  {    void derive 2 message ( )
   {  System. out. Println (“Welcome to derive 2 class”);  }     }
class multiinl
{public static voidmain (String dc [ ])
derive 2 d2 = new derive 2 ( );
d2. derive 2 message ( ) ;       d2. derive 1 message ( ) ;
d2. base message ( ) ;   }        }
Hierachical Inheritance

We can create more derived class from an super class.The properties of one class may be       inheritad by more then several classes.

Base
 
 




     
       

Derived 1
 

Derived2
 

Derived 3
 
 




Eg:
    Class b
        {public void bmsg ( )
             { system. out. Println ( “Base class”);
    }       }
class d1 extends is
      { }
class d2 extends b
      { }
class d3 extends b
   {public static void main (string dc [J)
       {d1 m= new d1 ( );
         d2 n = new d2 ( );
         d3 p = new d3 ( ) ;
                       m. bmsg ( ) ;
                        n. bmsg ( ) ;
                        p. bmsg ( );
   }        }

Multipele Inheritance
One derived class with several  base classes.

   j
 

    i
 
A                                               B
 






Note: Java do not support multiple in hertance. It is possible when Interface is used.

Hybrid Inheritance
Hybrid is nothing but the combination of single, Multivel,Hierachical and Multiple Inheritance. Java do not support multiple inheritance, so this  inheritance cannot be used in Java. It is done when Interface concept is used.

    A
 
 
    

                   
 









Final keyword
The final keword in a method declaration to indicate to the compilen that the method cannot be overridden by subclasses. The word “final” is used to  indicate that no  further atterations can be made.
Final   = ;
Eg:
import java.io.*;
            // Final class
class A
{           final void fin()
            {                       System.out.println("This is a final method.");      }           }
class B extends A
{           void fin()
            {                       System.out.println("Illegal");          }           }
class finalc
{           public static void main(String tc[])
            {                       B d = new B();                      
                        d.fin();
                                    d.fin();             }           }
Note:
fin() is a contant function.
it cannot be used in sub class.

usage of super
Whenever a subclass need to refer to its immediate base clase, it can also do so by use of the keyword   super   Super has 2 general forms.
(1)  Calls the base class constructor. (2)  used to areass a member of base class that has been hidden by a member of a subclass.
Supper (parameterlist );
Where parameter - list specifies any paremeters neede by the constructor in the base class. Syper ( ) must always be the firststatement executed iside a subclass constructor.
Eg:
import java.io.*;
class A
{           int i;     }
class B extends A
{           int i;
            B(int a, int b)
            {           super.i = a;    i=b;      }
            void show()
            {           System.out.println("i in super class :" + super.i);
                        System.out.println("i in subclass     :" + i);           }           }
class superc
{           public static void main(String tc[])
            {           B xx = new B(1,2);    xx.show();      }           }

Abstract Methods and classes
Abstract classes are classes from which instances are usually nnot created. It is basicallly used to conitain common characteristics  of its derived classes. Abstract classes are generaly higher up the hierarchy and act up suber classes. Methods can also be declared as abstract.

 












Exception
An exeetiton is an banormal condition, which orcurs during the execution of a  program. There are many types of exceptions.  A  Java exception is an object, which describes the error conditon that has materialized in the program.
Java handles exceptions using five kewords - try, catch finally, therours and throw.

Object
 
 


                         

   Error
 

Exception
 

Io Exception
 

Runtime Exception
 
 














There are 2 types Exceptions.
(1)  Complie time Error:
(a)   Variable undefined.
(b)   Missing or mismatch of curly braces.
(c)   Wrong spelling.
(d)   Miss of double qustes.
(e)   Mixing up date types
(f)    Bad reference to objects
(g)   Wribg use of paerators
(h)  Wrong usage of idrectory path.
(2)  Runtime Error:
(a)   Division by 0 (zero).
(b)   Array index out of bound.
(c)   Incomplete data type or array.
(d)   Null object refernce
(e)   Casting (converting)
(f)    Passing wrong arguments to a method
(g)   Nagative index for an array.
(h)  Illegal change of a thread.
(i)    Converting non-numeric string to number.

Try and catch
            Try {
                        Statements; }  catch (Exception )
{Statements;}
The  keyword try and catch is  used to fix the error and prevents the program from terminating abruptly.

The code sequence,which is to be   gyarded, should placed inside the try  block . The catch statement should immedistely follow the try block. The catch  statement can have statements explaining the cause of the exception generated. The scope of each catch is restricted to a try block.
Eg:
import java.io.*;
                        // try and catch
class excp1
{           public static void main(String tc[])
                        {           try        {
                                                int a[] = new int[-2];
                                    a[0]=50;
                                    System.out.println("First Element :" +a[0]);          }
                        catch(NegativeArraySizeException e)
                                    {
                                                System.out.println("Generated exception :" + e);
                        }
                                    System.out.println("After the try block");  }                       }
Usage of  throws
Whenever a program does not want to handle exceptions using the try block it can use the throws clause.  The trous clause is reponsible to handle the different  types of exceptions generated by the program.
Eg:     
Class excp1
            {public static void main(string d[]) throws ArethmeticException
            { System.out.println(“inside main”);
int i=0;
int j =40/i;
System.out.println(“this statement is not printed”);        }           }

Package:
Packages contain a set of classes in order to ensure that class names are unique.  They are containers for classes that are used to compartmentalize the class name space. Packages are stared in a hierarchical mamer and are esepliciltly  imported into new class definitions. A perild is used as separator to enablethis.
Package ;
To execute the package file
java <[aclagemame>.
Eg:
Create a directory  claaed pack  
Save the file as  Classl java. Inside the pack dirctory package pack;
public class class1
{           public class void greet()
{ System.out.println(“Hello”);          }           }
Create a subdirectory called subpack inside the pack directroy save the file as class2. Java inside the Subpack directory
package pack. Subpack;
public class class2
{  public static void yourwell()
{  System.out.println(“by”);  }           }
In the root dirctory create file as Importer. Java.
Import pack.*;
Import pack. Subpack.*;
class importer
{ public static void main (string c[])
{class1.great();
class2.farewell();      }           }

Files and Streams
Files are the primary source and destination for data within most programs.  File I/O operation is comon in any language. Java dovtes a whole range of methods found in a class called File in tha java.io package to perform these operations.
A file is the only object in the I/O package that referances an actual disk file.  Java treats files and directories as objects of the File class. Path separator, path separator character, file separator file separator character etc., depend  an the platform on which we are working. “/” is used for escaped by  meentiong within a string, “/” is used as path separtor.

Constructors: objects of the file class can be created using 3 types of file constructors.
(1)  File =new File (filepath”);
Eg: File f1 = new file (“c:/java/deep”);

(2)  File =new File (file path , filename);
Eg: File f2 = new file (“c: java”, “deep”);

(3)  File =new file(“string/”,string2”);
Eg:File f3= new file (java”, “deep”);
Methods of the file class
(1)  getName() - As the name suggests, this method is used to obtation the name  of the   file  specified.
(2)  getPath() /getAbsolutePath() - To obtain the path of the file specified and the absolute path of the filespecified, respectively.
(3) getParent() - Return a string object that  contains the parent directroy.
(4) exists() - To check if thye named file exists in the specified directroy or not.
(5) isFile() isDirectory() - To check if the named.
Eg:
import java.io.*;
Class filemethods1
{public static void main(String c[])
{ File f1= new File(“c:// java”,”abc. Txt”);
System.out.println(“File name?”+f1.getName());
System.out.println(“path;”+f1.getpath ());
System.out.println(“Absolute path:”+f1. getAbsolutepath( ));
System.out.prinln(f1. exists ( ) ?”file exists”: file doesnot exibts”);
System.out.println(f1.isDirectory ( ) ? “Directory “:”named pipe file”);
System.out.println(f1. isFile ( )?” ordinary file”: “named pipe file”);           }           }

Canread() / canWrite Methods
There methods are used to check if we can read from the specified file or write into the specified file respectively.  These methoels return boolean value.

Last  Modified ( ) Method
This method returns the last modification time of the file.
Eg:
import java. Io *i;
class check perm
{public static void main(string d[])
{File  f1 = new File (“c//java”,”abc.txt”);
if (f1.can Read ( ) )
  System.out.println(We can read from this file”);
else
  System.out.println(“We can read from this file”);
      if (f1. canWrite( ) )
              System. out.println(“We can write to this file “);
      else
               System.out.println(“We cannot write to this file”);
   System.out.println(“The file was last modified at”+f1. last Modified ( )+
                        “seconds after January 1 1970”);  }           }

Length ( ) Method
This method is used to know the file size in bytes.

Delete( ) Mehod
This method is used to deletes the specified file.

renameTo( ) Method
This method is used to rename a specified file.

List ( ) Method
This method is used to list the contents of the specifed directory.

Mkdir( ) Method
This method is used to create a directory and returns a bodecan  indicating the success of the creation.
Eg:

Thread
A thread is similar to a sequential program. A sequential program has a beginning, s drwurnvr og ste[s tp execute & an and .  However a thread is not a program on its own.  But rens within a program.  A thread  can be eirin3e qw the sequential flow of corl with in a program.
            Every program has attlast one thread, is called the primary thread you can create more threads when necessary.
            A process in made up of only one thread is said to be single threaded.  A single threaded application  can -proform only one task at the time.
            You have two way for one task to be completed before another can stats.  A process having more than one thred is said to be called multi threaded.  Multiple threads in a process run at the same time, differnt tasks and internet with each other.
            You can create thread in a program using any of the
2.            Methods, listed  below.
(1)  Sub classing the thread   class
            (2)Using the Runnable  interface.
Eg:     (1) Public class extends Thread (Normal Extends)
(3)  Public class   extends Applet inplements Runnable (with in applet)

The life cycle of Thread:

New Thread
 

not Runnable
 

dead
 
 









(1)  New Thread State
When an instance of a Thread class is created the Thread  entres new     Thread state.  Code:
            Thread -new Thread (this);
            .  Start ( );
(2)  Runnable State
When the start method of a  Thread is invoked, A Thread enters the runnable State.  Thread may be waiting for attention of the process.  This is why the state of the thread is said to be Runnable.
(3)  The not Runnable State
A thread is said to be in the not runnable state if it is.
                (1). Sleeping
(2). Wating.
(3). being block by another Thread.
     (4) The dead Thread State:

(1)  A Thread can either die are naturally kill.
(2)  A Thread dies natural death when the loop in the  run ( ) metnod is completed.

Priority of Thread
The threads are scheduled using fixed periority scheduling which esentially executes the Thread depending on their periority relative to one another.  Each Thread has a periority that affects its position.  In the Thread que of the process.  A thread wotj ligher periority runs before Threads with low periority you can represent the periority of a .  Thred by an Integer in the range of 1to10.  You can.  Change the periority for the Thread using the set priority ( ) method.
Public Final void setpriority (int priority)
            MAXPRIORITY-10
            MINPRIORITY -1
            NORMPRIORITY-5

APPLET

Java is of 2 types.
(1)  Application (Eg: Ms.  word)
(2)  Applet         (Eg:net)
There are 2 ways to ways to exeuite applts
(1)  Browser.
(2)  Appletviewer
Syntax to run appletviewer.
Prompt>appletviewer

The applet class is contained in the java.  applet* package applet contains    in the java. applet*; package applet contains several methods that give 9 you detail control over the executiors of  your applet. All applets are sub  class of applet . That are applet must import, java.  Applet*;package.awt (Abstract Window Toolkit).

Applets must also import java,out*;applets
are executed by either a web browser (Internet Explorer, Netscafe Navigator orjava) or  applet viewer.  Applet does  not have a main function.   Applets have '20' methods.  To perform all this activities.

Life cycle of applet is implemented dby the following method.
(1). init()
(2). start()
(3). stop()
(4). destory()

Syntax:
            import java.awt.*;
            import java.applet.*;
            Public class extends Applet
            {method declaration.........   }
/*
*/

Painting
It helps in drawing something on the screen. Be it text, align, color background ar an image.  The paint methode looks like.
Syntax:
public void paint (Graphics g)
{-----------  ----------
 -----------  ----------}
Paint takes an agrument which is an instance of the class graphics.
repainting
This method is used in  case an applet to be repainted. The repaint calls the update methods, to create the screen.  of any existing content. The update() method down calls the paint method that turn draw tghe contents of the current applet.

Controls
A integral integral part of any programming lang is the ability to accept data from a user.
The has to  be  promted for data entry. To simplicity user interaction and make date entry casier  you can use contrds.

Control
Function
Class
(1)  Text box
Accepts single line alpha Numeric entry.
TextField
(2) TextArea
Accepts mulitline & numeric entry
TextArea
(3) Button
Triggers a sequence of actions
Button
(4) Label
Display the text
Label
(5) Check Box
Accepts data that has Y/N, value more than one check Box can be selected
CheckBox
(6) Radio Button
Similar to check Boc. Exceot that it allows the user to select a single option from a group
Check Box & Check box Group

(7) ComboBox
Displays a drop down list for  single item selection it allows a new value to be  ended,
Choice
(8) List Box
Similar to  Combo box. Except that , it allows a uset to select single or mutliple it ens .  Nes nalues can be entered.
List

Eg:
import  java.awt.*;
import java.applet.*;
public class comp extends Applet
{
Label L1 ;
Button b;
Text Field t1;
Text Area ta;
            Check box  c 61 c 62 c 63 c 64 ;
Check box  & 61, & 62, & 63, & 64;
Check box Group g 61,   g 62;
            List Li;
            Choice c:
            Scrollbar sh, sv:
Public vold init()
{           setBackground(new color(125, 125, 130) );
L1 = new Label("Name");
L1.setBackground(Color.cyan);
L1.setForeground(Color.gray);
b = new Button("Enter");
t1= new textField(1,'Judi,10);
t1= setEnabled( false);
ta2 new TextArea("welcome to csc”);
Cb1 = new checkBox("sports");
cb2  = new checkBox(" Television");
cb3= new checkBox("Reading Books”);
cb4 = new checkBoxGroup();
gb1 = new checkBoxGroup();
gb2 = new checkBoxGroup();
rb1 = new checkBox(“male”, gb1, False);
rb2 = new checkBox("female",gb1,False);
rb3 = new checkBox("Married”,gb1,false);
rb4 = new checkBox ("single ",gb2,false);
Li  = new List(3);
Li = ("Marager");
Li= ("Managing directors");
li = ("clerk");
Li= add("Typist”);
li = add( "office Boy");
li  = add( "gupesvisor");
sh = new Scrollbar(Scrollbar, HORIZONTAL)
sv= new scrollbar(Scrollbar, VERTICAL1,10,1100);
add(L);add(t1);add(ta);
add(cb1); add(cb2); add(cb3);
add(cb4); add(rb1); add(cb3);
add(cb4); add(rb4); add(Li);
add(c); add(sh); add(sv); add(b);
}           }
//< applet code ="comp class' height = 450 width = 700 >


Event handling
It is essential is GUI programing The prog waits for a uses to perform some action.

Components Of event
1. Even handles       2. Event source        3. Event object
getSource()
This method, which returns the referemce to the component, that generate the event.  Ir returns which component occurs.
Event cotegory
Interfacemain
Method
Action
actionListener
action performed (Action         Event object name)
Item
itemListener
Item Statechanged (Item Event object name)
WindowEvent
WindowListener
Window closing (window Event objct name
Window opened (window Event obj name)
Window Activate (window Event obj name)
Window Deactivated ( window Event obj name
Window closed (window Event obj name)
Window I conified ( window Event onj name)
Window  Deiconified  (window event obj name)
MouseMotion
MouseMotionListener
(1) Mouse Drogged (Mouse Event obj name)
Mouse Moved (mouse Event obj nam)
MouseEvent
MouseListener
Mouse pressed (mouse Event objname)
Mouse Released (Mouse Event obje name)
Mouse clicked (Mouse Event obj name)
Mouse Entered (Mouse Event. onje name)
Mouse Exited (Mouse Event offe name )
Key
KeyListener
(1) key presed (key Event objc name)
(2)  Key Released ( " ")
Key typed ( ")
Focus
FocusListener
Focus Gained (Fous event obj name)
Focus Lost ( ")
Scrollbar
AdjustmentValuesListener.


Eg: for Button Event
import java. awt.*;
import java.  Applet. *;
import java. awt. awt. event.*;
Public class eventl extends Applet implements ActionListener
{           Textfield t1,t2,t3,
Button b1,b2;
public void  init()
{           t1 = new Textfield(10);
t2 = new Textfield(10);
t3 = new Textfield( );
b1 = new Button(“add”);
b2 = new Button(“sub”);
b1.addActionListener(this);
b2.addActionListener(this),
add (t1); add (t2); add (t3); add (b1); add (b2);     }
public void actionPerformed(actiong event ae)
{           if (ae. getSource( ) == b1)
            {           int z = Integer.praseInt(t1.getText())+Integer.parseInt (t2.getText());
t3. setText(strubg, value(), f(2));     }
            if (ae. getSource ( ) == b2)
            {           int y =Integer.parseInt(t1.getText ( ))+Integet.parseInt(t2.getText());
            t3. setText(String.value(),f(z));        }
if (ae. getSource() == b2)
{           int y= Integer.parseInt(t1.getText())+Integer.parseInt(t2.getText());
t3.setText(String.value(),f(y));         }     }     }
            //

***
Program on applet methods
import java.io.*;
import java.awt.*;
import java.applet.*;

public class app1 extends Applet
{
            int xs[] = {40,49,60,70,57,40,35};
            int ys[] = {260,310,315,280,260,270,265};
            int xss[] = {140,150,180,200,170,150,140};
            int yss[] = {260,310,315,280,260,270,265};
            public void paint(Graphics g)
            {
                        g.drawString("Hello",40,20);
                        g.drawLine(40,30,200,30);
                        g.drawRect(40,60,70,40);
                        g.fillRect(140,60,70,40);
                        g.drawRoundRect(240,60,70,40,10,20);
                        g.draw3DRect(140,120,70,40,true);
                        g.fillOval(40,180,70,40);
                        g.drawArc(140,180,170,40,0,180);
                        g.drawPolygon(xs,ys,7);
                        g.fillPolygon(xss,yss,7);
            }           }
//

Program to draw a lamp

import java.io.*;
import java.awt.*;
import java.applet.*;

// Lamp

public class lamp extends Applet
{
            public void paint(Graphics g)
            {
                        g.setColor(Color.red);
                        g.fillRect(90,250,130,50);
                        g.drawLine(125,250,125,160);
                        g.drawLine(175,250,175,160);
                        g.drawArc(85,157,130,50,-65,312);
                        g.drawArc(85,87,130,50,62,58);
                        g.drawLine(85,177,119,89);
                        g.drawLine(215,180,181,89);
                        g.fillArc(78,120,40,40,63,-174);
                        g.fillOval(120,96,40,40);
                        g.fillArc(173,100,40,40,110,180);
            }
}

//


Eg: To find factorial
public class fact
{int factl (int n)
            {if (n <=1)
returm 1
else
            return (n*fact1 (n-1);}
public statoc vpod main (string dc (J)
{int fa, fb, fc, a=4 , b=5, c=16;
factlf,
f= new fact1 ( );
fa=f.fact (a);
fb=f.
fc=f-
s.o.p. (“factional of” ta).,
}
Eg: Item Listener.
import java. owt. *;
import java. owt.event *;
import java. applet. *;
public class checkevent extends Apple implements ItemListener
{ checkbox c,c1,c2,c3;
String name = “ “;
public void init ( )
{c= new checkbox (“movie”);
c1= new checkbox (“T.v.”);
c2= new  checkbox (“sports”);
c3= new checkbox (Reading books”)
add (c)i add (c1); add (c3);
c.addItem Listener (this);
c1. addItem Listener (this);
c2. add Item Listener (this);
            c3. ad Item Listener (this);
}
Publicc void itemState Changed (Item Event (3)
{repaint ( );
}
Public void paint (Graphics g)
{name= c. getlabel ( )+ “ “+c. getstate ( );
            g. draw string (name , 20,200);
name = c1. getlabel ( )+” “+e2. get State ( );
g. drawstring (name , 20, 240,);
Name = 3.getlabel ( )+” “+(3.get State( );
g. drawstring (name, 20,260);
}
//




































































Net working
Thare are 3 components
(1)  Protocls
(2)  Socket
(3)  IPSddress & port No.       
Networking:
            The client /serwer model: is an application development Architecture designed to reperate the presentation of data from its internal procesin & storge
            The client request for services & the sewer services these requests.  The requests are transfromed from the client to the server, over the network.  The communication between the client & the server is an important constituent in client / server Architecture & is usually through a network.
(1)  Prodocls:

1.When computers communicate, they need to follow contain rules too.
2.Data  is sent from  are machine to another in the from of packets.  rules goven packaging of the data into its original from.  These rules are caled network


protocls.  Network protcols are set of ruler & conventions followed by systems.  That commuincat over a network.  & one examples of network protocls are:
(1)    TCP/IP
(2)    UDP
(3)    Apple talk
(4)    Net Bell I
There are 2 tools availbale in Java for commuincation.
(1)  TCP/IP
(2)  UDP
(2) Sockets:
            Traansmittion control  protocal (TCP) provides a reliable point to point commuincation channel.  That cliont /server applications can used to commuicate with each other.  Tio commenicate over PCP client/server programs established their connection& bind a socket Sockets are used to landle commuication link betwwen  application over the network control.
The socket class used to create a clientprogram  the server socket class used to create a server program.
(Socket (class):
            Socket is the Basic class which supports the TCP protocl.  TCP  is the relaibale stream network connection protocd.  The socket class provides methods for stream input output, which maeks reading from & conting to easy.  This class is indispensable to programs return to commuincate & the Internet.
Sower Sockets:
            It a class used to by Internet server programs for listine to client request.  server sockets clases not are actually perform this sewere.  Instead its create a socket object on behalf of the client.
            The  communication is peformend through the object created.
(3) IP Address & Port No:
            An Intenet server can be throught of a sot of socket clases.  That provide additional capabilities, generally called service.  Some example of services are
(1)  electornic mail
(2)  FTP
(3)  http
(4)  delnet
(5)  SMTP
each service is associated erith a port.  A port  is a numeric Address, Through which service request, such as a request for web page are procesed. The TCP request to data` hedion
(1)    Ip  Address & another one is port no.
The IP provides, even  network device with a logical address called a IP address.
      The Ip address, each in a 32 bit number, represented as a series of four. 8 Bit nos.  for example 172.17.8.182 iw qn Ip Address for www. NiiT. com (.Domain name & storage)
Notes:   The domain naming service or dms os a servoce tjat trams;ate www. NHT. com into 172.17.8.182.
Server socket constructor.:
Server socket (int,int)- Creates a server socket and binds it to  the specifid local port No.
Methods
1. accept ( ) - Listenes for a cnnection to be made to the socket and accepts it.
2.Close ( ) -closes this socket
                  3. getInetAddress ( ) - returns the local adress of this server socket.
                  4. getlocalport ( ) - return the porton which this socket is listening.
Contors of socket:

Socket (Inet Address, int) - Creater a sheam socket  & connects it to the specified port no. at the specified IPAddress.
Methods:
1.getInetAddress ( )  - return the adress to which the socket is  connected.
2. get Input stream ( ) - returns an input stream for this socket.
3.getlockal Address ( ) - gets the local adress to which the socket is bound.
4. getlocal port ( ) - returns the local port to which this socket is bound .
5. getouput Stream ( ) - returns an output stream for this socket.
6. get port ( ) - retuns  the remote port to which the socket is connected.
Buffered Reader:
            Road Text from a character - input Stream, buffering characters so as toprovide for the efficeinet reading of character, arrays and liner.
ConstruTor:
Buffered Reader (REader) - Create a buffereing character - inpent stream that uses a  default - sixed input buffer.
Method:
read( ) - read a single character.
Printwriter:
Print formatted represntation of objech to a text out put stream.
Constructor :
1. Printwriter (outpurstream)-  create a new print wirter, a without automatic line flushing, from an existing outputstream.
Method:
Print (string) - print a string.
Check box progrom in applet
import java. awt. event. *;
import java .  awt.*;
import java. applet.*;
//
{string s= " ";
Check box or, ap, bn pa;
[public void init ( )
{ Cb = new Cbeckbox Group ( );
   Or=new Checkbox ( :orange", cb, false);
bn = new checkbox ("banana," cb, false);
ap = new checkbox ( " apple, cb, flase);
pa=  new Checkbox ( " pine apple", cb, false);
add (or); (pa); add (ap ) ; add (bn);
or. add Item List ener (This);
pa. add Item List ener ( this);
bn. add Item list ener (this)
qp.  add Item  Listener ( this);
}
public void item State Changed (Item Elent e)
{
     repaint ( ) ;
}
Public void paint (graphics g)
{s= "current Selection;" ;
stcp. get Seleted Checkbox ( ). getlable ( );
g. draw String ( 5, 6, 100);
      }
}
 


Combo Box:
import java. awt. event. *;
import java.  awt.*
import java. applet . *;
Public class image1 entends Applet implements Item List ener
{
Choice c;      // ComboBox
Image im [ ] = new Image [5];
int x;
Public void init ( )
{c= new chocie ( ) ;
 c. addItem ("A");
 c. addItem ("B");
 c. addItem ("C");
 c. addItem ("D");
 c.addItem (“E”);
 im (0) = get Image (get Document Base ( ),”1.jpg”);
im (1) = get Image ( get Document Base ( ), “2.j[g”);
im (2) = getImage (get Document Base ( ), “3.jpg”);
im (3) = get Image (get Document Base ( ), “4.jpg”);
im (4) = getImage (get DocumentBase ( ) , “8. jpg”);
“im (5)= getImage (get Document Base ( ), “8. jpg”);
            add (c);
c.addItem Listener (this);
}
Public void item State Changed (Item Event ie)
{
            String na= c. getSelected Item ( );
Show Status (na);
x=c get  Selected Index ( );
repaint ( );
}
Public void paint (graphics g)
{
            g. draw Image (in [x], 0,0,700,450,this);
            }
}
11

Life Cycle  of an Applet
This life cycle of an applet can be described through four emthods.  These are;
§  The init () method
§  The start() method
§  The stop() method
§  The destroy () method
The init () method
   The init () method is called the first time an applet is loaded into the memory of the computer.  One can initialize variables and add components like buttons checkboxes to the applet using the init () method.
The start () method
      The start ()  method is called immediately after the init () method and every tuime  the applet receives focus as a resives  focus as a result of scrolling in the active window .  This method used when a process is to be restarted. Sucj as therad  animation, everytime  the  applet receives  thefocus.
The stop () method
      The stop () method is called every time the applet loses the foucs. You can use this  method to reset varoables and stop and stop the threads that are running.
The  destory () method
      The destory () method is called by the browser when the user moves to another page you can use the method to perform clean-up operations like closing file
Previewkng an applet
Through the applet are meant to run inside a browser. We can use appletviewer to preview the applet using a program called aappletviewer.  Exe/appletviewer.  Bin.  This program can be called upon a java file that contains a   (tag as a comment of  course1).  Usually when we write an applet we write an   tag inside a comment line.  More about this tag will be said laget in this chapter.
Notes:
§  The  file passed is a java file and not the class file.
§  The java file should contain an applet tag (whcich is a HTMLtag)  with a minimum of CODE.WIDTH and HEIGHT  specified.  (Applet tgs are discussed a little later in this chapter)

Taking Advantage  of the Applet APL
            The applet APL lets you take advantage of the close relationship that applets have with web browsers.  The APL us orivuded vt tge hava. Applet package-- mainly by  the Applet class and tg\he Applet Context interface.  Thanks to the applet APL, applets can do the following:
1.Be notified by the browser of milestones.
2.    Load data files specified relativeto URL of the applet or the page in which it is running.
3.    Display short status strings.
4.    Makes the browser display a document.
5.    Find other applets running in the same page.
6.    Play sounds.
7.    Get parameters specified by user in the < APPLET> tag.
Methods in Applet
            Public class Simple extends Aplet
            {
                ...
                 Public void init () {...}
                 Public void start () {...}
                 Public void stop () { ...}
                 Public void destroy () {...}
                ...
            }
The Simple applet like every other applet, features a subclass of the APP;et class.  The Simple class overides four Applet methods so that it can respond to major events:
Init ()
            To inititalixe the applet each time  it’s loaded (or reloaded).
Start()
            To start the applet’s execution,  such as when the applet’s loaded or when the user revisits a page that contains the applet.
Stop()
            To stop the applet’s execution, such as when the user leaves the applet’s
page or quits the browser
destory ()
            To perform a final cleamup in prepartion  for unloding.

BUTTONS
            A Button is a user interface component, when pressed with the mouse, triggers some action.
            Button ( )
            Button (String)
Eg.,
import  java.awt.*;
import java.aplet.*;
public class buttontese extends java.  applet.  Applet
{
            public void init
            {
            Button b1=new Button ( );
            add (b1);
b1. setlabel (“REVIND”);
Button b2=new Button (“play”);
add (b2);
add (new Button (“Fast Forward”) );
add (new Button (Stop) );
   }
}
LIST’
            The list is a component that allows us to choose one (or) multiple items (Strings) from a list of items.  The list may be scrollable.  Lists can allow either multiple selections (or) just one selection at a time.
            List ( ) - creates a list
List (int, boolean )   -
            Creates a list with rows, visible rows and given multiple selection behavior.  The second parameter when given true, will allow multiple selection in the list.
List Method
            additem ( )     adds the specified item at the specified index.
            getitem ( )       Returns the string
            clear   ( )         deletes all the items in the list
            delitem ( )       deletes the item specified by the index
            select ( )         selects item by an index
Eg:
import java.awt.*;
import java.aplet.*;
public class listtest extends Applet
{
            Public void init ( )
            {
            List 11 = new list ( );
            11.additem (“Sony”);
            11.additem (“Thomson “);
            11.additem (“Panosonic”);
            11.additem (Samsung”);
            11.additem (“Phillips”);
            List 12=new list (4,true);
            12.additem(“Television”);
            12.additem (“Computer”);
            12.additem (“Computer”);
            12.additem (“Aircooler”);
            12.additem(“Washing Machine”);
            add(11);
            add(12);
            }
}
           
           
           

           

EVENTS:
            Event is an object that describes a state change in the source.  Events may be of different types namely mouse clicks, key presses, netwrok data arriving on the port and many.
Event delegation model:
            A souce generates an event and sends it to one or more listeners.  The listeners simplay waits until it receives an event.  Once received, the listener proceses the event  and then returns. Listeners must register with a source in order to receive an event notification.
Event Source:
            A source is an object that generates an event.  Sources may generate morethan one type of event.
            A source must register listeners.  In rder for the listerners to receive notifications about a specific type of event.  Each type of event has its own registration method.
Syntax:          
            public void add Type Listener (Type Listener el)
Event Listener:
            A listener is an object that is notified when an event ocurs.  It has two major requirements.  1. It must have been registered with one or more sources to receive notifications about specific types of events.  2. It must implement methods to receive and proces these notifications.
Eg.,
import hava.apple.applet;
import java.awt.*;
import hjava.awt.evernt*;
public class clicket extends Applet implements Action Listener
{
            Text Field t;
Button b;
Public void init ();
{
t=newTextField (20);
add(t);
b=new Button (“click me”);
add (b);
}
}

The way the delegation based event model works is that events are passed from source controls to listener objects.  We connect listener to our buttons.  When an event occurs, the listener object will hear it.
import hava.applet.applet;
import  java.awt*;
import hava.awt.event*;
public class clicker extends Applet implements ActionListener
{
Strings1;
            Button b1 =new Button (“OK”);
            Button b2=new Button (“Cancel”);
            public void init (
            {
            add (b1);
            add(b2);
            b1.addAction Listener (this);
            b2.addAction Listener (this);
            }
            Public void actionperfomed (ActionEvent e)
            {
            String S= e.getAction Command(;
If (S.equals (“Ok”) )
S1=”OK Clicked”;
If (S.equals (“Cancel”) )
S1=”CancelClicked”;
}
/*

*/
eg:
import java.applet.applet;
import java.awt.*;
import java.awt.event*;
public class clicker extends Applet implements ActionListener
{
            TextField t;
            Button b;
Public void init ()
{
t=mew
TextField (20);
add(t);
b=new Button (“Click me”);
add (b);
b.addAction Listener (thios);
}
Public void action performed (ActionEvent e)
{
String msg=new string(“Welcome to USA”);
If (e.getSource()==b)
{
t.setText(msg);
}
}
            }
Handling Multiple Events
import java.applet.applet;
importjava.awt.*;
import java.awt.event.*;
public class clicker extens Apllet implements ActionListener
{
            TextField t;
            Button b1;
Button b2;
public void init ()
{
t=neww TextFied (20);
add(t);
b1=new Button (“click this”);
add(b1);
b1.addActionListener (this);
b2=new Button (“click this too”);
add(b2);
b2.addActionListener (this);
}
public void action performed (ActionEvente)
{
            if(e.getSource(_==b1)
            {
            t.setText (“Welcome to India”);
            }
            if (e.getSource()==b2)
            {
            t.setText(“Welcome to USA”);
            }
}
            }
            }
ITEM EVENS
//program to show the items in a particular fashion by choice
import java.applet.applet;
import java.awt.*;
import java.awt.event.*;
public class choice extends Apple implements Action Listener
{
            TextField t;
            Choice c;
            public void init ()
            {
            add(t=newTextField (20) );
            c=new choice ();
            c.add(“Apple”);
            c.add(“Orange”);
            c.add(“Grapes”);
            add(c);
            c.addItemListener (this);
            }
}
LAY OUT MANAGERS
            The layout manager’s classes are set of classes that help to position the components in a container.  The layout manager determines how AWT components are  dynamically arranged on the screen.  Each panel on the screen can have its own layout  manager.  By nesting panels within panels, using the appropriate layout manager for each one, we can often arrange ou UI to group and arrange components in a way that is both functionally useful and that looks good on a variety of platforms and windowing system.
There are five basic layout managers.
1. Flow layout           2.Border layout         3.Cardlayout             4.Gridlayout 5.GridBag layout
1.Flow layout:
            It is the default layout manager.  This flow layout clas implements a simple layout style, which is similar to how words folw in text editior.  Flow layout aranges components from left to right in rows.  By derault, the flow layout alignment will be

CENTER.
            Setlayout (new Flowlayout (flowlayout. LEFT) );
Eg.,
import java.awt.*;
import java.applet.*;
public class Flowtest extends Applet
{
            public void init ()
            {
            setLayout (new FlowLayout *(FlowLayout.LEFT) );
            add(newButton(“one”));
            add(newButton (“Two”) );
            add(newButton(“Three”) );
            add( newButton (“Four”));
add(new Button (“Fuve”) );
}
}

           
           
           

           



Write a program in java to perform matrix addition?
import java.io*;
public class Arrays
{
public static void main (String s[ ] throws IOException
{
Sclass s1 =new Sclass (“Suzuki”,40000);
int a [ ] [ ] = new int [3] [3];
int b [ ] [ ]= new int [3]  [3];
int c [ ] [ ] = new int [3] [3];
int ij;
sl. show fn ();
Buffered Reader br = new Buffered Reader (new InputStream Reader (System.in) );
System out.println (“Enter NINE elements (3X3):”);
for (i=0;i
for (j=0;j
a[i][j]=Integer.parseInt(br.readLine());

for (i=0;i
for (j=0;j
c[i][j]= a [i][j]+b [i][j];

fpr  (i=0;i
{
for(j=0;j
   System.out.print(c[i][j]+”\t”);
System.out.println();
      }
  }
}
2. Write a java program to write a string to a file using byte array stream class?
           
 import java.lang.Exception;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;

public class Barray - op-st
{
 public static void main (String a [ ])
   {
try
 {
String s= “Please Enter”;
byte b [ ] =s.getBytes ();
Byte.ArrayOutputStream b1 =new Byte.ArrayOutputSteam ();
b1. write (b);
File OutputStream f= new FileOutputStream (“uexcept.j”);
b1.write To (f);
byte b2 [ ] =b1.toByteArray ();
}
catch (Exception e)
{
 System.out.println (e);
  }
 }
}
3. Write a java  program to print the content of a file using File Stream Class?
import java.io.FileIbputStream;
import java.io.FileOutputStream;
import java.lsng.Exception;

public class Concatfiles
{
public static void main (String s [])
{
try
{
int,i,t,c;
String ch = ” “;
File OutputStream f1 =new File OutputStream (“Outj”);
i=0;t=s.length-1;
while (i<=t)
{
FileInputStream f=new FileInputStream(s[i]);
while ( (c=f.read () !=-1)
 ch=ch+(char)c;
byte b [ ]=ch.getBytes 9 ();
f1.write (b);
f.close ();
i++;ch=” ”;
}
f1.close ();
}
catch (Exception e)
{
System.out.println (e);
  }
 }
}



4.Write a program for converting yen to rupees and pounds to rupes.
import java.lang.System:
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

class money
{
private int y,r,p;
public money ()
{
r=0;y=0;p=0;
public void ­yen _rs()
{
r=y*20;
System.out.println (“The Corresponding Rupees for yen is:”+r);
}
public void pound _rs()
{
r=p*85;
 System.out.println (“theCorresponding Rupees for pounds is ;”+r);
}
public void input (intf)throws IOException
{
String s;
BufferedReader br=new BufferedReader (new InputStreamReader (System.in) );
if (f = =1
{
System.out.println(“Enter the yen:”);
s=br.readLine ();
y=Integer.parseInt (s);
}
if (f= =2)
{
System.out.println (Enter the pounds:”);
s=br.readLine ();
p=Integer.parseInt(s);
  }
 }
}
public class Convert
{
public static void main (string a [ ])throws IOException
{
money m= new money ();
String s;
int k;
System.out.println (“1-Yen to Rupees”);
System.out.println (“2-pounds to Rupees “);
BufferedReader br= new BufferedReader (new InputStreamReader (System.in) );
s=br.readLine ();
k=Integer.parseint (s);
m.input (k);
if (k = =1)m.yen_rs();
if (k==2)m.pound_rs ():
 }
}

5.Write a java program to copu a file?
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.lang.Exception
  public class Copy file
{
public static void main (String s [ ])
{
try
{
int i,t,c;
String ch = “ “;
FileOutputStream f1 = new File Output Stream (s[1]);
FileInputStream f=new FileInputStream (s[0]);
while ((c=f.read ()!= -1)
{
ch=ch+(xhar)c;
}
byte b[]=ch.getBytes ();
f1.write (b);
f1.close ();
f.close();
}
catch (Exception e)
{
 System.out.println (e);
  }
 }
}
6.Write a java program to count the no of  words in given file?
  import java.lang.System;
import java.io.FileInputStream;
import java.lang.Exception;
import java.lang.String;

public class Count _all_words1
{
public static void main (String s[])
}
try
{
FilenputStream f=new FileInputStream (s[0]);
int word1=1,c,flag=0,i=0,j=0;
String ch=” “,word=” “,arrl=” “;
char ch1;
String arr []=new String [100];
while ((c=f.read () )1=-1)
ch+=(char)c;

while (i
{
ch1 =ch.charAt(i);
if (ch1==”) {arr[j]=arr1,flag = 0;j++;arr1=””;}
else arr1=arr1+ch1;
i++;
}

}
for (i=m+1;i
if (arr[m].equals(arr[i])) {world1++;arr[i]=””;
if(arr[m]!””)
 System.out.println(“The number of times of occurence of the “+arr[m]+”is:
“+word1);
 word1=1;
}
f.close ();
}
catch (Exception e)
}
System.out.println (e.getMessage());
  }
 }
}
7 Write a java program to count the number of words, vowels, line in a given file?
 import java.io.FileInputStream;
import java.lang.Exception;
public class Count_ file_ all
{
public static void mai  (String s [])
{
try
{
FileInputStream f=new FileInputStream (s[0]);
int c=0,w=1,v=0,1=1;
int ch,i;
char ch1 []= {‘a’,’e’,’i’,’o’,’u’,};
while((ch=f.read ())!=-1)
{
for (i=0;i<5 i="" o:p="">
if ((char) ch==ch1[i])v++;
if (char)ch==”)2++;
if ((char) ch==’\n’) {1++;pN++;}
else c++;
}
f.close()
System.out.println (“characters:”+c+”; words: “+w+”; vowels: “+v+”; lines:
“+1)
}
catch (Exception e)
{
System.out.println (e);
  }
 }
}


8. Write a java program to find how manu times a given word has occured?
import  java.io.FileInputStream;
import java.lang.Exception;
import java.lang.String;

public class Count_word
{
public static void main (string s[])
{
try
{
FileInputStream f=new FileInputStream (s[0]);
String w=s[1];
int word=0,c,flag=0;
String ch=””;
while ( ( c=f,read ()) != -1)
{
if (char) c!=” ch=ch+(char) c;
else flag =1;
{
if (ch.compare To(w) ==0) word++;
flag =0;
ch=””;
 }
}
System. out,println(“The number of times of occurence of the word is : “+word);
f.close();
catcg (Exception e)
{
System.out.println(e);
   }
 }
}
8.Write a java program to decrypt a file?
 import java. lang.System;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.lang.Exception;

public clas Decrypt
{
public static void main(String s [])
{
try
{
FileInputStream f=new FileInputStream (s[0]);
FileOuputStream f1=new File OutputStream s[1]);
String ch=””;
int c;
while((c=f.read()!=-1)
ch+=(char)(c-s[2].length());
byte b[] =ch.getBytes ();
f1.write (b);
f.close
f1.close();
}
catch(Eception e)
{
System.out.println(e.getMessage());
    }
  }
}
10. Write a java program to encrypt a file
import java.lang.System;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.lang.Exception;

public class Encrypt
{
public static void main (String s[])
{
try
{
FileInputStream f=new FileInputStream(s[0])
FileOuputStream f1=new FileOutputStream(s[1]);
String ch=””;
int c;
while ((c=f.read() !=-1)
 ch +=(char)(c+s[2].length());

byte b[]=ch.getBytes();
f1.write(b);
f.close();
f1.close();
}
catch(Exception e)
{
System.out.println(e.getMesage());
  }
 }
}

11.Write a program to show how divide by error Exception in java>
import java.lang.System;
import java.lang.Exception;

public static void main (String a[])
{
public class Except1
{
public static void main (String a[])
{
try
{
int il=1,i2=0,i3;
i3=i1\i2;
}
catch (ArithmeticException e)
{

12.Write a program to show how array out of bounds Exception handled in java?
import java.lang.System;
import java.lang.Exception;

public class Ex ept2
{
public static void main (string a[])
{
try
{
inti1=10,i2,i3;
int s[]=new int [5];
s[7]=100;
}
catch (Arithmetic Exception e)
{
System.out.println )e.getMessage());
}
catch (ArraryIndex OutOfBoundsException e)
{
Sysem.out.println(e.getMessage());
   }
 }
}
13.Write a Java program to print N fibonic Series?
import java.lang.System;
import java.io.BufferedReader;
import java.io.InputstreamReader;
import java.io.IoException;
public class Fibo
{
public static void main(String a[]) throws IoException
{
String str;
InputStreamReader n=new InputStreamReader(System.in);
BufferedReader m=newBufferedReader(n);
System.out.println(“Enter the N value:”);
str=m.readLine();
inti,j;
int f1,f2,f3;
f1=0;f2=1;
i=Integer.parsent(str);
System.out.println(f1+f2);
for(j=1;j
{
f3=f1+f2;
System.out.println(f3);
f1=f2;
f2=f3;
}
}
}
14. Write a java program to find the factorial of a given Number?
import java.lang.System:
import java.io.InputStreamReader;
import java.io.IoException;
import java.io.BufferedReader;
public class Factorial
{
public static int fact (int i)
{
int j,s=1;
for(j=1
s*=j;
return (s);
public static void main(String a[]) throws IOException
{
String str;
InputStreamReader p=new InputStreamReader(System.in);
BufferedReader m=newBufferedReader(p);
System.out.println(“Enter the value for finding factorial:”);
str=m.readLine();
int n,sum=0,i;
n=Integer.parselnt(str);
for(o=1;i
sum+fact(i);
System.out.println(“The sum of factorial is:”+sum);
}
}
15.Write a Java program that reads the given string?
import java.io.FileOutputStream;
import java.lang.Exception;
import java.lang.string;

public clas File_op_at
{
public static void main(String a[])
{
try
{
String s=”Thank you very much”;
byte b[]=s.getBytes();
FileOutputStreamf=newFileOutputStream(“uexcept.j”);
f.write(b);
f.close();
}
catch(Exception e)
{
System.out.println(e);
  }
 }
}
16. Write a program to show how inheritance is done in java?
import java.lang.System;
import java.io.IOException;

class Sclass
{
protected String name;
protected float price;
public Sclass(String n,float p)
{
public void show_fn()
{
System.out.println(“Name”+nme+” “+price”+price);
   }
}
class Sclass1 extends Sclass
{
public sclass1(String s,float p)
{
super(s,p);
}
void display()
{
System.out.println(“Rs”+price+” per”+”one”+name);
 }
}
public class Inherit
{
public static void main(String a[])throwsIoException
{
Sclass sup=new Sclass(“cycle”2000);
Sclass 1 sub=new Sclass1 (“motor”,4000);
sup.show_fn();
sub.display();
sub.show_fn();
}
}
17. Write a  java program that reads the name,address,calls and calculate the total call Bill?
import java.lang.System;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

public class p_bill
{
public static void main(String a[])throws IOException
{
String name, addr;
String s;
int calls;
float sum
BufferedReader br=new BufferedReader(newInputStreamReader(System.in));
System.out.print(“Enter the Name:”);
name=br.readLine();
System.out.print(Eenter the Address”);
addr=br.readLine();
System.out.print(“Enter the total number of calls:”);
s=br.readLine();
calls=Integer.parseInt(s);
sum=0.0f;
if(calls>250) {sum+=(calls-250)*2.75f;calls=250;}
if ((calls>150)&&(calls<250 calls-150="" calls="150;}<o:p" f="" sum="">
if(calls<=150) sum+=(cals*1.50f);
System.out.println(“The Name is;”+nsme);
System.out.println(“The Address is:”+addr);
System.out.println(“The Amount for “+calls+”calls is”+sum);
}
}
18.(a) Write a java program to check if given no is a Armstrong or not?
(b) Write a java program to check if given no is prime or not?
import java.lang.System;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

public class primearm
{
public static void main (String a[]) throws IOException
{
System.out.println(“1-prime number”);
System.out.println(“2-Armstrong number”);
InputStreamReader p=new InputStreamReader (System.in);
BufferedReader m=new BufferedReader(p);
Strint s;
System.out.print(“Enter the option:”);
s=m.readLine();
int n,i,f0,1sum;
n=Integer.parseInt(s);
if(n==1)
{
System.out.print(“Enter the nummber.”):
w= m.readLine();
n=Integer.parseInt(s);
for (i=2;i
if (n%i==0) {f=1;break;}
if(f==0)System.out.println(“The given number”+n+”is prime”);
else
System.out.println(“The given number”+n+is not prime”);
}
else
{
System.out.print(“Enter the number:”);
s=m.readLine();
f=Integer.parseInt(s);
sum=0;
while(f>=1)
{
1=f%10;f=f\10;
sum+=(1*1*1);
}
f=Integer.parseInt(s);
if(f==sum) System.out.out.println(“The Number Is Armstrong”);
else System.out.println(“The Number Is Not Armstrong”);
   }
 }
}
19. write a java program to create and read a student record with following fields Name Reno,Mark?
import java.io.Bufferedreader;
import java.io.InputStreamReader;
import java.io.printStream;
import java.lang.Exception;
import java.io.IOException;

public class Record_w
{
public static void main (String s[]) throws Exception
{
try
{
  FileOutputStream f=newFileOutputStream(s[0]);
printStream p=newPrintStream(f);
BufferedReader br=new BufferedReader (InputStreamReader(System.in));
int op=1;
String name, rno;
int tmark;
while (op!=0)
{
System.out.print(“Enter the Name:”);
name=br.readLine();
System.out.print(“Enter the Rollno:”);
rno=br.readLine();
System.out.print(“Enter the total mark:”);
tmark=Integer.parseInt(br.readLine());
System.out.ptint(“Do you  want to continue(0\1):”);
op=Integer.parseInt(br.readLIne());
p.println(rnp+”:+name+”:”+tmark);
 }
}
catch(Exception e)
{


System.out.pintln(e.getMessage());
  }
 }
}
20 Write a java program to read a sequencal file using file Input Stream?
import java.io.SequenceInputStream;
import java.io.InputStream;
import java.io.FileInputStream;
import java.lang.Exception;

public class Seq_ip_st
{
public static void main(String a[])
{
try
{
   InputStream i1=new FileInputStream(“uexcept j”);
   InputStream i2=new FileInputStream (“uecept[].j”);
SequenceInputStream s=new SequenceInputStream(i2,i1);
int ch;
While((ch=s.read())!=-1)
{
Sustem.out.print((char) ch);
}
   s.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
21. Write a program to show how priority threads are used in Java?
import java.lang.System;
import java.lang.InterruptedException;
class Tjr extends Thread
{
Thread t;

public Thr(String name, int prior)
{
 t=new Thread(this, name);
t.setpriority(prior);
t.start();
}

public void run()
{
try
{
for(inti=0;i<10 i="" o:p="">
{
System.out.println(t.getName()+i);
t.sleep(100);
 }
}
catch(InterruptedException e)
{
System.out.rintln(e);
    }
  }
}
public class Thr join
{
public static void main(String s[])
 {

Thr c1=new Thr(“one”,thread.NORM _PRIORITY);
Thr c2=new Thr(“two”,Thread.MIN PRIORITY);
Thr c3=new Thr(“six”, Thread.MAX_PRIORITY);

System.out.println(“T1 is alive:”+c1.t.isAlive());
System.out.println(“T2is alive:”c2.t.isAlive());
System.out.println(“T3 is alive:”+c3.t.isAlive());

try
{
    c1.t.join();
    c2.t.join();
    c3.t.join();
    Thread.sleep(100);
}
catch(InterruptedException e)
{
 System.out.println(e);
}
  System.out.println(“main thread existing”);

System.out.println(“T1 is alive:”+c1.t.isAlive());
System.out.println(T2 is alive: “+c2.t.isAlive();
System.out.println(“T3 is alive:”c3.t.isAlive();

22 Write a  multithread program in Java.
import java.lang.System;
import java.lang.String;

class Thr extends Thread
{
Thread t;
  public Thr(String s)
  {
  t=new Thread(this,s);
  t.start();
   }
public void run()
{
try
{
for(inti=0;i<10 i="" o:p="">
{
  System.out.println(t.getName()+i;
t.sleep (100);
  }
}
catch(InterruptedException e)
{
 System.out.println(e);
  }
  }
}
public class Thr_multi
{
public static void main(String s[])
{
new Thr(“child”);
try
{
  for(int i=0;i<10 i="" o:p="">
  {
System.out.println(“main”+i);
Thread.sleep(500);
   }
}
catch(InterruptedException e)
{
   System..out.println(e);
     }
  }
}






23. Write a Java program to raise a userdefined  exception for minimum  balance for a given a\c no.

import java.lang.System;
import java.lang.Exception;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
class ExceedsException extends Exception
{
public String disp_message()
{
return “please enter the valid value(aount mustbe>100)”;
 }
}
public  class Uexcept
{
public static void main(String a[]) throws IOException
{
try{
Buffered Reader br=new BufferedReader(new InputStreamReader(System.in));
String accno;
Int amount;
System.out.print (“Enter the account number”);
Accno=br.readLine();
System.out print(“Enter the amount”);
Amount = integer. ParseInt(br. ReadLine();
If(amount <100 exceedsexception="" new="" o:p="" throw="">
else
{
System.out.println(“The account no=”+accno);
System.out.println(“The amount=”+amount);
 }
}
catch(ExceedsException s)
{
System.out.println(s.disp_message()); 
  }
 }
}





24. Write  a java program that check a file for the following
(a) can read
(b) can write
(c) is Directory
(d) is File
(e) last modified

import java.io.File

public class Ufile
{
public static void main(String a[])
{
try
{
File f1=new File(“Ufile.txt”);
File f2=new File(“me.text”);
System.out.println(f1.getName());
System.out.println(f1.canRead());
System.out.println(f1,canWrite());
System.out.println(f1.isDirectory());
System.out.println(f1.isFile());
System.out.println(f1.lastModified());
f1.renameTo(f2);
System.out.println(f2.isFile());

}
catch(Exception e)
{
System.out.println(e);
  }
 }
}

            import java.sql.*;
            public class Acc_emp
{
public static void main(String s[])
{
try
{
String url=”jdbc:odbc:con_acc”;
Class.forName(“Sun.Jdbc.odbc.JdbcodbcDriver”);
Connection con=DriverManager.getConnection(url);
Statenebt stnt=con.create Statement();
ResultSet rs=stmt.executeQuery(“select*from e_add”);
While(rs.next())
{          
   System.out.println(“Employee no:””+rs.getString(“id”);

  System.out.println(“Employee name:”+rs.getString(“name”));
   System.out.println(“Employee city:”+rs.getString(“city”));
   System.out.prinln(“Employee country:”rs.getString(“ctry”));
  }
}
   catch(SQLException e)
  {
  System.out.println(e.getMessage());    
         }
   }
}

25. Write a java jdbc program to create or to alter a table at Runtime.
            Import  java.sql.*;
            Import javax.swing.*;
            Import java.awt.*;
            Import java.awt.event.*;
            Import java.awt.GridBagLayout;
            Import java.awt.GridBagConstraints;

            Public class Cre_table Extedns Jframe implements ActionListener, ItemListener
{
 static int f_I=0;
 static int t_I=0;
 static int w_I=0;
GridBagConstraints gc=newGridbagLayout()
GridBagConstraints gc=newGridBagConstraints();
Jlabel 1[]=newJLabel[5]
String f_name[]=new String[20];
String t_name[]=new String[20]
String width[]=new String[20];
String s[]={Enter The Table Name:”Number Of fields:”,”Enter The Field
Name:”,
                        “Enter the Field Type:”,”Field width”};
            String d_type[]={“Number”,varchat”,char”};
            JtextField[]=newJTextField[5];
            JButton b=new Jbutton(“Create”)
            Jbutton b1 =new Jbutton (“Next Field”);
            JcomboBox  c= new JcomboBox(d_type);
            Container p = getContentPane();

            public Cre_table ()
            {
            p.setLayout (gb);
            for (int j=o;j<5 j="" o:p="">
            {
                        1[j]=new Jlabel (s[j]);
                        t[j]=new JtextField (20);
            }
            t[3].setText(“Number”);t[3].setEnabled(false);
            b1.setEnabled(true);
            gc.gridx=o;gc.gridy =o;
            gc.insetet.top=5;
            gc.insets. bottom=5;
gc.insets.right=5;
            gc.insets.left=5;
            for(int j=0;j<5 j="" o:p="">
            {
                        gb.setConstraints(1[j],gc);
                        gc.gridx++;padd(1[j]);
                        gb.setConstraints(t[j],gc);
                        if(j==3){          
                                                gc.gridx++;
                                                gb.setConstraints(c,gc);
                                                p.add(c);
                                    }
gc.gridx=o;gc.gridy++;
            }
            c.addItemListener(this);
            gc.gridx++;gb.setConstraints(b,gc);
            gc.gridy--;gc.gridx=2;
            gb.setConstraints(b1,gc);
            p.add(b1);
            t[4]addFocusListener(newMyadapter());
            b.addActionListener(this);
            b1.addActionKustener(this);
            addWindowListener(newMywindowAdapter());
            p.add(b);
            t[0].requestFocus();
            }
            classMywindowAdapter extends Window Adapter
{
public void window closing(WindowEvent e)
{
            system.exit(0);
}
    }

class Myadapter extends FocusAdapter
{
public void focusLost(FocusEvent e)
{
 JtextField tf=(JtextField)e.getSource();
if (tf==t[4])     
            if (Integer. parseInt(t[1].getText())==w_i+1)
            b1.setText(“Click”);
}
}

public void itemStateChange(ItemEvent e)
{
JcomboBox c1=(JcomboBox) e.getSource();
t[3].setText((String)c1.getSelectedItem());
}
public void actionPerformed(ActionEvent e)
{
try
{
 Jbutton jb=(Jbutton) e.getSource();
if(jb==b)
{
 Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
 Connection   conn=
DriverManager.getConnection(“jdbc:odbc:v_ora”,scott”,tiger”);
            PreparedStatement ps = conn.prepareStatement(“create table
“+t[0]/getText()+”(“+f_name[0]+””+t_name[0]+”(“width[0]+”))”);
            int op=ps.executeUpdate();
            if(op==-1)
            {
                        ofr(int j=1;j
                        {
                        PreparedStatement pt =conn.prepareStatement(“Alter table
“+t[0].getText()+”add(“+f_name[j]+””+t_name[j]+”(“+width[j]+”))”;
                        op=pt.executeUpdate();
            if(op!=-1)break;
            }
            System.out.println(“Table created”);
}
     }
else
{
            width[w_i]=t[4].getText();w_i++;
            f_name[f_i]=t[2].getText();f_i++;
            t_name[t_i]=t[3].getText();t_i++;
if (Integer.parseInt(t[1].getText ()==w_i)b1.setText(“Click”);
            else t[2].requestFocus();
            for (int j=2;<5 j="" o:p="">
                        t[j].setText(“”);
}
}catch(Exception x)
 {
   System.out.println(x);
}
         }
public  static void main (String s[])
{
Cre_table ct=new Cre_table();
            ct.setSize(600,300);
            ct.setVisible(true);
            }
    }
26. Write a Java program to display theodbc driver Information
            import java.sql.*;

            public class Db_meta
            {
            public static void main(String s[])
            {
            try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection                                                   con
DriverManager.getConnection(“jdbc:odbc:v_ora”,scott”,tiger”);
            DatabaseMetaData db=con.getMetaData();
            System.out.println(db.getDriverName());
            System.out.println(db.getDriverVersion());
            }
            catch(Exception e)
            {
             System.out.println(e);
             }
       }
}
Compiled from Drivermanager.java
public calss java.sql.DriverManager extends java.langObject{
            static{};
   public static synchronized void deregisterDriver(java.sql..Driver) throws  java.sql.SQLException;
    public static sybcgribuzed java.sql.Connection(java.lang.String)throws java.sql.SQLException;
   public static synchronized java.sqlConnection getConnection(java.lang.String,java.lang.String,java.lang.String) throws java.sql.SQLExceptio n
   public static synchronized java.sql.Commection getConnection(java.lang.String,java.util.Properties)throws java.sql.SQLException;
   public static synchronized java.sql.Driver getDriver(java.lang.String) throws java.sql.SQLException;
   public static synchronized java. ution.Enumeration getDrivers();
            public static java.io.printStream getLogStream ();
public static java.io.printWriter getLogWriter();
public static int getLogin Tmieout();
static void initialize();
public static synchronized void println (java.lang.String);
public static synchronized void registerDreiver(ava.sql.Driver)  throws java.sql.SQLException;
public static synchronized void setLogStream(java.io.PrintStream);
public static synchronized void setLogWriter(java.io.printWirter);
public static void setLoginTimeout(int);
}


            importjava.sq1.*;
            import java.utiol.*;

            public class Drivers_detail
 {
   public static void main(String a[])
     {
      try
       {

            Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
            Enumeration enum =DriverManager.getDrivers();
            System.out.println(“AvailableDrivers”);
            while(enum.hasMoreElements())
            {
              Driver driver =(Driver) enum.nextElement();
              System.out.println(“Driver                        :”+driver.getClass().getName());
              System.out.println(“Major version           :”driver.getMajorVersion());
              System.out.println(“Minor version           :”driver.getMinorVersion());
              System.out.println(JDBC compliant       :”driver.jdbcCompliant();
            }
}catcg(Exception e)
            {
              System.out.println(e);
    }
 }
}
network.

27. Write a java program to send and get data for the local host and the server port using Datagram.

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

            public class Client_dgram
            {
            public static int Client_port =999;
            public static int Server_port=666;
            public static int buffer_size=1024;
            public static byte Buffer []=new byte[buffer_size];

            public static void main (String s[]throws Exception
            {
            try
{
DatagramSocket ds=newDatagramSocket(Client_port);
BufferedReader            br           =            new              BufferedReader(new InputStreamReader (System.in));
Datagrampacket p=new DatagramPacket(buffer,buffer_size);
while (true)
{
            buffer=br.readLine()).getBytes ();
            ds.send(new
Datagrampacket(buffer,o,InetAdress.getLocalHost(),Server_port));
            ds.receive (p);
            System.out.println(new String (p.getData(),o,p.getLength()));
            }
            }
catch(Exception e)
  {System.out.println(e); }
   }
}
28. Write a Java Program to create a client  socket     
                        importjava.net.*;
                        import java.io.*;

                        public class Client_sockextends Thread
{
public static void main (String a[])
{
try
{
  Socket csok=new Socket(“dinosaur”,2011);
InputStream inp =scok.getInputStream();
OutputStream out1 =csok.getOutputStream();
printWriter pr =new printWriter(out1);
BufferedRead br1=new BufferedReader(new InputStreamReader(inp));
BufferedReader br     =  new BufferedReader (new  InputStreamReader(System.in));
}
catch(Exception e)
{
  System.out.println(e);
}
}
publicc void run()
                        {
                        while (stop)
                           {
                             pr.println(br.readLine());
                             pr.flush();
                          System.out.println(“Message:”+br1.readLine());
                             }
                         }
                             public void stop()
                              {
                           }
                        }
29.    Write a  Java Program to implement chating for client
import java. net.*;
import java.io.*;
public clas Client_sok
{
public static void main (String a[])
{
                        try
                         {
                        Socket csok =new Socket(“ghost”,2011);
                           InputStream inp =csok.getInputStream();
                           OutputStream out 1 =csok.getOutputStream ();
                         print Writer pr=new PrintWriter (out1);
                      BufferedReader br1=new BufferedReader(new InputStreamREader(inp));
                        BufferedReader           br                   =             BufferedReader(new InputStreamReader (System.in));
                    while(true)
{
pr.println(br.readLine());
pr.flush();
            System.out.println(“message:”+br1.readLine());
                      }
                    }
                     catch (Exception e)
{
System.out.println(e);
}
                  }
               }
30. Write a Java progra to print the information about domain or   server import java.net.*;
            public class Net_addr
{
public static void main(String s[])
{
try
{
   String name=(InetAddress.getLocalHost()).getHostName();
   InetAddress inet=InetAddress.getByName(name);
  System.out.println(“String:”+inet);
  System.out.println(“HostName:+inet.getHostName());
  System.out.porintln(“hostAddress: “+inet.getHostAddress());
  InetAddress a[]=inet.getAllByName(name)l;
  for(int i=o;i
  System.out.println(“Name:”+a[i]);
  System.out.println(“LocalHost::”+InetAddress.getLocalHost());p
  }
  catch(Exception e)
  {
  System.out.println(e);
}
      }
}

No comments:

Post a Comment

CakePHP Date Picker

Folder Structure: Controller:   File location - cakephp/src/controller/HomepageController.php namespace App\Controller; use...