Let's learn java programming language with easy steps

Sunday, 25 June 2017

StringTokenizer In Java

Java StringTokenizer

StringTokenizer

The StringTokenizer class allows an application to break a string into tokens(parts). The StringTokenizer class are available into java.util package.

In other words, StringTokenizer class breaks a string on the basis of delimiters(spaces or any special symbols).

for example : suppose there is a word or String "Java is a simple programming language". We can break this string into tokens(part) with the help of delimiters like spaces or any special symbols.

java
is
a
simple
programming
language

The StringTokenizer is a legacy class in java.


Constructors of StringTokenizer Class

There are some constructors of StringTokenizer class, these are

1) StringTokenizer(String str)

This constructor creates a string tokenizer for the specified string.

2) StringTokenizer(String str, String delim)

This constructor creates a string tokenizer for the specified string and delimiter.

3) StringTokenizer(String str, String delim, boolean retrunDelims)

This constructor creates a string tokenizer for the specified string delimiter and return value. If return value is true, delimiter characters are considered to be tokens. If return values is false, delimiter characters serve to separate tokens.


Methods of StringTokenizer Class

There are some certain methods of StringTokenizer class in java which is given below.

1) boolean hasMoreTokens()

This method tests if there are more tokens available from this tokenizer's string.

2) boolean hasMoreElements()

This method returns the same value as the hasMoreTokens method.

3) String nextToken()

This method returns the next token from this string tokenizer.

4) Object nextElement()

This method returns the same value as the nextToken() method, excepts that is declared return value is Object rather than String.

5) String nextToken(String delim)

This method returns the next token in this string tokenizer's string.

6) int countTokens()

This methods returns the total numbers of tokens.


Java StringTokenizer Example

This is simple example of string tokenizer class where we will break or tokenize this string " java is a simple programming language" on the basis of white spaces. Space is the default delimiter.

import java.util.StringTokenizer;
class StringTokenizerExample
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer("java is a simple programming language", " ");//using space delimiter
while(st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}

output : java
              is
              a
              simple
              programming
              language


Java StringTokenizer Example 1

This is another example of StringTokenizer, in this example we will break the string on the basis of 2 delimiters " space" and " comma". Space is the default delimiter.

import java.util.StringTokenizer;
public class StringTokenizerExample1
{
public static void main(String args[])
{
String s = "i am john, thank you";
StringTokenizer st = new StringTokenizer(s);//by using space
StringTokenizer st1 = new StringTokenizer(s, ",");//by using comma

System.out.println("tokenize by using space delimiter");

while(st.hasMoreTokens())

{

System.out.println(st.nextToken());

}

System.out.println("tokenize by using comma delimiter");


while(st1.hasMoreTokens())
{
System.out.println(st1.nextToken());
}
}
}

output : tokenize by using space delimiter
              i
              am
              john,
              thank
              you
              tokenize by using comma delimiter
              i am john
               thank you

Java StringTokenizer Example 2

This is the same example as above except that there we will use different method hasMoreElements() and nextElement() and in this example there is space between john and , e.g i am john , thank you.


import java.util.StringTokenizer;
public class StringTokenizerExample2
{
public static void main(String args[])
{
String s = "i am john , thank you";
StringTokenizer st = new StringTokenizer(s);//by using space
StringTokenizer st1 = new StringTokenizer(s, ",");//by using comma

System.out.println("tokenize by using space delimiter");

while(st.hasMoreElements())

{
System.out.println(st.nextElement());
}

System.out.println("tokenize by using comma delimiter");


while(st1.hasMoreElements())

{

System.out.println(st1.nextElement());
}
}
}

output : 
tokenize by using space delimiter
am
john
,
thank
you
tokenize by using comma delimiter
i am john
 thank you

Share:

Saturday, 24 June 2017

Java HashTable

Java HashTable Class

In java Hashtable is a class which is available in java.util package. This class implements hash table, which maps key to values.

Java Hashtable class extends Dictionary class and implements Map interface in java collection Framework.


Some Points About Java Hashtable Class

  • Java Hashtable class implements hash table, which maps key to values.
  • Java Hashtable class extends(inherit) Dictionary class and implements Map interface.
  • Hashtable class stores the key and value pairs.
  • Hashtable class stores only unique elements.
  • Hashtable class is synchronized i.e multiple threads cannot access simultaneously. In other word Hashtable class is thread-safe.
  • Hashtable class doesn't allows null keys and null values.
  • Hashtable class is a legacy class and it uses hashing technique to store the elements i.e it doesn't maintains insertion order of an elements.
  • By using Iterator interface, for each loop and Enumeration interface you can easily retrieve the elements from the Hashtable class.


Hierarchy of Hashtable Class

Java Hashtable


Java Constructors of Hashtable Class

There are some constructors of hash table class, these are given below

1) Hashtable()

It constructs a  new, empty hashtable with the default initial capacity(11) and load factor(0.75).

2) Hashtable(int initialCapacity)

It constructs a  new, empty hashtable with the specified initial capacity and load factor(0.75).

3) Hashtable(int initialCapacity, float loadFactor)

It constructs a  new, empty hashtable with the specified initial capacity and specified load factor.

4) Hashtable(Map m)

It constructs the new hashtable with the same mapping as the given map.


Methods of Hashtable Class

There are certain methods of Hashtable class, which is

1) void clear()

This method clears this hashtable so that it contains no key.

2) Object clone()

This method creates a shallow copy of this hashtable.

3) boolean contains(Object value)

It returns true if some value equal to the value exists within the hash table, otherwise returns false.

4) boolean containsValue(Object value)

It returns true if some value equal to the value exists within the hash table, otherwise returns false.

5) boolean containsKey(Object key)

It returns true if some key equal to the key exists within the hash table, otherwise returns false.

6) boolean equals(Object o)

This method compares the specified Object with this Map for equality.

7) int hasCode()

This method returns the hash code value for this Map.

8) boolean isEmpty()

This method returns true if the hash table is empty otherwise it returns false.

9) void putAll(Map t)

This methods copies all of the mappings from the specified map to this hash table.

10) protected void rehash()

It is use to increase the size of the hash table.

11) int size()

This method returns the number of the keys in this hashtable.


Java Hashtable Example

This is simple example of hash table class in java collection.

import java.util.*;
class HashTableExample
{
public static void main(String args[])
{
//creating Hashtable object
Hashtable<Integer, String> ht = new Hashtable<Integer, String>();
ht.put(7, "sachin");
ht.put(9, "virat");
ht.put(5, "rohit");
ht.put(2, "bumrah");
ht.put(8, "dhoni");

for(Map.Entry me : ht.entrySet())
{
System.out.println(me.getKey()+" "+me.getValue());
}
}
}

output : 9 virat
              8 dhoni
              7 sachin
              5 rohit
              2 bumrah 
Share:

Tuesday, 20 June 2017

Java Garbage Collection

Garbage Collection

Java Garbage Collection

Garbage collection, Here garbage means unused or unreferenced objects. 

In java, Garbage collection is the way to destroy all the unused and unreferenced objects from the heap memory and garbage collection are performed by the JVM automatically. We do not need to write any extra code in our java program.

If we want to perform garbage collection in c language and c++ then we have to use free() function in c language and delete() function in c++ but in java it is performed automatically, so java provides batter memory management and it make memory efficient.


Advantage of Garbage Collection

There are some advantage of garbage collection in java. These are
  • It makes the memory efficient because garbage collector destroy all the unused and unreferenced objects from the heap memory.
  • It saves time because the garbage collection is performed by the JVM so we do not need to write any extra code in java programs.
  • It reduces the length of the code because it is handled by the JVM, so we don't need to write extra code in prorgram.
  • Programmer does not need to worry about dereferencing an objects.

When an Objects Becomes eligible for Garbage Collection

There are many ways when objects becomes unused and unreferenced in java. these are
  1. By nulling the reference.
  2. By assigning a reference to another.
  3. By annonymous objects etc.

1) Example of by nulling a reference

Student s = new Student();
s = null;

2) Example of by assigning a reference to another

Student s = new Student();
Student s1 = new Student();
s = s1;

3) Example of by using annonymous object

new Student();


Finalize Method

The finalize() method comes from Object class which is available in java.lang package. 

In java sometimes object will need to perform some specific task before it garbage collected such as open and closing connection etc. To handle this situation finalize() method is used.

Basically finalize() method is used to clean-up processing.

Before the object is garbage collected, finalize() method invoked each time.

Syntax of finalize() method :

protected void finalize(){}

The finalize method is called by the garbage collector thread of JVM. Garbage collector thread is Daemon thread.

In java garbage collection is performed by the Daemon thread called garbage collector (gc).


gc() Method

The gc() method is used to invoke garbage collector to perform cleanup processing. The gc() method is defined in the System and Runtime classes.


Java Garbage Collection Example

public class GarbageCollectionTest
{
public void finalize()
{
System.out.println("object is garbage collected");
}
public static void main(String args[])
{
GarbageCollectionTest g = new GarbageCollectionTest();
GarbageCollectionTest g1 = new GarbageCollectionTest();

g = null;
g1 = null;

System.gc();
}
}

output : object is garbage collected
              object is garbage collected

Q. Can garbage collection be the forced explicitly ?

Ans. No, Garbage collection cannot be the forced explicitly but we may request to the JVM for garbage collection. There is no guarantee that JVM will perform garbage collection its totally depend on JVM. We can only request to the Java Virtual Machine(JVM).




Share:

Monday, 19 June 2017

Java Comparator

Comparator Interface

Java Comparator

Comparator is a interface in java which is available in java.util package.

Comparator is used to sort or order the objects of user-defined class.

As we know comparable interface contains only one method compareTo(Object) but comparator interface contains 2 methods which is compare(Object obj1, Object obj2) and equals(Object element).

Comparator interface provides multiple sorting sequence i.e you can sort the elements on the basis of any data member such as name, age, rollno, etc.

A comparison function, which imposes a total ordering on some collection of objects. Comparator can be passed to a sort method(such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparator can also be used to control the order of certain data structure(such as sorted sets and sorted maps) or to provide an ordering for collections of objects that don't have a natural ordering.


Methods of Comparator Interface

  1. public int compare(Object obj1, Object obj2) : This method compares the first object with second object.
  2. boolean equals(Object obj) : This method indicates whether some other objects is "equal to " this comparator.

Collections Class


Collections is a class in java, It is not a collection(interface), it is a collections(class) which provides us static method so that we can easily sort the elements of collections. If the elements of collection is a type of Set or Map then we will sort these elements easily by using treeSet and treeMap class but we cannot sort the elements of List if we want to sort the elements of List type , We have to use method of Collections's class so that we can easily sort the elements of List type.


Collections class extends only super class i.e Object class.


The methods of this class all throw a NullPointerException, if the collections or class objects provide them are null.

Method of Collections Class

public void sort(List list, Comparator c) : This method is used to sort the elements of List by the given Comparator.


Java Comparator Example

This is a comparator example, where we will sort the elements of List type on the basis of age and name. Here we will create 4 .java files.

File 1 : Student.java
class Student
{
int rollno;
String name;
int age;
Student(int rollno, String name, int age)
{
this.rollno = rollno;
this.name = name;
this.age = age;
}
}

File 2 : AgeComparator.java

In this java file, we will define the comparison logic based on age. If age of first object is greater than the second it will return positive value and if age of first object is less than the second object it will return negative value, if both will be equal, return 0.

import java.util.*;
class AgeComparator implements Comparator<Student>
{
public int compare(Student s1, Student s2)
{
if(s1.age == s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
}
}

File 3 : NameComparator.java

In this java file, we will define comparison logic based on name and we will use compareTo() method.

import java.util.*;
class NameComparator implements Comparator<Student>
{
public int compare(Student s1, Student s2)
{
return s1.name.compareTo(s2.name);
}
}

File 4 : Test.java

In this java file, we will sort the List on the basis of age and name.

import java.util.*;
class Test
{
public static void main(String args[])
{
ArrayList<Student> al = new ArrayList<Student>();
al.add(new Student(100, "salman", 19);
al.add(new Student(105, "ranvir", 9);
al.add(new Student(102, "varun", 29);
al.add(new Student(107, "arjun", 18);

System.out.println("sorting by name");
Collections.sort(al, new NameComparator());
for(Student st : al)
{
System.out.println(st.rollno+" " +st.name+" " +st.age);
}

System.out.println("sorting by age");
Collections.sort(al, new AgeComparator());
for(Student st : al)
{
System.out.println(st.rollno+" " +st.name+" " +st.age);
}
}
}

output : sorting by name
              107 arjun 18
              105 ranvir 9
              100 salman 19
              102 varun 29

              sorting by age
              105 ranvir 9
              107 arjun 18
              100 salman 19
              102 varun 29




Share:

Facebook Page Likes

Popular Posts

Translate