Exploring Java - Lang & Java - Util: Accent e Technology Pvt. LTD

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 28

Java

Exploring java.lang & java.util

Accent e Technology pvt. Ltd.


http://www.accentonline.co.in

Wrapper Classes
Java uses simple types, such as int, byte, float and
char, for performance reasons.
At times, you will need to create an object
representation for one of these simple types.
To address this need, Java provides wrapper classes
that correspond to each of the simple types.

The Number Class


The abstract class Number defines a superclass that is
implemented by the classes that wrap the numeric types
byte, short, int, long, float, and double.
Number has six concrete subclasses that hold explicit
values of each numeric type:
Double, Float, Byte, Short, Integer, and Long.

Number has abstract methods that return the value of the


object in each of the different number formats.

byte byteValue( )
double doubleValue( )
float floatValue( )
int intValue( )
long longValue( )
short shortValue( )

Wrapper - Example
class WrapperDemo
{
public static void main(String args[] )
{
Byte ob = new Byte((byte)125);
long obl = ob.longValue();
System.out.println("Byte " + ob + " is now long " + obl);
Double od = new Double(45.6783);
int odi = od.intValue();
System.out.println("Double " + od + " is now int " + odi);

Wrapper - Example
Float of = new Float(67.56);
short ofs = of.shortValue();
System.out.println("Float " + of + " is now short " + ofs);
Integer oi = new Integer(10000);
float oif = oi.floatValue();
System.out.println("Integer " + oi + " is now float " + oif);
Long ol = new Long(678345546);
double old = ol.doubleValue();
System.out.println("Long " + ol + " is now double " + old);
}
}

String / Number Conversion


The parseByte( ), parseShort( ), parseInt( ) and
parseLong( ) methods return the byte, short, int, or
long equivalent of the numeric string with which
they are called.
To convert a whole number into a decimal string,
use the versions of toString( ) defined in the Byte,
Short, Integer or Long classes.
The Integer class also provide the methods
toBinaryString(
),
toHexString(
)
and
toOctalString( ), which convert a value into a
binary, hexadecimal, or octal string, respectively.

Conversion - Example
class ParseConversionDemo
{
public static void main(String args[ ])
{
String str = "100";
int num = 2008;
int i = Integer.parseInt (str);
System.out.println("String 100 is int " + i );
byte b = Byte.parseByte (str);
System.out.println("String 100 is byte " + b );
short s = Short.parseShort (str);

Conversion - Example
System.out.println("String 100 is short " + s );
long l = Long.parseLong (str);
System.out.println("String 100 is long " + l );
String sbs = Integer.toBinaryString(num);
System.out.println("int 2008 in binaryStr " + sbs);
String sos = Integer.toOctalString(num);
System.out.println("int 2008 in octalStr " + sos);
String shs = Integer.toHexString(num);
System.out.println("int 2008 in hexaStr " + shs);
}
}

The Character Class


Character is a simple wrapper around a char. The
constructor for Character is
Character(char ch)

To obtain the char value contained in a Character


object, call charValue( ) method as,
char charValue( )

Character includes several static methods that


categorize characters and alter their case.

Character - Example
class IsCharDemo
{
public static void main(String args[])
{
char a[] = {'a', '5', 'B', ' '};
for(int i=0; i < a.length ; i++)
{
if( Character.isDigit (a[i]))
System.out.println(a[i] + " is a digit.");
if( Character.isLetter (a[i]))
System.out.println(a[i] + " is a letter.");

Character - Example
if( Character.isWhitespace (a[i]))
System.out.println(a[i] + " is whitespace.");
if( Character.isUpperCase (a[i]))
System.out.println(a[i] + " is uppercase.");
if( Character.isLowerCase (a[i]))
System.out.println(a[i] + " is lowercase.");
}
}
}

Executing Other Programs


class ExecDemo
{
public static void main(String args[])
{
Runtime r = Runtime.getRuntime();
Process p = null;
try
{
p = r.exec("calc");
}
catch (Exception e)
{
System.err.println("Error in Execution.");
}
}
}

Collections Overview
A collection is a group of objects.
The Java collections framework standardizes the
way in which groups of objects are handled by your
programs.
java.util is one of Java's most widely used packages.
Their applications include generating pseudorandom
numbers, manipulating date and time, and tokenizing
strings.
The collection framework defines several classes and
interfaces.

Collections Overview
The
collection
interfaces
determine
the
characteristics of a collection.
At the top of the interface hierarchy is Collection,
which defines the features common to all collections.
Subinterfaces add the attributes related to specific
types of collections.
Several classes, such as ArrayList, LinkedList
provide concrete implementations of the collection
interfaces.
Algorithms are static methods defined within the
Collections class that operate on collections.

The ArrayList Class


The ArrayList class extends AbstractList and
implements the List interface.
ArrayList supports dynamic arrays that can grow as
needed.
Array lists are created with an initial size.
When this size is exceeded, the collection is
automatically enlarged. When objects are removed,
the collection is shrunk.

ArrayList - Example
import java.util.*;
class ArrayListDemo
{
public static void main(String args[])
{
ArrayList alOb = new ArrayList();
System.out.println("Initial size of al: " + alOb.size());
alOb.add("C");
alOb.add("A");
alOb.add("E");
alOb.add("B");

ArrayList - Example
alOb.add("D");
alOb.add("F");
alOb.add(1, "A2");
System.out.println("Size of al after additions: " + alOb.size());
System.out.println("Contents of al: " + alOb);
alOb.remove("F");
alOb.remove(2);
System.out.println("Size of al after deletions: " + alOb.size());
System.out.println("Contents of al: " + alOb);
}
}

The LinkedList Class


The
LinkedList
class
extends
AbstractSequentialList and implements the List
interface.
LinkedList class defines some useful methods of its
own for manipulating and accessing lists.
To obtain the current value of an element, pass get( )
the index at which the element is stored.
To assign a new value to that index, pass set( ) the
index and its new value.

LinkedList - Example
import java.util.*;
class LinkedListDemo
{
public static void main(String args[])
{
LinkedList llOb = new LinkedList();
llOb.add("F");
llOb.add("B");
llOb.add("D");
llOb.add("E");
llOb.add("C");
llOb.addLast("Z");
llOb.addFirst("A");

LinkedList - Example
llOb.add(1, "A2");
System.out.println("Original contents of llOb: " + llOb);
llOb.remove("F");
llOb.remove(2);
System.out.println("Contents of llOb after deletion: " + llOb);
llOb.removeFirst();
llOb.removeLast();
System.out.println("llOb after deleting first and last: "+ llOb);
Object val = llOb.get(2);
llOb.set(2, (String) val + " Changed");
System.out.println("llOb after change: " + llOb);
}
}

HashSet - Example
import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
HashSet hs = new HashSet();
hs.add("B");
hs.add("A");
hs.add(new Integer(1000));
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}

TreeSet - Example
import java.util.*;
class TreeSetDemo {
public static void main(String args[]) {
TreeSet ts = new TreeSet();
ts.add("C");
ts.add("A");
ts.add("E");
ts.add("Demo");
ts.add("Xplore");
ts.add("String");
System.out.println(ts);
}
}

The Collection Algorithms


The collections framework defines several
algorithms that can be applied to collections.
These algorithms are defined as static methods
within the Collections class. Some of the important
methods are,
static Object max(Collection c)
Returns the maximum element in c as determined by natural
ordering.

static Object min(Collection c)


Returns the minimum element in c as determined by natural
ordering.

The Collection Algorithms


static void copy(List list1, List list2)
Copies the elements of list2 to list1.

static void reverse(List list)


Reverses the sequence in list.

static void shuffle(List list)


Shuffles (i.e., randomizes) the elements in list.

static void sort(List list)


Sorts the elements of list as determined by their natural
ordering.

static void fill(List list, Object obj)


Assigns obj to each element of list.

The Vector Class


import java.util.*;
class VectorDemo
{
public static void main(String args[])
{
Vector v = new Vector();
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Double(5.45));
v.addElement(new Float(9.4));
Enumeration vEnum = v.elements();
System.out.println("Elements in vector:");
while( vEnum.hasMoreElements ())
System.out.print( vEnum.nextElement () + " ");
System.out.println();
}
}

The StringTokenizer Class


import java.util.*;
class StringToken
{
static String s = "Central_Park_Plaza_Inn";
public static void main(String args[])
{
StringTokenizer str = new StringTokenizer(s,"_");
Vector v = new Vector();
while( str.hasMoreTokens ())
v.addElement(str.nextToken());
System.out.println("Vector Contains : " + v);
}
}

The Date Class


import java.util.Date;
class DateDemo
{
public static void main(String args[])
{
Date date = new Date();
System.out.print("Today's Date is ");
System.out.print(date.getDate() + "/");
System.out.print(date.getMonth() + 1 + "/");
System.out.println(date.getYear() + 1900);
}
}

The Random Class


import java.util.Random;
public class RandomNumberTest
{
public static void main(String[] args)
{
Random random = new Random();
int rV1 = random.nextInt();
int rV2 = random.nextInt(1000);
long rV3 = random.nextLong();
float rV4 = random.nextFloat();
System.out.println(rV1 + "\n" + rV2 + "\n"+ rV3+ "\n"+ rV4);
}
}

You might also like