Friday, 6 November 2015

How to convert character literal into an integer in java?


You can use Character.getNumericValue(char c) method to get the character in integer values.


Sample Program:-


 /**  
  * @author Dixit  
  *   
  */  
 public class CharToInteger {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           String str = "1234aB";  
           for (int i = 0; i < str.length(); i++) {  
                char c = str.charAt(i);  
                System.out.println(Character.getNumericValue(c));  
           }  
      }  
 }  

NOTE:-  Character.getNumericValue(char c) :-Returns the int value that the specified Unicode  character represents. For example, the character  '\u216C' (the roman numeral fifty) will return  an int with a value of 50.  

The letters A-Z in their uppercase ('\u0041' through  '\u005A'), lowercase  ('\u0061' through '\u007A'), and  full width variant ('\uFF21' through  '\uFF3A' and '\uFF41' through  '\uFF5A') forms have numeric values from 10  through 35. This is independent of the Unicode specification,  which does not assign numeric values to these char  values.  

If the character does not have a numeric value, then -1 is returned.  If the character has a numeric value that cannot be represented as a  nonnegative integer (for example, a fractional value), then -2  is returned.

Enjoy Programming.

Difference between Enumeration and Iterator ?


Both Iterator and Enumeration allows you to traverse over elements of Collections in Java.Iterator allows you to remove elements from collection during traversal but Enumeration doesn't allow that. Enumeration is introduced in legacy class and not all Collection class supports it .For example:- Vector supports Enumeration but ArrayList doesn't.


Example of Iterator:-

 public static void main(String[] args) {  
           List<String> list = new ArrayList<String>();  
           list.add("Java");  
           list.add("C++");  
           list.add("C");  
           list.add("Python");  
           Iterator<String> itr = list.iterator();  
           while (itr.hasNext()) {  
                System.out.println(itr.next());  
           }  

Example of Enumeration:-


 public static void main(String[] args) {  
           List<String> list = new ArrayList<String>();  
           list.add("Java");  
           list.add("C++");  
           list.add("C");  
           list.add("Python");  
           Enumeration<String> e=Collections.enumeration(list);  
           while(e.hasMoreElements())  
           {  
                System.out.println(e.nextElement());  
           }  
      }  




Enumeration
Iterator
Enumeration doesn't have a remove() method
Iterator has a remove() method
Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects
Can be abstract, final, native, static, or synchronized


Note:- Enumeration is used whenever we want to make Collection objects as Read-only.


Enjoy Reading

Difference between Class Methods and Instance Methods


Class Methods are nothing but static methods which are called without an instance of the class where as Instance methods needs an instance of class .

For example:- public static void display() is an Class method

where as class A
                    {

                             public void display()
                          {
                                ......................
                           }
                     
                public static void main(String[] args) {
                           A a = new A();
                            a.display();// Instance method
                       
                    }
                }


Class Methods
Instance Methods
Class methods are methods which are declared as static. The method can be called without creating an instance of the class
Instance methods on the other hand require an instance of the class to exist before they can be called, so an instance of a class needs to be created by using the new keyword.
Instance methods operate on specific instances of classes.
Class methods can only operate on class members and not on instance members as class methods are unaware of instance members.
Instance methods of the class can also not be called from within a class method unless they are being called on an instance of that class.
Class methods are methods which are declared as static. The method can be called without creating an instance of the class.
Instance methods are not declared as static.



Enjoy Reading.

Difference between Consructors and Methods?



A Constructor is a special method whose task is to initialize the object of its class. It is special because its name is the same as the class name. They do not have return types, not even void and therefore they cannot return values. They cannot be inherited, though a derived class can call the base class constructor. Constructor is invoked whenever an object of its associated class is created.
whereas Methods  refers to group of statement enclosed within curly braces{}.Its name should be other the name of class.




Constructors
Methods
Purpose
Create an instance of a class
Group Java statements
Modifiers
Cannot be abstract, final, native, static, or synchronized
Can be abstract, final, native, static, or synchronized
Return Type
No return type, not even void
void or a valid return type
Name
Same name as the class (first letter is capitalized by convention) -- usually a noun
Any name except the class. Method names begin with a lowercase letter by convention -- usually the name of an action
This
Refers to another constructor in the same class. If used, it must be the first line of the constructor
Refers to an instance of the owning class. Cannot be used by static methods.
super
Calls the constructor of the parent class. If used, must be the first line of the constructor
Calls an overridden method in the parent class
Inheritance
Constructors are not inherited
Methods are inherited


Enjoy Reading.

Difference between Interface and Abstract class


A very common asked in interview at all levels Freshers as well as Experienced level.Interface and Abstrat class.forms the basics of Java.here are some differences between the two.




Abstract Class
Interfaces
An abstract class can provide complete, default code and/or just the details that have to be overridden.
An interface cannot provide any code at all, just the signature.
In case of abstract class, a class may extend only one abstract class.
A Class may implement several interfaces.
An abstract class can have non-abstract methods.
All methods of an Interface are abstract.
An abstract class can have instance variables.
An Interface cannot have instance variables.
An abstract class can have any visibility: public, private, protected.
An Interface visibility must be public (or) none.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
An abstract class can contain constructors.
An Interface cannot contain constructors.
Abstract classes are fast.
Interfaces are slow as it requires extra indirection to find corresponding method in the actual class.



Prepare well.Enjoy Reading.

Thursday, 5 November 2015

Write an program such that if an element in an NxN matrix is 0, its entire row and column is set to 0.



Its simple just you need to keep track in two arrays all the rows with zeros and all the columns with zeros. You then make a second pass of the matrix and set a cell to zero if its row or column is zero.


Sample Program:-


 /**  
  * @author Dixit  
  *   
  */  
 public class MatrixProblem {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           int m[][] = { { 1, 2, 0 }, { 3, 4, 5 }, { 6, 7, 8 } };  
           setZeros(m);  
      }  
      public static void setZeros(int[][] matrix) {  
           int[] row = new int[matrix.length];  
           int[] column = new int[matrix[0].length];  
           // Store the row and column index with value 0  
           for (int i = 0; i < matrix.length; i++) {  
                for (int j = 0; j < matrix[0].length; j++) {  
                     if (matrix[i][j] == 0) {  
                          row[i] = 1;  
                          column[j] = 1;  
                     }  
                }  
           }  
           // Set arr[i][j] to 0 if either row i or column j has a 0  
           for (int i = 0; i < matrix.length; i++) {  
                for (int j = 0; j < matrix[0].length; j++) {  
                     if ((row[i] == 1 || column[j] == 1)) {  
                          matrix[i][j] = 0;  
                     }  
                }  
           }  
           for (int i = 0; i < matrix.length; i++) {  
                for (int j = 0; j < matrix.length; j++) {  
                     System.out.print(matrix[i][j] + " ");  
                }  
                System.out.println("\n");  
           }  
      }  
 }  


Output:-


 0 0 0   
 3 4 0   
 6 7 0   


Enjoy Programming.

Java program to check if given String is Pangram or not


A pangram or holoalphabetic sentence for a given alphabet is a sentence using every letter of the alphabet at least once.

For Example:-
  • We promptly judged antique ivory buckles for the next prize.
  • How razorback jumping frogs can level six piqued gymnasts.
  • Sixty zippers were quickly picked from the woven jute bag.
  • Crazy Fredrick bought many very exquisite opal jewels.
  • Jump by vow of quick, lazy strength in Oxford.
  • The quick brown fox jumps over the lazy dog.

Sample Program:-


 /**  
  * @author Dixit  
  *   
  */  
 public class PangramExample {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           String s = "The quick brown fox jumps over the lazy dog";  
           System.out.println("Is given String Pangram ? : "  
                     + isPangramString(s.toLowerCase()));  
      }  
      private static boolean isPangramString(String s) {  
           if (s.length() < 26)  
                return false;  
           else {  
                for (char ch = 'a'; ch <= 'z'; ch++) {  
                     if (s.indexOf(ch) < 0) {  
                          return false;  
                     }  
                }  
           }  
           return true;  
      }  
 }  


Output:-

 Is given String Pangram ? : true  


Enjoy Programming.

Write a program to check if two strings are anagrams or not.


An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once. Any word or phrase that exactly reproduces the letters in another order is an anagram.

For example:-    William Shakespeare = I am a weakish speller
                         Debit card = Bad credit
                         Dormitory = Dirty Room         
                         School master = The classroom
  

Sample Program:-

 import java.util.Arrays;  
 /**  
  * @author Dixit  
  *  
  */  
 public class AnagramStrings {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           String first="Dormitory";  
           String second="Dirty Room";  
           // sort both the string  
           String sortedFirstString=sortString(first.toLowerCase().toCharArray());  
           String sortedSecondString=sortString(second.toLowerCase().toCharArray());  
           if(sortedFirstString.trim().equals(sortedSecondString.trim()))  
           {  
                System.out.println("Anagrams");  
           }  
           else  
           {  
                System.out.println("Not Anagrams");  
           }  
      }  
      private static String sortString(char[] cs) {  
           Arrays.sort(cs);  
           return new String(cs);  
      }  
 }  

Output:-

 Anagrams  


Enjoy Programming.

Write a program that adds two numbers.You should not use + or any arithmetic operators.



To solve this problem, you need to work on binary representation of numbers and bitwise operators.

Approach to solve this problem is:-

-   If you add two binary numbers together but forget to carry, bit[i] will be 0 if bit[i] in a and b are both 0 or both 1.This is an XOR.

-   If you add two numbers together but only carry, you will have a 1 in bit[i] if bit[i-1] in a and b are both 1’s.This is an AND, shifted.

-   Now, recurse until there’s nothing to carry.


Sample Program:-

 /**  
  * @author Dixit  
  *   
  */  
 public class AddNumber {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           int a = 2;  
           int b = 3;  
           System.out  
                     .println("Addition of two number without using addition operator:"  
                               + add(a, b));  
      }  
      static int add(int a, int b) {  
           if (b == 0)  
                return a;  
           int sum = a ^ b; // add without carrying  
           int carry = (a & b) << 1; // carry, but don’t add  
           return add(sum, carry); // recurse  
      }  
 }  


Output:-

Addition of two number without using addition operator:5  

How Solution Works?

-- Initially a=2 and b=3,call add(2,3)

-- Apply the XOR operation on ‘a’ and ‘b’ i.e. 2^3 but don’t consider carry. So you get sum as                        1(0001)

-- Apply (a & b) << 1, returns carry as 4(0100)

-- Call add(1,4) recursive call.

-- Again,Apply the XOR operation on ‘a’ and ‘b’ i.e. 1^4 but don’t consider carry. So you get sum as              5(0101)

-- Apply (a & b) << 1, returns carry as 0(0000)

-- Recursively call (5,0) which returns 5 if ‘b’ is 0.


Enjoy Programming.


Collection class: Thread-Safe Collections


Thread-Safe Collections :-  Similar to read-only collections, thread-safe collections are factory decorators that wrap instances of the six core interfaces into thread-safe versions.

  • Collection synchronizedCollection(Collection collection)
  • List synchronizedList(List list)
  • Map synchronizedMap(Map map)
  • Set synchronizedSet(Set set)
  • SortedMap synchronizedSortedMap(SortedMap map)
  • SortedSet synchronizedSortedSet(SortedSet set)


Synchronize the collection immediately after creating it. You also must not retain a reference to the original collection, or else you can access the collection unsynchronized. The simplest way to make sure you don't retain a reference is never to create one:

Set set = Collections.synchronizedSet(new HashSet());

Making a collection unmodifiable also makes a collection thread-safe, as the collection can't be modified. This avoids the synchronization overhead.

public static void main(String[] args) {  
           Set set = Collections.synchronizedSet(new HashSet());  
           synchronized (set) {  
                Iterator itr = set.iterator();  
                while (itr.hasNext()) {  
                     System.out.println(itr.next());  
                }  
           }  
      }  

The iterator itself is not synchronized and iterating through a collection requires multiple calls back into the collection. If you don’t synchronize the getting and use of your iterator, your iteration through the collection will not be atomic and the underlying collection may change.

Enjoy Reading.


Collections class: Read-Only Collections


Read-Only Collections: When working with collection, there are times when you need or at least prefer an unmodifiable access to your collection instance. This may be because you are finished adding and removing elements from the collection but you still want to use it or you need to pass your collection to some method which you don’t necessarily know or you know the method but you don’t want them to change anything. To provide this capability, the Collections class provides six factory methods, one for each of Collection, List, Map, Set, SortedMap, and SortedSet.
         
  •       Collection unmodifiableCollection(Collection collection)
  •       List unmodifiableList(List list)
  •           Map unmodifiableMap(Map map)
  •       Set unmodifiableSet(Set set) 
  •             SortedMap unmodifiableSortedMap(SortedMap map)
  •       SortedSet unmodifiableSortedSet(SortedSet set)



Once you've filled the collection, replace the original reference with the read-only reference.If you don't replace the original reference, then the collection is not read-only, as you can still use the original reference to modify the collection. The following program demonstrates the proper way to make a collection read-only. In addition, it shows what happens when you try to modify a read-only collection.

 import java.util.Collections;  
 import java.util.HashSet;  
 import java.util.Set;  
 public class ReadOnlyCollectionExample {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           Set set = new HashSet();  
           set.add("Cat");  
           set.add("Dog");  
           set.add("Frog");  
           set.add("Elephant");  
           set = Collections.unmodifiableSet(set);  
           set.add("Lion");  
      }  
 }  

Output:-

Exception in thread "main" java.lang.UnsupportedOperationException  
      at java.util.Collections$UnmodifiableCollection.add(Unknown Source)  
      at ReadOnlyCollectionExample.main(ReadOnlyCollectionExample.java:22) 


When the program is run and the last add() operation is attempted on the read-only set, an UnsupportedOperationException is thrown.


Enjoy Reading



Difference between the '&' operator and '&&' operator ?


‘&&’ : - is a Logical AND operator produce a boolean value of true or false based on the logical relationship of its arguments.

For example: - Condition1 && Condition2

If Condition1 is false, then (Condition1 && Condition2) will always be false, that is the reason why this logical operator is also known as Short Circuit Operator because it does not evaluate another condition. If Condition1 is false , then there is no need to evaluate Condtiton2.

If Condition1 is true, then Condition2 is evaluated, if it is true then overall result will be true else it will be false.

public static void main(String[] args) {  
           int a = 12;  
           int b = 6;  
           if (a > 8 && b > 4) {  
                System.out.println("True");  
           } else {  
                System.out.println("False");  
           }  
      }  

Output:-
True because both the condition are true.

‘&’ : - is a Bitwise AND Operator. It produces a one (1) in the output if both the input bits are one. Otherwise it produces zero (0).

For example:-

int a=12; // binary representation of 12 is 1100
int b=6; // binary representation of 6 is 0110
int c=(a & b); // binary representation of (12 & 6) is 0100

The value of c is 4.


Enjoy Reading.


Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees



The rotation can be performed in layers, where you perform a cyclic swap on the edges on each layer. In the first for loop, we rotate the first layer (outermost edges). We rotate the edges by doing a four-way swap first on the corners, then on the element clockwise from the edges, then on the element three steps away.

Once the exterior elements are rotated, we then rotate the interior region’s edges.

Sample Program:-


 /**  
  * @author Dixit  
  *   
  */  
 public class RotateMatrix {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           int m[][] = { { 1, 2 ,3}, { 4, 5 ,6} ,{7,8,9}};  
           int n = 3;  
           for (int i = 0; i < n; i++)  
           {  
                for (int j = 0; j < n; j++) {  
                     System.out.print(m[i][j] + " ");  
                }  
                System.out.println("\n");  
           }  
           rotate(m, n);  
      }  
      public static void rotate(int[][] matrix, int n) {  
           for (int layer = 0; layer < n / 2; ++layer) {  
                int first = layer;  
                int last = n - 1 - layer;  
                for (int i = first; i < last; ++i) {  
                     int offset = i - first;  
                     int top = matrix[first][i]; // save top  
                     // left -> top  
                     matrix[first][i] = matrix[last - offset][first];  
                     // bottom -> left  
                     matrix[last - offset][first] = matrix[last][last - offset];  
                     // right -> bottom  
                     matrix[last][last - offset] = matrix[i][last];  
                     // top -> right  
                     matrix[i][last] = top; // right <- saved top  
                }  
           }  
           System.out.println("Resulting Matrix after 90 degree rotation \n");  
           for (int i = 0; i < n; i++)  
           {  
                for (int j = 0; j < n; j++) {  
                     System.out.print(matrix[i][j] + " ");  
                }  
                System.out.println("\n");  
           }  
      }  
 }  

Output:-


 1 2 3   
 4 5 6   
 7 8 9   
 Resulting Matrix after 90 degree rotation :  
 7 4 1   
 8 5 2   
 9 6 3   


Enjoy Programming.

Wednesday, 4 November 2015

What are Volatile Variables?


A Volatile variable is modified asynchronously by concurrently running threads in a Java application. It is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have its data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency.


When a field is declared volatile, the compiler and runtime  are  put on  notice  that  this  variable  is shared  and  that  operations  on  it  should  not  be  reordered  with  other memory operations.Volatile variables  are  not  cached  in  registers  or  in  caches  where  they  are  hidden  from  other processors, so a read of a volatile variable always returns the most recent write by any thread.


The most common use for volatile variables is as a completion, interruption, or status flag. Volatile variables can be used for other kinds of state information, but more care is required when attempting this. For example, the semantics of volatile are not strong enough to make the increment operation (count++) atomic, unless you can guarantee that the variable is written only from a single thread.

Note: Volatile variables can only guarantee visibility not atomicity.



Enjoy Reading.                                       

What is Transient Variable?


Transient variable :- In Java, a transient variable is one which would not be saved during serialization. This is mostly the case when a variable is sensitive enough that it should not be saved during serialization, such as a password. Even when such variable is private in the object, once it is serialized it is possible to read it inside a file or over a network. The keyword 'transient' is solution for such variables that are not required to be serialized.

Another way to prevent sensitive part of your object from being serialized is to implement your class as Externalizable. Then nothing is automatically serialized and you can explicitly serialize only the necessary parts inside writeExternal ( ) method.

If you are working with Serializable object , all serialization happens automatically. To control this, you can turn off serialization field-by-field basis using the transient keyword.


For example:- Consider a Login object that keeps information about a particular session .Suppose that, once you verify login , you want to store the data , but without the password .The easiest way to do this is by implementing Serializable and marking the password field as transient.

 import java.io.FileInputStream;  
 import java.io.FileNotFoundException;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.io.ObjectInputStream;  
 import java.io.ObjectOutputStream;  
 import java.io.Serializable;  
 import java.util.Date;  
 /**  
  * @author Dixit  
  *  
  */  
 public class Login implements Serializable{  
      private static final long serialVersionUID = 1L;  
      private Date date=new Date();  
      private String userName;  
      private transient String password;  
      Login(String userName,String password)  
      {  
           this.userName=userName;  
           this.password=password;  
      }  
      public String toString()  
      {  
           String pwd=(password==null) ? "(n/a)" : password;  
           return "login info : \n  "+"UserName: "+userName+  
                     "\n Date :"+date+  
                     "\n Password : "+pwd;  
      }  
      /**  
       * @param args  
       * @throws IOException   
       * @throws FileNotFoundException   
       * @throws ClassNotFoundException   
       */  
      public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {  
           Login login=new Login("Ashish", "magic");  
           System.out.println("login: "+login);  
           ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("Login.out"));  
           out.writeObject(login);  
           out.close();  
           try {  
                Thread.sleep(5000);  
           } catch (InterruptedException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
           ObjectInputStream in=new ObjectInputStream(new FileInputStream("Login.out"));  
           System.out.println("Recovering object at : "+new Date());  
           login=(Login) in.readObject();  
           System.out.println("login : "+ login );  
      }  
 }  


You can see that date and username are ordinary and are automatically serialized.However, the password is transient, and so is not stored to disk. also the serialization mechanism makes no attempt to recover it.


Ouput:

 login: login info :   
   UserName: Ashish  
  Date :Wed Nov 04 19:40:10 IST 2015  
  Password : magic  
 Recovering object at : Wed Nov 04 19:40:16 IST 2015  
 login : login info :   
   UserName: Ashish  
  Date :Wed Nov 04 19:40:10 IST 2015  
  Password : (n/a)  

When the object is recovered, the password field is null. Note that the toString ( ) method checks for a null value of password


Enjoy Reading

What is Java Virtual Machine(JVM)?


A Java Virtual Machine is a runtime environment required for execution of a Java application. Every Java application runs inside a runtime instance of some concrete implementation of abstract specifications of JVM. It is JVM which is 'platform independent'.

A runtime instance of the Java virtual machine has a clear mission in life: to run one Java application. When a Java application starts, a runtime instance is born. When the application completes, the instance dies. If you start three Java applications at the same time, on the same computer, using the same concrete implementation, you'll get three Java virtual machine instances. Each Java application runs inside its own Java virtual machine.


A Java virtual machine instance starts running its application by invoking the main() method of some initial class. The main() method must be public, static, return void, and accept one parameter: a String array. Any class with such a main() method can be used as the starting point for a Java application.

 public class SampleProgram {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           System.out.println("Hello World");  
      }       
 }  

The main() method of an application's initial class serves as the starting point for that application's initial thread. Inside the Java virtual machine, threads come in two flavours: daemon and non- daemon. A daemon thread is ordinarily a thread used by the virtual machine itself, such as a thread that performs garbage collection. The application, however, can mark any threads it creates as daemon threads. The initial thread of an application, the one that begins at main() is a non- daemon thread.

A Java application continues to execute (the virtual machine instance continues to live) as long as any non-daemon threads are still running. When all non-daemon threads of a Java application terminate, the virtual machine instance will exit. If permitted by the security manager, the application can also cause its own demise by invoking the exit() method of class Runtime or System.

In the SampleProgram application previous, the main() method doesn't invoke any other threads. After it prints out the command line arguments, main() returns. This terminates the application's only non-daemon thread, which causes the virtual machine instance to exit.


Happy Reading

Tuesday, 3 November 2015

How to work with Subsets of TreeSet



Since a TreeSet is ordered ,a subset of the tree set is also ordered. TreeSet class provides several methods for working with these subsets.The two subsets among them are headSet() and tailSet():

    public SortedSet headSet(Object toElement)  
    public SortedSet tailSet(Object toElement)  

The third method subSet() provides the endpoints:

    public SortedSet subSet(Object fromElement,Object toElement)  

All of these methods will give you a view into the underlying tree such that changes to that view are reflected in the set from which the view came from .In other words, if you remove something from the subset, it's gone. In addition, if you try to add something to the subtree, it must fit within your view of the tree. And if you add something to the original view, the subset will be altered too.

In headSet method, fromElement is not included as a part of resultant set whereas in case of tailSet,fromElement is included.

If you want to include the fromElement in the subset of headSet, you must do something like this

   SortedSet headSet = set.headSet(toElement+"\0");  

and if you don't want to include the fromElement in subset of tailSet:

   SortedSet tailSet = set.tailSet(fromElement+"\0");  

To get a set that includes both the ends, use:

   SortedSet set = set.subSet(fromElement,toElement+"\0");  

Or, for a set that includes neither end, use:

   SortedSet set = set.subSet(fromElement+"\0",toElement);  

Here are some few examples which will help to understand this better.
For example, you have a treeSet ("John","Mary","Dean","Sam","Lillith").as we know tree is ordered set.All the element will stored in sorted order.

  • tailSet("John") :- [John,Lillith,Mary,Sam]
  • headSet("John") :- [Dean]
  • headSet("John\0") :- [Dean,John]
  • tailSet("John\0") :- [Lillith,Mary,Sam]
  • subSet("John","Mary\0") :- [John,Lillith,Mary]
  • subSet("John","John\0") :- [John]
  • subSet("John","John") :- []


Enjoy Reading.