SlideShare uma empresa Scribd logo
1 de 48
Chapter 9



Packages



            http://www.java2all.com
Introduction



               http://www.java2all.com
Package :

      Packages are java`s way of grouping a veriety of
  classes and/or interfaces together.

Java API packages :

     java API provides a large number of classes
  grouped into different packages according to
  functionality.

     Frequently used API packages are as under.
                                           http://www.java2all.com
http://www.java2all.com
Package       Contents
Name
              Language support classes. These are classes that java
              compiler itself uses and therefore they are automatically
Java.lang
              imported. They include classes for primitive types, strings,
              math functions, threads and exceptions.
              Language utility classes such as vectors, hash tables,
Java.util
              random numbers, date, etc.
              Input/output support classes. They provide facilities for
Java.io
              the input and output of the data.
              Set of classes for implementing graphical user interface.
Java.awt      They include classes for windows, buttons, lists, menus
              and so on.
              Classes for networking. They include classes for
Java.net      communicating with local computers as well as with
              internet servers.

Java.applet   Classes for creating and implementing applets.
                                                            http://www.java2all.com
Syntax for import packages is as under

     import packagename.classname;
or
     import packagename.*;

     These are known as import statements and
must appear at the top of the file, before any file
declaration as you can see in our few examples.
Here import is a keyword.

      The first statement allows the specified
class in the specified package to be imported.
                                               http://www.java2all.com
EX :

import java.awt.Color;
double y = java.lang.Math.sqrt(x);

      Here lang is a package, Math is a class and sqrt
is a method.
For create new package you can write...
package firstPackage;
public class Firstclass
{
        ..................
        body of class
        .................
}                                            http://www.java2all.com
Vector Class



               http://www.java2all.com
Vector class :

       The Vector class is one of the most important in
all of the Java class libraries. We cannot expand the
size of a static array.

      We may think of a vector as a dynamic array
that automatically expands as more elements are
added to it.

      All vectors are created with some initial
capacity.

                                             http://www.java2all.com
When space is needed to accommodate more
elements, the capacity is automatically increased.
That is why vectors are commonly used in java
programming.




                                            http://www.java2all.com
This class provides the following

constructors:
       Vector()
       Vector(int n)
       Vector(int n, int delta)

     The first form creates a vector with an initial
capacity of ten elements.

        The second form creates a vector with an
initial capacity of n elements.

                                              http://www.java2all.com
The third form creates a vector with an initial
capacity of n elements that increases by delta elements
each time it needs to expand.




                                             http://www.java2all.com
import java.util.*;
public class Vector_Demo
{
  public static void main(String args[])
  {
    int i;
    Vector v = new Vector();
    v.addElement(new Integer(10));
    v.addElement(new Float(5.5f));
    v.addElement(new String("Hi"));
    v.addElement(new Long(2500));
    v.addElement(new Double(23.25));
    System.out.println(v);
    String s = new String("Bhagirath");
    v.insertElementAt(s,1);
    System.out.println(v);
    v.removeElementAt(2);
    System.out.println(v);                   Output :
    for(i=0;i<5;i++)
    {

    }
       System.out.println(v.elementAt(i));
                                             Bhagirath
}
  }                                          Hi
                                             2500
                                             23.25
                                                         http://www.java2all.com
Random Class



               http://www.java2all.com
The Random class allows you to generate
random double, float, int, or long numbers.

     This can be very helpful if you are building a
simulation of a real-world system.

     This class provides the following constructors.

      Random()
      Random(long start)

    Here, start is a value to initialize the random
number generator.
                                             http://www.java2all.com
Method              Description

Double
                    Returns a random double value.
nextDouble()

Float nextFloat()   Returns a random float value.

                    Returns a random double value. Numbers obtained from
Double
                    repeated calls to this method have a Gaussian distribution
nextGaussian()
                    with a mean of 0 and a standard deviation of 1.

Int nextInt()       Returns a random int value.


Long nextLong()     Returns a random long value.


Method              Description
                                                                http://www.java2all.com
import java.util.*;
public class Random_Demo
{
  public static void main(String args[])
  {
    Random ran = new Random();
    for(int i = 0; i<5;i++)
    {
          System.out.println(ran.nextInt());
    }
  }
}



             Output :

             64256704
             1265771787
             -1962940029
             1372052

                                               http://www.java2all.com
Date Class



             http://www.java2all.com
Date class :

     The Date classes encapsulate information about
a specific date and time.

      It provides the following constructors.
            Date()
            Date(long msec)

     Here, the first form returns an object that
represent the current date and time.

     The second form returns an object that
represents the date and time msec in milliseconds after
                                             http://www.java2all.com
Method          Description

Boolean         Returns true if d is after the current date.
after(Date d)   Otherwise, returns false.
Boolean        Returns true if d is before the current date.
before(Date d) Otherwise, returns false.
Boolean        Returns true if d has the same value as the
equals(Date d) current date. Otherwise, returns false.
               Returns the number of milliseconds since the
Long getTime()
               epoch.
Void setTime    Sets the date and time of the current object to
(long msec)     represent msec milliseconds since the epoch.
String
                Returns the string equivalent of the date.
toString()
                                                       http://www.java2all.com
import java.util.*;
public class Date_Demo
{
  public static void main(String args[])
  {
    Date dt = new Date();
    System.out.println(dt);

        Date epoch = new Date(0);
        System.out.println(epoch);
    }
}




         Output :

         Fri May 25 00:04:06 IST 2012
         Thu Jan 01 05:30:00 IST 1970

                                           http://www.java2all.com
import java.util.Date;
public class date2
{
   public static void main(String[] args)
   {

        Date d1 = new Date();     Output :
        try
        {                         First Date : Fri May 25 00:06:46 IST 2012
          Thread.sleep(1000);
        }                         Second Date : Fri May 25 00:06:47 IST
        catch(Exception e){}
                                  2012
        Date d2 = new Date();
                                  Is second date after first ? : true
        System.out.println("First Date : " + d1);
        System.out.println("Second Date : " + d2);
        System.out.println("Is second date after first ? : " + d2.after(d1));

    }
}




                                                                                http://www.java2all.com
import java.util.*;
public class date3
{
  public static void main(String args[])
  {
    Date date = new Date();
    System.out.println("Date is : " + date);
    System.out.println("Milliseconds since January 1, 1970, 00:00:00 GMT : " + date.getTime());
    Date epoch = new Date(0);
    date.setTime(10000);
    System.out.println("Time after 10 second " + epoch);
    System.out.println("Time after 10 second " + date);
    String st = date.toString();
    System.out.println(st);
  }
}
       Output :

       Date is : Fri May 25 00:12:52 IST 2012
       Milliseconds since January 1, 1970, 00:00:00 GMT :
       1337884972842
       Time after 10 second Thu Jan 01 05:30:00 IST 1970
       Time after 10 second Thu Jan 01 05:30:10 IST 1970
       Thu Jan 01 05:30:10 IST 1970
                                                                                   http://www.java2all.com
Calendar & Gregorian class



                      http://www.java2all.com
The Calendar class allows you to interpret date
and time information.


      This class defines several integer constants that
are used when you get or set components of the
calendar. These are listed here.




                                              http://www.java2all.com
AM            AM_PM              APRIL

AUGUST        DATE               DAY_OF_MONTH

              DAY_OF_WEEK_IN_M
DAY_OF_WEEK                      DAY_OF_YEAR
              ONTH

DECEMBER      DST_OFFSET         ERA

FEBRUARY      FIELD_COUNT        FRIDAY

HOUR          HOUR_OF_DAY        JANUARY

JULY          JUNE               MARCH

MAY           MILLISECOND        MINUTE
                                           http://www.java2all.com
MONDAY      MONTH           NOVEMBER

OCTOBER     PM              SATURADAY

SECOND      SEPTEMBER       SUNDAY

THURSDAY    TUESDAY         UNDERIMBER

WEDNESDAY   WEEK_OF_MONTH   WEEK_OF_YEAR

                            The Calendar class
                            does not have public
                            constructors. Instead,
                            you may use the static
YEAR        ZONE_OFFSET
                            getInstance() method
                            to obtain a calendar
                            initialized to the
                            current date and time.
                                     http://www.java2all.com
One of its forms is shown here:

Calendar getInstance()




                                  http://www.java2all.com
import java.util.Calendar;
 public class Cal1
{
  public static void main(String[] args)
  {
    Calendar cal = Calendar.getInstance();

    System.out.println("DATE is : " + cal.get(cal.DATE));
    System.out.println("YEAR is : " + cal.get(cal.YEAR));
    System.out.println("MONTH is : " + cal.get(cal.MONTH));
    System.out.println("DAY OF WEEK is : " + cal.get(cal.DAY_OF_WEEK));
    System.out.println("WEEK OF MONTH is : " + cal.get(cal.WEEK_OF_MONTH));
    System.out.println("DAY OF YEAR is : " + cal.get(cal.DAY_OF_YEAR));
    System.out.println("DAY OF MONTH is : " + cal.get(cal.DAY_OF_MONTH));
    System.out.println("WEEK OF YEAR is : " + cal.get(cal.WEEK_OF_YEAR));
    System.out.println("HOUR is : " + cal.get(cal.HOUR));
    System.out.println("MINUTE is : " + cal.get(cal.MINUTE));
    System.out.println("SECOND is : " + cal.get(cal.SECOND));
    System.out.println("DAY OF WEEK IN MONTH is : " +
cal.get(cal.DAY_OF_WEEK_IN_MONTH));
    System.out.println("Era is : " + cal.get(cal.ERA));
    System.out.println("HOUR OF DAY is : " + cal.get(cal.HOUR_OF_DAY));
    System.out.println("MILLISECOND : " + cal.get(cal.MILLISECOND));
    System.out.println("AM_PM : " + cal.get(cal.AM_PM));// Returns 0 if AM and 1 if PM
  }
}

                                                                                 http://www.java2all.com
Output :

Date is : Fri May 25 00:21:14 IST 2012
Milliseconds since January 1, 1970, 00:00:00 GMT :
1337885474477
Time after 10 second Thu Jan 01 05:30:00 IST 1970
Time after 10 second Thu Jan 01 05:30:10 IST 1970
Thu Jan 01 05:30:10 IST 1970




                                                     http://www.java2all.com
The GregorianCalendar class is a subclass of
Calendar.

     It provides the logic to manage date and time
information according to the rules of the Gregorian
calendar.

     This class provides following constructors:

GregorianCalendar()
GregorianCalendar(int year, int month, int date)
GregorianCalendar(int year, int month, int date, int
hour, int minute, int sec)
                                            http://www.java2all.com
GregorianCalendar(int year, int month, int
date, int hour, int minute)




                                           http://www.java2all.com
The first form creates an object initialized with
the current date and time.

     The other forms allow you to specify how
various date and time components are initialized.

     The class provides all of the method defined by
Calendar and also adds the isLeapYear() method
shown here:
Boolean isLeapYear() This method returns true if the
current year is a leap year. Otherwise, it returns false.

                                               http://www.java2all.com
import java.util.*;
 public class gcal1                                         Output :
{
   public static void main(String[] args)
                                                            Era is : 1
  {                                                         HOUR OF DAY is : 0
    GregorianCalendar c1 = new GregorianCalendar() ;
                                                            MILLISECOND : 780
    System.out.println("DATE is : " + c1.get(c1.DATE));     AM_PM : 0
    System.out.println("YEAR is : " + c1.get(c1.YEAR));
    System.out.println("MONTH is : " + c1.get(c1.MONTH));
    System.out.println("DAY OF WEEK is : " + c1.get(c1.DAY_OF_WEEK));
    System.out.println("WEEK OF MONTH is : " + c1.get(c1.WEEK_OF_MONTH));
    System.out.println("DAY OF YEAR is : " + c1.get(c1.DAY_OF_YEAR));
    System.out.println("DAY OF MONTH is : " + c1.get(c1.DAY_OF_MONTH));
    System.out.println("WEEK OF YEAR is : " + c1.get(c1.WEEK_OF_YEAR));
    System.out.println("HOUR is : " + c1.get(c1.HOUR));
    System.out.println("MINUTE is : " + c1.get(c1.MINUTE));
    System.out.println("SECOND is : " + c1.get(c1.SECOND));
    System.out.println("DAY OF WEEK IN MONTH is : " +
c1.get(c1.DAY_OF_WEEK_IN_MONTH));
    System.out.println("Era is : " + c1.get(c1.ERA));
    System.out.println("HOUR OF DAY is : " + c1.get(c1.HOUR_OF_DAY));
    System.out.println("MILLISECOND : " + c1.get(c1.MILLISECOND));
    System.out.println("AM_PM : " + c1.get(c1.AM_PM));// Returns 0 if AM and 1 if PM */
  }
}

                                                                                http://www.java2all.com
Math Class



             http://www.java2all.com
Math Class :

      For scientific and engineering calculations, a
variety of mathematical functions are required.

      Java provides these functions in the Math class
available in java.lang package.

     The methods defined in Math class are given
following:



                                              http://www.java2all.com
Method           Description

Double
                 Returns the sine value of angle x in radians.
sin(double x)

Double
                 Returns the cosine value of the angle x in radians
cos(double x)

Double
                 Returns the tangent value of the angle x in radians
tan(double x)

Double
                 Returns angle value in radians for arcsin of x
asin(double x)
Double
                 Returns angle value in radians for arcos of x
acos(double x)
Double
                 Returns angle value in radians for arctangent of x
atan(double x)
                                                           http://www.java2all.com
Double
                  Returns exponential value of x
exp(double x)
Double
                  Returns the natural logarithm of x
log(double x)
Double
pow(double x,     Returns x to the power of y
double y)

Double
                  Returns the square root of x
sqrt(double x)

Int abs(double
                  Returns absolute value of n
n)
Double            Returns the smallest wholoe number greater than or
ceil(double x)    equal to x
Double            Returns the largest whole number less than or equal
floor(double x)   to x
                                                         http://www.java2all.com
Int max(int n, int
                     Returns the maximum of n and m
m)
Int min(int n, int
                     Returns the minimum of n and m
m)
Double
                     Returns the rounded whole number of x
rint(double x)
Int round(float
                     Returns the rounded int value of x
x)
Long
                     Returns the rounded int value of x
round(double x)
Double
                     Returns a random value between 0 and 1.0
random()
Double
toRandians(dou       Converts the angle in degrees to radians
ble angle)
Double
toDegrees(doubl      Converts the angle in radians to degrees
                                                                http://www.java2all.com
public class Angles
{
  public static void main(String args[])
  {
     double theta = 120.0;
     System.out.println(theta + " degrees is " + Math.toRadians(theta) + " radians.");
     theta = 1.312;
     System.out.println(theta + " radians is " + Math.toDegrees(theta) + " degrees.");
  }
}




      Output :

      120.0 degrees is 2.0943951023931953
      radians.
      1.312 radians is 75.17206272116401
      degrees.


                                                                                         http://www.java2all.com
Hashtable



            http://www.java2all.com
Hashtable is a part of the java.util library and is
a concrete implementation of a dictionary.

      (Dictionary is a class that represents a key/value
storage repository. Given a key and value, you can
store the value in a Dictionary object. Once the value
is stored, you can retrieve it by using its key.)

      Hashtable stores key/value pairs in a hash table.
When using a Hashtable, you specify an object that is
used as a key, and the value that you want to link to
that key.

                                              http://www.java2all.com
The key is then hashed, and the resulting hash
code is used as the index at which the value is stored
within the table.

The Hashtable constructors are shown here:
      Hashtable()
      Hashtable(int size)

     The first constructor is the default constructor.
     The second constructor creates a hash table that
has an initial size specified by size.

     The methods available with Hashtable are
                                             http://www.java2all.com
Method            Description

Void clear()      Resets and empties the hash table.
Boolean
                Returns true if some key equals to key exists within
containsKey(Obj
                the hash table. Returns false if the key isn’t found.
ect key)
Boolean         Returns true if some value equal to value exists
containsValue(O within the hash table. Returns false if the value isn’t
bject value)    found.
Enumeration       Returns an enumeration of the values contained in
elements( )       the hash table.
                  Returns the object that contains the value associated
Object
                  with key. If key is not in the hash table, a null object is
get(Object key)
                  returned.
Boolean           Returns true if the hash table is empty; Returns false
isEmpty( )        if it contains at least one key.          http://www.java2all.com
Enumeration       Returns an enumeration of the keys contained in the
keys( )           hash table.
Object
put(Object key    Inserts a key and a value into the hash table.
Object value)
Object            Removes key and its value. Returns the value
remove(Object     associated with key. If key is not in the hash table, a
key)              null object is returned.
Int size( )       Returns the number of entries in the hash table.

String toString( ) Returns the string equivalent of a hash table.

Enumeration       Returns an enumeration of the keys contained in the
keys( )           hash table.
Object
put(Object key    Inserts a key and a value into the hash table.
Object value)                                                http://www.java2all.com
import java.util.*;
  public class hash1
{
   public static void main(String args[])
   {
     Hashtable marks = new Hashtable();
     Enumeration names;
     Enumeration emarks;
     String str;
     int nm;

    // Checks wheather the hashtable is empty
    System.out.println("Is Hashtable empty " + marks.isEmpty());
    marks.put("Ram", 58);
    marks.put("Laxman", 88);
    marks.put("Bharat", 69);
    marks.put("Krishna", 99);
    marks.put("Janki", 54);

    System.out.println("Is Hashtable empty " + marks.isEmpty());
    // Creates enumeration of keys
    names = marks.keys();
    while(names.hasMoreElements())
    {
       str = (String) names.nextElement();
       System.out.println(str + ": " + marks.get(str));
    }
                                                                   http://www.java2all.com
/*
     nm = (Integer) marks.get("Janki");
     marks.put("Janki", nm+15);
     System.out.println("Janki's new marks: " + marks.get("Janki"));

     // Creates enumeration of values
     emarks = marks.elements();
     while(emarks.hasMoreElements())
     {
        nm = (Integer) emarks.nextElement();
        System.out.println(nm);
     }

     // Number of entries in a hashtable
     System.out.println("The number of entries in a table are " + marks.size());

     // Checking wheather the element available

     System.out.println("The element is their " + marks.containsValue(88));
     */
     // Removing an element from hashtable




                                                                                   http://www.java2all.com
System.out.println("========");
    marks.remove("Bharat");
    names = marks.keys();
    while(names.hasMoreElements())
    {
       str = (String) names.nextElement();
       System.out.println(str + ": " + marks.get(str));
    }
    // Returning an String equivalent of the Hashtable

        System.out.println("String " + marks.toString());
        // Emptying hashtable

        marks.clear();
        System.out.println("Is Hashtable empty " + marks.isEmpty());
    }
}
         Output :
         Laxman: 88
         Janki: 54
         Ram: 58
         String {Krishna=99, Laxman=88, Janki=54,
         Ram=58}
         Is Hashtable empty true                                       http://www.java2all.com

Mais conteúdo relacionado

Mais procurados

Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 

Mais procurados (20)

Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java packages
Java packagesJava packages
Java packages
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
 
Java swing
Java swingJava swing
Java swing
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Applet programming
Applet programming Applet programming
Applet programming
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 

Destaque

Email and web security
Email and web securityEmail and web security
Email and web security
shahhardik27
 
Intrusion detection system ppt
Intrusion detection system pptIntrusion detection system ppt
Intrusion detection system ppt
Sheetal Verma
 
Importance Of A Security Policy
Importance Of A Security PolicyImportance Of A Security Policy
Importance Of A Security Policy
charlesgarrett
 

Destaque (15)

Graphics programming in Java
Graphics programming in JavaGraphics programming in Java
Graphics programming in Java
 
Network Security Primer
Network Security PrimerNetwork Security Primer
Network Security Primer
 
Email Security
Email SecurityEmail Security
Email Security
 
Microsoft Hololens
Microsoft Hololens Microsoft Hololens
Microsoft Hololens
 
Threats to information security
Threats to information securityThreats to information security
Threats to information security
 
pgp s mime
pgp s mimepgp s mime
pgp s mime
 
Email and web security
Email and web securityEmail and web security
Email and web security
 
Intrusion detection system
Intrusion detection system Intrusion detection system
Intrusion detection system
 
Intrusion detection system ppt
Intrusion detection system pptIntrusion detection system ppt
Intrusion detection system ppt
 
Threats to Information Resources - MIS - Shimna
Threats to Information Resources - MIS - ShimnaThreats to Information Resources - MIS - Shimna
Threats to Information Resources - MIS - Shimna
 
Information security: importance of having defined policy & process
Information security: importance of having defined policy & processInformation security: importance of having defined policy & process
Information security: importance of having defined policy & process
 
Importance Of A Security Policy
Importance Of A Security PolicyImportance Of A Security Policy
Importance Of A Security Policy
 
Email security - Netwroking
Email security - Netwroking Email security - Netwroking
Email security - Netwroking
 
Computer security threats & prevention
Computer security threats & preventionComputer security threats & prevention
Computer security threats & prevention
 
Digital signature
Digital signatureDigital signature
Digital signature
 

Semelhante a Packages and inbuilt classes of java

WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_04-Feb-2021_L2_...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_04-Feb-2021_L2_...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_04-Feb-2021_L2_...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_04-Feb-2021_L2_...
MaruMengesha
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf
amitbhachne
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
Satya Johnny
 
Fundamentals of oop lecture 2
Fundamentals of oop lecture 2Fundamentals of oop lecture 2
Fundamentals of oop lecture 2
miiro30
 

Semelhante a Packages and inbuilt classes of java (20)

CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
More topics on Java
More topics on JavaMore topics on Java
More topics on Java
 
Ifi7184 lesson3
Ifi7184 lesson3Ifi7184 lesson3
Ifi7184 lesson3
 
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_04-Feb-2021_L2_...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_04-Feb-2021_L2_...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_04-Feb-2021_L2_...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_04-Feb-2021_L2_...
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf
 
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
 
First fare 2010 java-introduction
First fare 2010 java-introductionFirst fare 2010 java-introduction
First fare 2010 java-introduction
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
 
Fundamentals of oop lecture 2
Fundamentals of oop lecture 2Fundamentals of oop lecture 2
Fundamentals of oop lecture 2
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 

Mais de kamal kotecha

Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with code
kamal kotecha
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 

Mais de kamal kotecha (18)

Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with code
 
Java rmi
Java rmiJava rmi
Java rmi
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
JSP Error handling
JSP Error handlingJSP Error handling
JSP Error handling
 
Jsp element
Jsp elementJsp element
Jsp element
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Interface
InterfaceInterface
Interface
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
 
Class method
Class methodClass method
Class method
 
Control statements
Control statementsControl statements
Control statements
 
Jsp myeclipse
Jsp myeclipseJsp myeclipse
Jsp myeclipse
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 

Último

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Último (20)

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 

Packages and inbuilt classes of java

  • 1. Chapter 9 Packages http://www.java2all.com
  • 2. Introduction http://www.java2all.com
  • 3. Package : Packages are java`s way of grouping a veriety of classes and/or interfaces together. Java API packages : java API provides a large number of classes grouped into different packages according to functionality. Frequently used API packages are as under. http://www.java2all.com
  • 5. Package Contents Name Language support classes. These are classes that java compiler itself uses and therefore they are automatically Java.lang imported. They include classes for primitive types, strings, math functions, threads and exceptions. Language utility classes such as vectors, hash tables, Java.util random numbers, date, etc. Input/output support classes. They provide facilities for Java.io the input and output of the data. Set of classes for implementing graphical user interface. Java.awt They include classes for windows, buttons, lists, menus and so on. Classes for networking. They include classes for Java.net communicating with local computers as well as with internet servers. Java.applet Classes for creating and implementing applets. http://www.java2all.com
  • 6. Syntax for import packages is as under import packagename.classname; or import packagename.*; These are known as import statements and must appear at the top of the file, before any file declaration as you can see in our few examples. Here import is a keyword. The first statement allows the specified class in the specified package to be imported. http://www.java2all.com
  • 7. EX : import java.awt.Color; double y = java.lang.Math.sqrt(x); Here lang is a package, Math is a class and sqrt is a method. For create new package you can write... package firstPackage; public class Firstclass { .................. body of class ................. } http://www.java2all.com
  • 8. Vector Class http://www.java2all.com
  • 9. Vector class : The Vector class is one of the most important in all of the Java class libraries. We cannot expand the size of a static array. We may think of a vector as a dynamic array that automatically expands as more elements are added to it. All vectors are created with some initial capacity. http://www.java2all.com
  • 10. When space is needed to accommodate more elements, the capacity is automatically increased. That is why vectors are commonly used in java programming. http://www.java2all.com
  • 11. This class provides the following constructors: Vector() Vector(int n) Vector(int n, int delta) The first form creates a vector with an initial capacity of ten elements. The second form creates a vector with an initial capacity of n elements. http://www.java2all.com
  • 12. The third form creates a vector with an initial capacity of n elements that increases by delta elements each time it needs to expand. http://www.java2all.com
  • 13. import java.util.*; public class Vector_Demo { public static void main(String args[]) { int i; Vector v = new Vector(); v.addElement(new Integer(10)); v.addElement(new Float(5.5f)); v.addElement(new String("Hi")); v.addElement(new Long(2500)); v.addElement(new Double(23.25)); System.out.println(v); String s = new String("Bhagirath"); v.insertElementAt(s,1); System.out.println(v); v.removeElementAt(2); System.out.println(v); Output : for(i=0;i<5;i++) { } System.out.println(v.elementAt(i)); Bhagirath } } Hi 2500 23.25 http://www.java2all.com
  • 14. Random Class http://www.java2all.com
  • 15. The Random class allows you to generate random double, float, int, or long numbers. This can be very helpful if you are building a simulation of a real-world system. This class provides the following constructors. Random() Random(long start) Here, start is a value to initialize the random number generator. http://www.java2all.com
  • 16. Method Description Double Returns a random double value. nextDouble() Float nextFloat() Returns a random float value. Returns a random double value. Numbers obtained from Double repeated calls to this method have a Gaussian distribution nextGaussian() with a mean of 0 and a standard deviation of 1. Int nextInt() Returns a random int value. Long nextLong() Returns a random long value. Method Description http://www.java2all.com
  • 17. import java.util.*; public class Random_Demo { public static void main(String args[]) { Random ran = new Random(); for(int i = 0; i<5;i++) { System.out.println(ran.nextInt()); } } } Output : 64256704 1265771787 -1962940029 1372052 http://www.java2all.com
  • 18. Date Class http://www.java2all.com
  • 19. Date class : The Date classes encapsulate information about a specific date and time. It provides the following constructors. Date() Date(long msec) Here, the first form returns an object that represent the current date and time. The second form returns an object that represents the date and time msec in milliseconds after http://www.java2all.com
  • 20. Method Description Boolean Returns true if d is after the current date. after(Date d) Otherwise, returns false. Boolean Returns true if d is before the current date. before(Date d) Otherwise, returns false. Boolean Returns true if d has the same value as the equals(Date d) current date. Otherwise, returns false. Returns the number of milliseconds since the Long getTime() epoch. Void setTime Sets the date and time of the current object to (long msec) represent msec milliseconds since the epoch. String Returns the string equivalent of the date. toString() http://www.java2all.com
  • 21. import java.util.*; public class Date_Demo { public static void main(String args[]) { Date dt = new Date(); System.out.println(dt); Date epoch = new Date(0); System.out.println(epoch); } } Output : Fri May 25 00:04:06 IST 2012 Thu Jan 01 05:30:00 IST 1970 http://www.java2all.com
  • 22. import java.util.Date; public class date2 { public static void main(String[] args) { Date d1 = new Date(); Output : try { First Date : Fri May 25 00:06:46 IST 2012 Thread.sleep(1000); } Second Date : Fri May 25 00:06:47 IST catch(Exception e){} 2012 Date d2 = new Date(); Is second date after first ? : true System.out.println("First Date : " + d1); System.out.println("Second Date : " + d2); System.out.println("Is second date after first ? : " + d2.after(d1)); } } http://www.java2all.com
  • 23. import java.util.*; public class date3 { public static void main(String args[]) { Date date = new Date(); System.out.println("Date is : " + date); System.out.println("Milliseconds since January 1, 1970, 00:00:00 GMT : " + date.getTime()); Date epoch = new Date(0); date.setTime(10000); System.out.println("Time after 10 second " + epoch); System.out.println("Time after 10 second " + date); String st = date.toString(); System.out.println(st); } } Output : Date is : Fri May 25 00:12:52 IST 2012 Milliseconds since January 1, 1970, 00:00:00 GMT : 1337884972842 Time after 10 second Thu Jan 01 05:30:00 IST 1970 Time after 10 second Thu Jan 01 05:30:10 IST 1970 Thu Jan 01 05:30:10 IST 1970 http://www.java2all.com
  • 24. Calendar & Gregorian class http://www.java2all.com
  • 25. The Calendar class allows you to interpret date and time information. This class defines several integer constants that are used when you get or set components of the calendar. These are listed here. http://www.java2all.com
  • 26. AM AM_PM APRIL AUGUST DATE DAY_OF_MONTH DAY_OF_WEEK_IN_M DAY_OF_WEEK DAY_OF_YEAR ONTH DECEMBER DST_OFFSET ERA FEBRUARY FIELD_COUNT FRIDAY HOUR HOUR_OF_DAY JANUARY JULY JUNE MARCH MAY MILLISECOND MINUTE http://www.java2all.com
  • 27. MONDAY MONTH NOVEMBER OCTOBER PM SATURADAY SECOND SEPTEMBER SUNDAY THURSDAY TUESDAY UNDERIMBER WEDNESDAY WEEK_OF_MONTH WEEK_OF_YEAR The Calendar class does not have public constructors. Instead, you may use the static YEAR ZONE_OFFSET getInstance() method to obtain a calendar initialized to the current date and time. http://www.java2all.com
  • 28. One of its forms is shown here: Calendar getInstance() http://www.java2all.com
  • 29. import java.util.Calendar; public class Cal1 { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); System.out.println("DATE is : " + cal.get(cal.DATE)); System.out.println("YEAR is : " + cal.get(cal.YEAR)); System.out.println("MONTH is : " + cal.get(cal.MONTH)); System.out.println("DAY OF WEEK is : " + cal.get(cal.DAY_OF_WEEK)); System.out.println("WEEK OF MONTH is : " + cal.get(cal.WEEK_OF_MONTH)); System.out.println("DAY OF YEAR is : " + cal.get(cal.DAY_OF_YEAR)); System.out.println("DAY OF MONTH is : " + cal.get(cal.DAY_OF_MONTH)); System.out.println("WEEK OF YEAR is : " + cal.get(cal.WEEK_OF_YEAR)); System.out.println("HOUR is : " + cal.get(cal.HOUR)); System.out.println("MINUTE is : " + cal.get(cal.MINUTE)); System.out.println("SECOND is : " + cal.get(cal.SECOND)); System.out.println("DAY OF WEEK IN MONTH is : " + cal.get(cal.DAY_OF_WEEK_IN_MONTH)); System.out.println("Era is : " + cal.get(cal.ERA)); System.out.println("HOUR OF DAY is : " + cal.get(cal.HOUR_OF_DAY)); System.out.println("MILLISECOND : " + cal.get(cal.MILLISECOND)); System.out.println("AM_PM : " + cal.get(cal.AM_PM));// Returns 0 if AM and 1 if PM } } http://www.java2all.com
  • 30. Output : Date is : Fri May 25 00:21:14 IST 2012 Milliseconds since January 1, 1970, 00:00:00 GMT : 1337885474477 Time after 10 second Thu Jan 01 05:30:00 IST 1970 Time after 10 second Thu Jan 01 05:30:10 IST 1970 Thu Jan 01 05:30:10 IST 1970 http://www.java2all.com
  • 31. The GregorianCalendar class is a subclass of Calendar. It provides the logic to manage date and time information according to the rules of the Gregorian calendar. This class provides following constructors: GregorianCalendar() GregorianCalendar(int year, int month, int date) GregorianCalendar(int year, int month, int date, int hour, int minute, int sec) http://www.java2all.com
  • 32. GregorianCalendar(int year, int month, int date, int hour, int minute) http://www.java2all.com
  • 33. The first form creates an object initialized with the current date and time. The other forms allow you to specify how various date and time components are initialized. The class provides all of the method defined by Calendar and also adds the isLeapYear() method shown here: Boolean isLeapYear() This method returns true if the current year is a leap year. Otherwise, it returns false. http://www.java2all.com
  • 34. import java.util.*; public class gcal1 Output : { public static void main(String[] args) Era is : 1 { HOUR OF DAY is : 0 GregorianCalendar c1 = new GregorianCalendar() ; MILLISECOND : 780 System.out.println("DATE is : " + c1.get(c1.DATE)); AM_PM : 0 System.out.println("YEAR is : " + c1.get(c1.YEAR)); System.out.println("MONTH is : " + c1.get(c1.MONTH)); System.out.println("DAY OF WEEK is : " + c1.get(c1.DAY_OF_WEEK)); System.out.println("WEEK OF MONTH is : " + c1.get(c1.WEEK_OF_MONTH)); System.out.println("DAY OF YEAR is : " + c1.get(c1.DAY_OF_YEAR)); System.out.println("DAY OF MONTH is : " + c1.get(c1.DAY_OF_MONTH)); System.out.println("WEEK OF YEAR is : " + c1.get(c1.WEEK_OF_YEAR)); System.out.println("HOUR is : " + c1.get(c1.HOUR)); System.out.println("MINUTE is : " + c1.get(c1.MINUTE)); System.out.println("SECOND is : " + c1.get(c1.SECOND)); System.out.println("DAY OF WEEK IN MONTH is : " + c1.get(c1.DAY_OF_WEEK_IN_MONTH)); System.out.println("Era is : " + c1.get(c1.ERA)); System.out.println("HOUR OF DAY is : " + c1.get(c1.HOUR_OF_DAY)); System.out.println("MILLISECOND : " + c1.get(c1.MILLISECOND)); System.out.println("AM_PM : " + c1.get(c1.AM_PM));// Returns 0 if AM and 1 if PM */ } } http://www.java2all.com
  • 35. Math Class http://www.java2all.com
  • 36. Math Class : For scientific and engineering calculations, a variety of mathematical functions are required. Java provides these functions in the Math class available in java.lang package. The methods defined in Math class are given following: http://www.java2all.com
  • 37. Method Description Double Returns the sine value of angle x in radians. sin(double x) Double Returns the cosine value of the angle x in radians cos(double x) Double Returns the tangent value of the angle x in radians tan(double x) Double Returns angle value in radians for arcsin of x asin(double x) Double Returns angle value in radians for arcos of x acos(double x) Double Returns angle value in radians for arctangent of x atan(double x) http://www.java2all.com
  • 38. Double Returns exponential value of x exp(double x) Double Returns the natural logarithm of x log(double x) Double pow(double x, Returns x to the power of y double y) Double Returns the square root of x sqrt(double x) Int abs(double Returns absolute value of n n) Double Returns the smallest wholoe number greater than or ceil(double x) equal to x Double Returns the largest whole number less than or equal floor(double x) to x http://www.java2all.com
  • 39. Int max(int n, int Returns the maximum of n and m m) Int min(int n, int Returns the minimum of n and m m) Double Returns the rounded whole number of x rint(double x) Int round(float Returns the rounded int value of x x) Long Returns the rounded int value of x round(double x) Double Returns a random value between 0 and 1.0 random() Double toRandians(dou Converts the angle in degrees to radians ble angle) Double toDegrees(doubl Converts the angle in radians to degrees http://www.java2all.com
  • 40. public class Angles { public static void main(String args[]) { double theta = 120.0; System.out.println(theta + " degrees is " + Math.toRadians(theta) + " radians."); theta = 1.312; System.out.println(theta + " radians is " + Math.toDegrees(theta) + " degrees."); } } Output : 120.0 degrees is 2.0943951023931953 radians. 1.312 radians is 75.17206272116401 degrees. http://www.java2all.com
  • 41. Hashtable http://www.java2all.com
  • 42. Hashtable is a part of the java.util library and is a concrete implementation of a dictionary. (Dictionary is a class that represents a key/value storage repository. Given a key and value, you can store the value in a Dictionary object. Once the value is stored, you can retrieve it by using its key.) Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want to link to that key. http://www.java2all.com
  • 43. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table. The Hashtable constructors are shown here: Hashtable() Hashtable(int size) The first constructor is the default constructor. The second constructor creates a hash table that has an initial size specified by size. The methods available with Hashtable are http://www.java2all.com
  • 44. Method Description Void clear() Resets and empties the hash table. Boolean Returns true if some key equals to key exists within containsKey(Obj the hash table. Returns false if the key isn’t found. ect key) Boolean Returns true if some value equal to value exists containsValue(O within the hash table. Returns false if the value isn’t bject value) found. Enumeration Returns an enumeration of the values contained in elements( ) the hash table. Returns the object that contains the value associated Object with key. If key is not in the hash table, a null object is get(Object key) returned. Boolean Returns true if the hash table is empty; Returns false isEmpty( ) if it contains at least one key. http://www.java2all.com
  • 45. Enumeration Returns an enumeration of the keys contained in the keys( ) hash table. Object put(Object key Inserts a key and a value into the hash table. Object value) Object Removes key and its value. Returns the value remove(Object associated with key. If key is not in the hash table, a key) null object is returned. Int size( ) Returns the number of entries in the hash table. String toString( ) Returns the string equivalent of a hash table. Enumeration Returns an enumeration of the keys contained in the keys( ) hash table. Object put(Object key Inserts a key and a value into the hash table. Object value) http://www.java2all.com
  • 46. import java.util.*; public class hash1 { public static void main(String args[]) { Hashtable marks = new Hashtable(); Enumeration names; Enumeration emarks; String str; int nm; // Checks wheather the hashtable is empty System.out.println("Is Hashtable empty " + marks.isEmpty()); marks.put("Ram", 58); marks.put("Laxman", 88); marks.put("Bharat", 69); marks.put("Krishna", 99); marks.put("Janki", 54); System.out.println("Is Hashtable empty " + marks.isEmpty()); // Creates enumeration of keys names = marks.keys(); while(names.hasMoreElements()) { str = (String) names.nextElement(); System.out.println(str + ": " + marks.get(str)); } http://www.java2all.com
  • 47. /* nm = (Integer) marks.get("Janki"); marks.put("Janki", nm+15); System.out.println("Janki's new marks: " + marks.get("Janki")); // Creates enumeration of values emarks = marks.elements(); while(emarks.hasMoreElements()) { nm = (Integer) emarks.nextElement(); System.out.println(nm); } // Number of entries in a hashtable System.out.println("The number of entries in a table are " + marks.size()); // Checking wheather the element available System.out.println("The element is their " + marks.containsValue(88)); */ // Removing an element from hashtable http://www.java2all.com
  • 48. System.out.println("========"); marks.remove("Bharat"); names = marks.keys(); while(names.hasMoreElements()) { str = (String) names.nextElement(); System.out.println(str + ": " + marks.get(str)); } // Returning an String equivalent of the Hashtable System.out.println("String " + marks.toString()); // Emptying hashtable marks.clear(); System.out.println("Is Hashtable empty " + marks.isEmpty()); } } Output : Laxman: 88 Janki: 54 Ram: 58 String {Krishna=99, Laxman=88, Janki=54, Ram=58} Is Hashtable empty true http://www.java2all.com

Notas do Editor

  1. White Space Characters