JAVA

Document Sample
JAVA Powered By Docstoc
					15.09.2008

What is Java?

Java is a technology from Sun Microsystems developed by James Gosling in 1991
with initial name ‘Oak’. Later converted to Java in 1995.

It is categorized in three main categories
      Java Standard Edition (Java SE)
      Java Enterprise Edition (Java EE)
      Java Mobile Edition (Java ME)

Requirements
  1. Java Development Kit
  2. Java Runtime Environment
  3. Integrated Development Environment (IDEs)
         a. Kawa
         b. NetBeans
         c. MyEclipse
         d. IBM Visual Age
         e. Oracle JDeveloper
         Etc.

Versions of Java

      Developer Version
          o For Software
                 1.0
                 1.1
                 1.2
                 …
                 1.5
                 1.6
                 1.7
      Product Version
          o 1.1
          o 1.2
          o 1.3
          o 1.4
          o 5.0
          o 6.0
          o 7.0

Source: http://java.sun.com
18.09.2008

Features of Java
   1. Simple and Secure
   2. Object Oriented
   3. Multi Threaded
   4. Portable
   5. Platform Independent
   6. Robust
         a. Garbage Collection
         b. Exception Handling
         c. Big set of classes under packages

Question
Differentiate between Portability and platform independence?


Hierarchy
      - package
           o Classes
                 Field and methods

Package
     - A collection of related set of classes and interfaces
          o java.lang (default)
                   String, System, Math, Integer, Float etc.
          o java.io  Input/Output operations
                   File, FileReader, FileWriter, InputStreamReader,
                     BufferedReader etc.
          o java.util  provides collections and utilities
                   Date, Scanner, Timer, ArrayList, LinkedList, Vector,
                     Hashtable etc.
          o java.awt  Abstract Window Toolkit
                   Button, TextField, TextArea, Menu, MenuBar, Frame,
                     Window etc.
          o java.net  Java Networking or Socket Programming
                   Socket, ServerSocket, InetAddress etc.
          o java.rmi  Remote Method Invocation
                   Naming, RemoteException, UnicastRemoteObject etc.
          o javax.servlet
          o javax.swing
          o javax.servlet.jsp
          o javax.ejb
     - To import the classes and interfaces use import command

import <packagename>.<classname>;
import <packagename>.*;  for all classes

Example
     import java.util.Scanner;
     import java.util.*;
Basic points for Java Programming
  1. File extension has to be .java
  2. Each executable Java program must have an entry point main()
         a. public static void main(String args[])
  3. Program name and class name can be same or differ except if the class is
      public then both must be same


Java Conventions
   1. All keyword and package names  always in lower case
   2. All class and interface names starts with caps
          a. String
          b. Math
          c. BufferedReader
          d. InputStreamReader
   3. All fields and methods starts with lower letter
          a. length()
          b. parseInt()
          c. println()
          d. substring()


General Input/Output in Java

      -   Java provides a class called System to denote the machine
      -   It provides two static objects called in and out to refer the keyboard and
          monitor
              o out
                      print()
                      println()
                      printf()
              o in
                      read()

Writing First Program
//Test.java
class First
{
        public static void main(String args[])
        {
               System.out.printf("Welcome to Java");
        }
}

Compiling the Program
     - Use JAVAC compiler


JAVAC <prograname.java>

Example
JAVAC Test.java
Returns First.class file as byte code file

Note: Set the path of JDK\BIN folder before compilation

Running a class

JAVA <classname>

Example
JAVA First


For Kawa
F7  Compile
F4  Run


Data types in Java

 All data types in Java are signed by default

Integrals
       - byte – 1 byte
       - short – 2 bytes
       - int – 4 bytes
       - long – 8 bytes
Floating
       - float – 4 bytes
       - double – 8 bytes
Booleans
       - boolean – 2 bytes – for only true or false
Character
       - char – 2 bytes (Unicode)


Note: Strings and Date are managed using classes String and Date

Providing values to the variables
   1. Using Literals
   2. Using Keyboard – Interactive mode
         a. Using Scanner class
         b. Using BufferedReader class
   3. Using Command Line – non interactive mode


Next Topics
  1. Literals
  2. Keyboard Input
  3. Wrapper classes
  4. Command Line Input
20.09.2008

Literals
       - The values used directly without any user input
       - Types of literals
            o Integrals
            o Floating
            o Boolean
            o Character
            o String Literals

Integrals
      - Default is int
      - Use l or L for long values as suffix

      int k=67;

      long k=78L;

Floating
       - Default is double
       - Use f or F for floats
       double k=5.6;

      float k=5.6F;

Characters
      - Same as C

String literals
        - Strings are managed by String class
        - Enclosed in double quotes

      String name=”Rakesh”;

Boolean
      - Can have true or false only
      - Default is false

      boolean married;
      married=true;



Reserve Words in Java
  1. Keywords
        a. Words used by the language for some purpose but not allowed to be
           used as identifier
               i. int,char, float etc.
  2. Values
        a. true, false, null
  3. Reserve for future
          a. Words neither used by the language nor allowed to be used as
             identifier
          b. const, goto

Getting Input from Keyboard

Method 1
     Using Scanner class of java.util package
Method 2
     Using BufferedReader class of java.io package

Working with Scanner class

      -   Create an object of Scanner class
      -   All objects get created using new keyword

classname reference=new constructor(arguments);


Example
Scanner sc=new Scanner(System.in);

Scanner class provides in-built methods
     String next()
     int getInt()
     float nextFloat()

Working with BufferedReader
     - System.in (keyboards) send a stream of bits to InputStreamReader class
        that reads the stream and convert into the character
            o InputStreamReader isr=new InputStreamReader(System.in);
     - That characters are then passed to BufferedReader for temporary
        buffering until Enter key is pressed
            o BufferedReader br=new BufferedReader(isr);
     - When Enter key is pressed data is retrieved and given to specified
        location using readLine() method
            o String readLine()
     - To convert data from string type to other types Java provides special
        classes called Wrapper classes
            o Wrapper classes are the special classes corresponding to data
               types
                    byte  Byte
                    short  Short
                    int  Integer
                    long  Long
                    float  Float
                    double Double
                    char  Character
                    boolean Boolean
            o They provide additional function on their value types
            o They also help in conversion from string type to their values types
datatype variable=wrapperclass.parseDatatype(stringvalue);

Example
int age=Integer.parseInt(br.readLine());
double salary=Double.parseDouble(br.readLine());


Using Command Line Input
      - When passed data from DOS Prompt while running a program is called as
        command line input
      - The data is entered into the program using entry point main() under args
        variable

VoterCmd Rajesh 44

args[0]  Rajesh
args[1]  44


25.09.2008

Arrays

       -   A collection of similar set of items
       -   Arrays are treated as objects
       -   Created with new keyword
       -   Each array has length property to give the size of array

Types of Arrays
   1. Single Dimension
   2. Two Dimensional
   3. Multi Dimensional

int n[]=new int[10];
int n[][]=new int[2][3];

Operated like C

int n[]={4,5,6,7};
Working with foreach loop
       - A loop that works with arrays and collections
for(datatype variable : array or collectioname)
{
}


Example
     public static void main(String args[])
     {
            int n[]=
            {5,6,7,8
            };
            for (int x : n)
            {
                     System.out.println(x);
            }
     }

Class and Objects

      -   Class is a set of specifications about an entity which define the fields and
          method be operated on the entity.
      -   Use class keyword to define a class
      -   A class can have two kind of members
             o Static or Class Members
                      Do not require an object to call them
                      May be called by the object
                      static keyword is required
             o Non-static or instance members
                      Always need an object to call them
                      No keyword is required
      -   Members can be
             o Field
             o Method

Types of Fields
   1. Variable
   2. Constant
         a. Use final keyword to declare the constants
             final double num=3.6;

Types of Methods
   1. General methods or Concrete methods
   2. Abstract methods
         o A method having the signature but no body contents
         o An abstract method can be declared inside the abstract class or
            interface
         o If declared inside an abstract class then use abstract keyword with the
            method. For interface no abstract keyword is required.
         o If a class contains any abstract method then it must be declared as
            abstract.
   3. Final Method
         o The method that can never be overridden
         o Use final keyword with such methods

Types of class
   1. Concrete class
   2. Abstract class
         a. A class that can never be instantiated
         b. Always used for inheritance purpose only
         c. An abstract class may or may not have any abstract method
         d. Use abstract keyword with such classes
   3. Final class
         a. A class that can never be inherited
         b. Use final keyword with class

Importing static members of a class
      - Use static keyword along with the import command

import static java.lang.System.*;
import static java.lang.Math.*;

out.println(“Hello”);
pow(5,6);

28.09.2008
Pass any number of argument to the functions

       -   Use … with the data type to accept any number of arguments inside an
           array
       -   Use for each loop to get data from that array

OOPs
       -   It is a methodology for better project management
       -   It defines a system using some of rules
       -   It is based on four main pillars
                o Encapsulation
                o Abstraction or Data Hiding
                o Polymorphism
                o Inheritance
       -   Encapsulation means combining all the members related with an entity at
           on place. Members of a class should not be accessible directly.
       -   Abstraction defined a layer to provide accessibility on the controls
                o Java allows four kinds of abstraction layers
                       Private
                              Accessible within the class
                       Default or Package
                              Accessible within the package
                              When no keyword is specified
                       Protected
                              Accessible within the package or in child class
                       Public
                              Anywhere access
Package
     - A collection of related set of classes
     - Package can be of two types
          o Provided by Sun
          o Custom Packages
     - They can be three formats
          o Folder
          o JAR file
          o ZIP file

Creating Custom Packages
   1. Create a folder to hold your packages
         a. E:\batch30
   2. Now define the package name and create a folder with that name
         a. general
   3. Now create the class for this package and save them into this folder
         a. Each such class must have package command on top
         package general;
         class Maths
         {
         }
   4. Save and compile

Using the Custom Package
      - Set the class path to give the location of your packages
      - For DOS
            o SET CLASSPATH=%CLASSPATH%;e:\batch30
      - For Kawa
            o Packages  classpath Add Dir…
            o Select batch30 on e drive
      - Import the package
            o import general.*;
      - Create an object to the class and use it
06.10.2008

Distributing the Packages

       -   Create the ZIP file or Create JAR files
       -   Use WinZip or Winrar to create the ZIP files and JAR.EXE utility from JDK

JAR (Java Archive) files are created using JAR utility with certain options
      - c (Create)
      - v (Verbose)
      - f (for Specified filename)
      - t (Tabulate)
      - x (eXtract)

Example
Creating a JAR file for the package
   1. Go inside the folder that contains the packages
          a. E:\batch30
          b. Create a jar file by merging all the packages into the jar file with
             command
                  i. JAR cvf batch30.jar .
          c. To view contents inside a JAR
                  i. Jar tvf batch30.jar
          d. To extract contents of a JAR
                  i. JAR xvf batch30.jar

Polymorphism
     - It is concept implemented with the help of overloading.
     - When two more methods have the same name but different number of
        arguments or the type of arguments is called as method overloading.

void area(int r)
{
}

void area(int len, int width)
{
}

Inheritance
       - To provide re-usability of code
       - It reduces the code size of the project making it more manageable and
         speedy software
       - Java allows only single inheritance and multilevel inheritance
       - Use extends keyword to inherit a class into other class
class X
{
}

class Y extends X
{

}

      -   Use this keyword to refer the object of current class
      -   Use super keyword to refer the object of just above class


Overloading Vs Overriding

      -   Overloading means two or more methods with same name but different
          signature that can be same class or in child class. Different method can
          have different scopes.
      -   Overriding means a method in parent class used in child class with same
          signature but different body contents. Can only be in child class. In case of
          overriding we can increase the scope but cannot decrease the scope.

Interfaces

      -   A set of specifications about an entity very similar to class, but contains all
          abstract methods and final fields by default
      -   All methods are public and abstract by default
      -   All fields are public and final by default
      -   A class can inherit any number of interfaces using implements keyword
      -   An interface can also inherit other interfaces using extends Keyword

interface A
{
}

interface B extends A
{
}

class X implements B
{
}

      -   All methods of an interface must be override or declare the class as
          abstract
Exception Handling

      -   A process to pass the message from the place the error has occurred to
          the place the method get called
      -   It is a system where all such error messengers are object of some class
          which must be inherited from Exception of java.lang package. All such
          classes have Exception word attached with them
               o IOException
               o IndexOutOfBoundException
      -   Exception class provide some common methods used by all the
          exceptions.
               o String getMessage()
               o String toString()
               o void printStackTrace()
      -   Java provides five keywords for exception handling
               o try
               o catch
               o throw
               o throws
               o finally
      -   try-catch is block of statements to do some task and catch the exception

      try
      {
      }catch(classname ref)
       {
       }

      -   One try can have any number of catch blocks but only one finally block
      -   finally block is used to execute certain statements irrespective of error

Creating Custom Exceptions

      -   Look for the class and their method that can have a kind of exception
      -   Create your own exception class by inheriting Exception class and
          overriding getMessage() and toString() methods

Throwing an Exception
     - To throw an object use throw keyword
     - Use throws keyword as indicator to the compiler that such method throws
        an exception
     -
18.10.2008

AWT (Abstract Window ToolKit)
     - A collection of classes for GUI development
     - It provides different set of classes for different purpose
            o Containers
                   Special classes used as container for the controls
                   Frame, Applet, Dialog, Window, Panel etc.
            o Components
                   The classes that support the data interaction
                   Label, Button, TextField, Menu, MenuItem, PopupMenu,
                   Choice, List, CheckBox etc.
            o Supporting Classes
                   The classes that support containers and components
                   Font, Color, Rectangle
     - All such classes are provided under java.awt package
     - Every component and container is inherited from a common class called
        Component class which is an Abstract class
            o void setSize(int x, int y)
            o void setVisible(boolean b)
            o void setBackgroud(Color c)
            o void setForeground(Color c)
            o void setFont(Font f)
            o void setCursor(Cursor c)
            o void setLocation(int x, int y)
            o void setBounds(int x, int y, int w, int h)
     - Every container is inherited from Container class
            o void add(Component c)
            o void setLayout(LayoutManager lm)
            o void setResizable(boolean b)


Types of GUI Applications
   1. Desktop Application
         a. Every desktop application must have at least one form class which
            must inherit from a Frame class
         b. Such programs need to be placed on every machine
   2. Web Applications
         a. Application that get placed at common place on some web server and
            can be accessed anywhere in the world using a Web Browser
         b. Called as Java Applets. Such Java program must inherit from Applet
            class of java.applet package

Adding Components into the containers
     - Create the components and add into the container with add() method
     - To place the controls properly inside the containers special classes are
        required called as layout managers
     - All such classes are inherited from LayoutManager class
           o BorderLayout – default for Frame and Dialog
                   Divides the container into five segments
                          East
                          West
                            North
                            South
                            Center (default)
             o FlowLayout – Default for Applets
                     To add items from left to right then top to bottom
             o GridLayout
                     To divide the container into given rows and columns
             o GridBagLayout
             o CardLayout
      -   To set the layout of the containers use setLayout() method


Components classes

Label class
       - To create a fixed text
            o Label()
            o Label(String text)
            o void setText(String text)
            o String getText()

TextField class
      - To create single line text field and password field
              o TextField()
              o TextField(int size)
              o TextField(String text)
              o TextField(String text, int size)
              o void setText(String text)
              o String getText()
              o void setEchoChar(char ch)
              o void setEditable(boolean b)

Button class
      - To create the push buttons
             o Button()
             o Button(String label)
             o void setLabel(String label)
             o String getLabel()


To take certain action we need to define the events. An event is an abstract method
defined inside some interfaces called as listeners.
       ActionListener
       WindowListener
       MouseListener
       MouseMotionListener
       KeyListener
       AdjustmentListener
       FocusListener
       ItemListener

      -   All such interfaces are provided under java.awt.event package
19.10.2008

In Java events are based on Event Delegation Model.

       ActionListener interface
           o public void actionPerformed(ActionEvent e)
                   ActionEvent class provides methods
                          Object getSource()
                          String getActionCommand()
       MouseMotionListener
           o public void mouseMoved(MouseEvent e)
           o public void mouseDragged(MouseEvent e)
                   MouseEvent class provides
                          int getX()
                          int getY()
       KeyListener
           o public void keyTyped(KeyEvent e)
           o public void keyPressed(KeyEvent e)
           o public void keyReleased(KeyEvent e)
                   KeyEvent class provide information about the control and
                     key typed
                          char getKeyChar()
                          Object getSource()
                          void consume()
       WindowListener
           o public void windowClosing(WindowEvent e)
           o


Process for event handling

      -   First check the controls on which events need to be applied and kind of
          event
              o Buttons b1,b2  Click
              o TextField t1  Typing
              o Frame  Closing
      -   Decide the listener and look for exact method of the listener that can do
          the operation required
              o Buttons  ActionListener  actionPerformed
              o TextField  KeyListener  keyTyped
              o Frame  WindowsListener windowClosing
      -   Register the event listeners with the controls using addXXXListener()
          method and define the object of the class that contains the overridden
          method of the listener
              o b1.addActionListener(object of class having listener methods);
              o b2.addActionListener(object of class having listener methods);
              o t1.addKeyListener(object of class having listener methods);
              o addWindowListener(object of class having listener methods);
      -   Override the methods and define the working

Using Inner Classes
      -   A class within a class in called as inner class
      -   It can access all members of containing class

Working with Adapters
     - Special classes corresponding to listeners
     - They provide pre-implementation of listeners with blank body
     - Listeners having just only one method, do not have the adapters
            o WindowListener  WindowAdapter
            o KeyListener  KeyAdapter

Working with Anonymous class
     - A class without any name
     - Once we override the method while registering the event, a class is
        automatically created by the compiler


06.11.2008

Java Database Connectivity (JDBC)
      - Java is front-end to connect with any kind back-end
      - Java needs a driver class to connect with database and SQL statements
         to perform the action
      - Java provides two packages
             o java.sql
             o javax.sql

Use the JDBC for Database Management

Step 1
   1. Look for the database
          a. MS Access
          b. Oracle
          c. MySql
          d. Sql Server
   2. Look for driver class and the location of the class file (JAR file)
          a. Java provides a common driver for windows called as JDBC-ODBC
             Bridge with class file sun.jdbc.odbc.JdbcOdbcDriver inside RT.JAR
             file
   3. Load the driver class file into memory using any of three methods
          a. Using Class class
                  i. Class.forName(“classname”);
          b. Using DriverManager class
                  i. DriverManager.registerDriver(object of class);
          c. Using System class
                  i. System.setProperty(“jdbc.drivers”,”classname”);
   4. Establish the connection with the database and hold the reference of the
       connection into a Connection interface
          a. Connection cn=DriverManager.getConnection(“url”,”login”,”password”);
   5. To run the SQL statements we need a class out of three
          a. Statement
          b. PreparedStatement
          c. CallableStatement
   6. The statements can of two types
          a. SELECT type
          b. Non-Select type
   7. Depending on the type of statement use the method of these classes
          a. Statement
                 i. ResultSet executeQuery(sql)
                ii. int executeUpdate(sql)
          b. PreparedStatement
                 i. ResultSet executeQuery()
                ii. int executeUpdate()
          c. CallableStatement
                 i. void execute()
   8. The ResultSet class is used to access the records returned by the
      statements
   9. Close the connection

For JDBC-ODBC Bridge with MS Access
      - First create a DSN (Data Source Name) from Control Panel and use that
        name into the program for URL creation
      -     jdbc:odbc:<dsnname>

Working with MySql
     - Install the software
     - Create the database
            o CREATE DATABASE batch30db;
     - Make the database as current database
            o USE batch30db;
     - Check for current database
            o SELECT database();
     - Create the tables
            o CREATE TABLE empdata (empid int, name varchar(50), email
               varchar(50));
     - View Structure of Tables
            o Describe empdata;

Data Types used in MySql
                           Numeric Column Types
TINYINT                                1 byte
SMALLINT                               2 bytes
MEDIUMINT                              3 bytes
INT                                    4 bytes
BIGINT                                 8 bytes
FLOAT                                  4 bytes
DOUBLE                                 8 bytes
DECIMAL(M,D)                           M+2 bytes
                            String Column Types
CHAR                                   Fixed-length characters
VARCHAR                                Variable length characters
TINYTEXT
TEXT
MEDIUMTEXT
LONGTEXT
                               Date and Column Types
DATE                                       “YYYY-MM-DD” format date value
TIME                                       “HH:MM:SS” format value
DATETIME                                   “YYYY-MM-DD hh:mm:ss” format
TIMESTAMP                                  Yyyymmddhhmmss format
YEAR                                       YYYY format


Creating a Login and Password and associate the database with that user
GRANT ALL PRIVILEGES ON *.* TO b30 IDENTIFIED BY '123456' WITH GRANT OPTION;

Here b30 is a user name, 123456 is the password


Look for the Driver Class files
com.mysql.jdbc.Driver

URL to connect with Database
jdbc:mysql://localhost:3306/batch30db?autoReconnect=true

08.11.2008

Using PreparedStatement
- Provide the SQL statement while create a prepared statement

PreparedStatement ps=cn.prepareStatement(sql);

Using Placeholders
      - A place holder is a ? provided in SQL Statement in place of data
      - Data is provided later before execution use setXXX() methods
      - setInt(column no or name,data)
      - setString()
      - setDouble()
      - It can be applied with PreparedStatement and CallableStatement only.
      -


Using MS SQL Server
      - MS SQL Server is an RDBMS from Microsoft
      - It provides a
      - Database
      -          Tables
      - Login/Password


Create the Procedure
CREATE PROCEDURE SaveData
      @empid int,
      @name varchar,
      @email varchar
AS
BEGIN
      INSERT INTO empdata VALUES(@empid,@name,@email)
END
GO
      -   Create the CallableStatement to call this procedure
      -   Create the DSN to connect with SQL Server
      -    DSN Batch30sql
      -   User id  sa
      -   Password  pass
      -   Procedure  SaveData

          CallableStatement cs=cn.prepareCall("{call SaveData(?,?,?)}");
                    cs.setInt(1,empid);
                    cs.setString(2,name);
                    cs.setString(3,email);

                    cs.execute();


13.11.2008

Reading data from Database

      - Create the SELECT statement get called the method executeQuery() to get
         the result into a ResultSet

      ResultSet rs=ps.executeQuery();

Methods of ResultSet
      boolean next()
      boolean previous()
      boolean first()
      boolean last()

          int getInt(column no or column name)
          String getString(....)
          double getDouble(....)

Setting the direction and Concurrency in Resultsets

      - To provide the direction and concurrency we need to specifify a set of
         constants to Statement, PrepareStatement, CallableStatement whele
         creating them
      -

For Direction
ResultSet.TYPE_SCROLL_SENSITIVE
ResultSet.TYPE_SCROLL_INSENSITIVE
ResultSet.TYPE_FORWARD_ONLY (default)

For Concurrency
ResultSet.CONCUR_READ_ONLY (default)
ResultSet.CONCUR_UPDATABLE



14.11.2008
Multi-Threading
       - A thread is a child process within a process that utilize the resources and
           timing allocated for a process
       - In every java program one thread is always present called as main thread
       - Threads are created and managed by java.lang.Thread class
       - Threads are implements using Thread class and Runnable interface
       - Runnable interface provides a method called run() which need to override
           working for a thread

Constructors of Thread class
      - Thread(Runnable r)
      - Thread(Runnable r, String threadname)

Methods of Threads class
       static Thread currentThread()
       String getName()
       void setName(String tname)
       int getPriority()
       void setPriority(int n)
       void start() – To send the thread in thread queue
       void run()
       void wait()
       void notify()
       void suspend()
       void resume()
       static void sleep(int ms) throws InterruptedException
       static void sleep(int ms, int nn) throws InterruptedException



Life Cycle of Thread
   1. Born State
   2. Ready State
   3. Running State
   4. Block
   5. Dead


15.11.2008

Inter-Thread communication
       - When one thread needs data from other thread then it is called as inter-
           thread communication
       - If required data in not available then the threads has to wait. We need to
           use wait() method to block the current thread thread until a notification is
           issued with notify() or notifyAll() method

Synchronization or Handling the Deadlocks
     - When two or more threads try to access a resource (variable) then their can
        be a collision if more than one threads try to modify a common resource is
        called as dead locks.
     - Java provides synchronized keyword to handle the deadlocks
      - It can be applied by two methods
          o With methods
          o Synchronized blocks

         synchronized <returntype> <methodname>(<arguments>)
         {
         }

         <returntype> <methodname>(<arguments>)
         {
                sysnchronized(this)
                {
                }
         }

      - synchronization provide a lock called as mutual exclusive lock or mutex to
         the current thread.

Example : Producer-Consumer Problem

Producer Thread adds the items and Consumer thread consumes the items, to and
from a common location called stock
Daemon Thread

A thread that work in background. To check a thread as daemon thread use
isDaemon() method
Use setDeamon() method to set or re-set as daemon thread
        void setDaemon(boolean b)


20.11.2008

Java Applets

      - Special Java classes that get placed on a web server and those classes get
         merged into a HTML file inside <APPLET></APPLET> tag
      - Applet is executed at client side into a web browser
      - The web browser must have the Java Virtual Machine (JVM)

Terms used

WWW (World Wide Web) – A collection of web pages all over the world. A term
coined by Sir Tim Berner’s Lee

Web Page  A page that get executed by a web browser, created using HTML
language. Extension should be .htm or .html

Home Page  First page of the website that runs automatically is called as home
page. Generally it is a index.htm or default.htm

Website  Collection of webpages about some organization. Eg.
impeccablegroup.org

Domain types  a domain type define the kind of website or organization
       .com  commercial
       .edu  Educational
       .org  Organizational
       .co.in  Indian Companies
       .in  Indian domain
       .ac.in  Indian academics
       .coop  dairys
       .mobi  mobiles companies
       .tv  TV channels
       .gov.in  Indian Govenment

Portal  Providing a set of services. Yahoo.com

Vortal  When a website works in specific area it is called as vortal. Example
               impeccablejobs.com

HTML  Hyper Text Markup Language
     - A formatting language used for web based on fixed set of command called
        markups or tags
      - Created and standardized by W3C (World Wide Web Consortium) with
         latest version 4.01 (w3.org, w3schools.com)

Tag
      - A fixed code defined by W3C enclosed in < and > having fixed meaning
      - <HTML></HTML>, <br> , <img>, <meta> etc.

Types of Tags
   1. Singular Tags – No Closing part
         a. <BR>, <IMG>, <META>,<BGSOUND> etc.
   2. Paired Tags – Having opening and closing both
         a. <B></B>, <font></font> etc.

Attributes
       - Additional properties associated with tags
       - Example
          o <IMG> Tag
                  src=”filename”
                  width=”x”
                  height=”y”
                  alt=”alternate text”
                  dynsrc=”video file”
                  start=”fileopen|mouseover”
          o <APPLET> tag
                  code=”classname”
                  width=”x”
                  height=”y”
                  codebase=”folder name having class file”
                  archive=”jar fielename”


Sub Tags
     - A tag within another tag
     - <PARAM> is a sub tag of <APPLET> tag to provide dynamic data to the
        applets
        o <PARAM name=”fieldname” value=”valuetosend”>


<META> - Provides data over the data and instruction for the browser. It has three
attributes
         name=”fieldname”
         content=”values”
         http-equiv=”instructions”

Example
        <meta name=”keywords” content=”abc,xyz”>
        <meta name=”description” content=”description of site or page”>
<meta http-equiv=”refresh” content=”10”> - auto refreshable website after 10
seconds
<meta http-equiv=”refresh” content=”10;http://www.yahoo.com”> - auto transfer to
yahoo.com after 10 seconds
<meta http-equiv=”pragma” content=”no-cache”>

<bgsound src=”filename” loop=”-1”>


Writing the Applets
      - A java applet class must inherit from java.applet.Applet class
      - No need of entry point
      - No constructor required
      - Applet class provide certain method to override
          o public void init()
          o public void paint(Graphics g)

Writing a string to applets
      - Use drawString() method of Graphics class
          o public void drawString(String s, int x, int y)

Running an applet

Method 1
       Using web browser
Method 2
       Using APPLETVIEWER tool of JDK
       Appletviewer filename.htm

21.11.2008

Placing class files and HTML files in different folders
      - Define the folder name of class files using CODEBASE attribute of
         <APPLET> tag

Using Images with applets

       - Use getImage() method of Applet class to get reference of the image

       Image getImage(URL path, String filename)

       - To get the information about the folder of the current website use
          getCodeBase() or getDocumentBase() methods
          o URL getCodeBase() returns the path upto class file folder
          o URL getDocumentBase() returns the path of the folder from where
              HTML file is running
       - To draw the image onto an Applet use drawImage() method of Graphics
          class
          o void drawImage(Image img, int x, int y, ImageObserver object)
          o void drawImage(Image img, int x, int y, int w, int h, ImageObserver
              object)

Passing Parameters to the Applets
      - To pass data later on we need to define the parameters
      - Use <param> sub tag of <applet> tag with name and value attributes
      - Use getParameter() method of Applet class to get the value of the
         parameter inside init() method


Using repaint() method
      - Special method that calls the paint() method again
      - repaint() calls the update() and then paint()


Placing the classes into a JAR file and use it
      - Use ARCHIVE attribute of <applet> tag
      - Used for optimization of applets

<applet code="RepaintTest" width="300" height="300" archive="repaint.jar">
</applet>


22.11.2008

Java Swings

      - Swing is advanced graphics model of Java which is rich look and platform
          independent look and feel with light weight components
      - In AWT every component and container has its widget or pointer managed
          by OS while in Swings component do not need such pointers but only the
          containers. That means the components are light weight requiring less
          memory while containers need that pointers
      - Swing is part of Java Foundation Class (JFC) which provides big set of
          advance classes for advance GUI operations
      - Most of the classes starts with J
      - Use the package javax.swing
      - Containers
          o JApplet, JFrame, JDialog, JPanel etc.
      - Components
          o JButton, JTextField, JRadioButton, JCheckBox, JMenu etc.
          o JToolbar, JProgressBar etc.

General points
     - Every swing control can have the Images and ToolTips
     - When using Image with the components use ImageIcon class whenever we
         find the Icon as argument
     - Use setToolTipText() method to provide the tooltip
Using Dialogs with JOptionPane class

      - Provides static method to show different kind of dialogs
         o Message Dialog
         o Confirmation Dialog
         o Input Dialog
      - Methods
         o showMessageDialog(parent, String message)

Create advance menus with JMenu, JMenuItem and JMenuBar

      - We can add the shortcut keyword called accelerators and they keystrokes
      - While using accelerator and keystroke we need to the define key
         combinations using Masking keys (Shift, Ctrl, Alt) and the Virtual keys
      - Use KeyEvent class to get the virtual keys and Event class for masking
         class
      - Event.CTRL_MASK, ALT_MASK, SHIFT_MASK
      - KeyEvent.VK_A, VK_F1, VK_UP etc,
      - Keystroke class provide a static method getKeyStroke() to create a
         keystroke the apply it on some JMenuItem using setAccelerator() method
      - Use setMnemonic() methot to define the hot keys

Example
JMenu f=new JMenu(“File”);
f.setMnemonic(‘F’);
or
f.setMnemonic (KeyEvent.VK_F);


Creating a toolbar

      - Use JToolBar class to create a toolbar and add the buttons into it the add
         the tool bar into “North” section of the frame

Working with different look and feels

      - Different look and feels can be created and used
      - By default Java provide three look and fees
         o Window, Motif and Metal (default)
      - Use UIManager class with setLookAndFeel() method to apply the class
         name
      - Use SwingUtilities class with updateComponentTreeUI() method to apply
         the style

javax.swing.plaf.metal.MetalLookAndFeel;
com.sun.java.swing.plaf.motif.MotifLookAndFeel;
com.sun.java.swing.plaf.windows.WindowsLookAndFeel;

UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
SwingUtilities.updateComponentTreeUI(getContentPane());
Using JColorChooser dialog
      - Provides selection of a color
       Color c=JColorChooser.showDialog(this,"Select a new Color",Color.white);

Using JScrollPane class to provide scrolling anywhere
      - Create a scrollpane and add any control into it
      - If the size is more than scrollbars are auto created


23-12-2008

Networking or Socket Programming
     - A system to provide communication between two machines
     - It is based on IP Address and Port number
     - Port number is a logical number given to different applications
     - A machine can have max. of 65535 ports
     - Different applications use different port numbers
         o HTTP  80
         o FTP 21
         o SMTP  25
         o Oracle  1521
         o RMI  1099
         o MySql  3306

       - All classes and interfaces are provided under java.net package
       - Communication can be of two types
          o TCP/IP Based communication
          o UDP Based communication
       - TCP/IP based communication
          o Reliable
          o Live Communication
          o Connection oriented
          o Classes used
                   Socket
                   ServerSocket
       - UDP Based communication
          o Un-reliable
          o Connection less
          o Classes
                   DatagramPacket
                   DatagramSocket
                   InetAddress

Testing application with TCP/IP

Create a server program with ServerSocket class

ServerSocket s=new ServerSocket(int portnumber);

The client will look for the server using Socket class

Socket s=new Socket(String ip address or dns, int portnumber);
      - It throws IOException is socket was not created
Methods of ServerSocket class

Socket accept()
      - Wait for a client until a client contacts the server

Setting up the communication
      - Get reference of the keyboard of other machine with getInputStream()
         method of Socket
      - Get reference of the monitor of other machine with getOutputStream()

To send data in string format from one machine to another machine, create an
object of PrintWriter class of java.io package



Using UDP

Encapslulate the information about the other machine into an InetAddress type
object with its static methods

         InetAddress getLocalHost()
         InetAddress getByName(String ip address or dns)

Create a packet to send the information using DatagramPacket
DatagramPacket(byte [], int size)
DatagramPacket(byte b[], int size, InetAddress ia, int port)

DatagramPacket p=new DatagramPacket(byte b[], int size, InetAddress ia, int port)

Methods
       int getLength()
       byte [] getData()

Use DatagramSocket class to send and receive the data on some port
DatagramSocket ds=new DatagramSocket(int portno);
Methods
       send(DatagramPacket p)
       receive(DatagramPacket p)


Note: While sending data convert the String into byte array using getBytes() method
of String class
Use String class to covert byte array into String again

String(byte b[], int start, int ending)
24.12.2008

Working with Java/IO

       - To work with files and folders and create new files in text or binary mode
       - Package java.io
       - Classes
       -         File
       -         FileWriter (Text mode)
       -         FileReader (text mode)
       -         FileOuputStream (binary mode)
       -         FileInputStream (binary mode)

File class
        - To get information about a file or folder
        - Create a folder
        - View contents of a folder
        - Create and remove folders
        - Remove files
        - Rename file and folders

Constructor
        File(String path)
        File(String folder, String filename)


Methods
       boolean exists()
       boolean isFile()
       boolean isDirectory()
       long length()
       long lastModified()
       boolean mkdir()
       boolean mkdirs()
       boolean remove()
       boolean renameTo(File f)
       String []list()

Operating files with Text Mode

       - Create an object of FileWriter to create new file or add content to a file
       - Use write() method to write contents to a file
       - Use close() method to close the file

       - to read the contents of a file create an object of FileReader class and pass
           it to a BufferedReader to read all data

Operating data in binary format
     - Convert data from string to byte array and save into a file
     - Use read() method to read a byte at one time
Collections and Utilities

Collections
      - A set of classes to hold dynamic set of objects provided under java.util
         package
      - Can be of two types
         o Legacy Collections
         o Framework based collections
      - Legacy collections are formed using some classes and interfaces and
         available from java 1.0
         o Vector class
         o Hashtable class
         o Enumeration interface
      - Framework based collection follow some rules and regulations with
         hierarchy
         o Collection interface
                  List interface – Have single set of value. Allows duplicate values
                        LinkedList
                        ArrayList
                  Set interface - Single set of unique value
                        HashSet
                  Map Interface – for key/value pairs
                        HashMap


Vector class
      - To hold multiple objects
      - Constructor
          o Vector()
      - Methods
          o void addElement(Object x)
          o Object elementAt(int index)
          o int size()

Note: Use instanceof operator to check the type of element


AutoBoxing and Auto-unboxing

       - Autoboxing means conversion from value type to reference type
       - Autounboxing means conversion from reference type to value type

Generics
     - A system to define the type of elements inside a class while creating an
         object of a class in collections
     - Such collections are knows as Generics

import java.util.*;
class ArrayListTest
{
         public static void main(String args[])
         {
                 ArrayList <Double>v=new ArrayList<Double>();
                 v.add(3.9);
                 v.add(2.3);

                 double sum=0;

                 System.out.println("Total elements : "+v.size());
                 for(int i=0;i<v.size();i++)
                 {
                                     sum+=v.get(i);
                 }
                 System.out.println("Sum is : "+sum);
        }
}


27.12.2008

Hashtable class
      - Holds the Key/Value pairs
      - Constructor
      - Hastable()
      - Methods
      - void put(String key, Object value)
      - Object get(String key)
      - Enumeration keys()

Enumeration interface
     - To work with enumerated values
     - boolean hasMoreElements()
     - Object nextElement()

Performing some action after given interval of time and delay
      - Use Timer and TimerTask class
      - TimerTask provides run() method
      - Timer class provide schedule() method to schedule the task with interval an
         delay time

				
DOCUMENT INFO
Shared By:
Tags:
Stats:
views:44
posted:7/26/2012
language:English
pages:32