Saturday, 10 February 2018

Enum



Enums in java are mainly used for grouping similar kind of constants as a one unit. constants means static and final. Enums are introduced in JDK 1.5 onward. Before that similar kind of constants are grouped by declaring them as static and final in one class. Below example shows how the constants will look without enums.
class ConstantsWithoutEnums
{
 public static final String north = "NORTH";
 public static final String south = "SOUTH";
 public static final String east = "EAST";
 public static final String west = "WEST";
}

public class MainClass
{
 public static void main(String[] args)
 {
  System.out.println(ConstantsWithoutEnums.north);
  System.out.println(ConstantsWithoutEnums.south);
  System.out.println(ConstantsWithoutEnums.east);
  System.out.println(ConstantsWithoutEnums.west);
 }
}
Above constatnts can be defined with enums as below,
enum Directions
{
 NORTH, SOUTH, EAST, WEST;
}

public class EnumsExample
{
 public static void main(String[] args)
 {
  Directions d1 = Directions.EAST;
  System.out.println(d1);

  Directions d2 = Directions.NORTH;
  System.out.println(d2);

  System.out.println(Directions.SOUTH);

  System.out.println(Directions.WEST);
 }
}
Let’s see some things-to-remember about java enums.
  • Enums in java are declared with enum keyword and constants in enums must be valid java identifier. It is good practice to declare constants with UPPERCASE letters.
enum Days
{
 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
  • Duplicate enum constants are not allowed.
enum Directions
{
 NORTH, NORTH, SOUTH, EAST, WEST;  //Compile Time Error : Duplicate Constants
}
  • Every constant of enum is public, static and final by default. As every constant is static, they can be accessed directly using enum name.
enum enums
{
 A, B, C;
}

public class EnumsExample
{
 public static void main(String[] args)
 {
  enums en = enums.A;   //accessing constant A through enum name

  enums en1 = enums.B;  //accessing constant B through enum name

  enums en2 = enums.C;  //accessing constant C through enum name
 }
}
  • Enums can have any number of fields. methods and constructors and Each constant will have their own copy of fields and methods.
enum enums
{
 A, B, C;

 int i;  //enums can have fields

 private enums()
 {
  //enums can have Constructor
 }

 void methodOfEnum()
 {
  //enums can have methods
 }
}

public class EnumsExample
{
 public static void main(String[] args)
 {
  enums en = enums.A;
  System.out.println(en.i);  //Constant A has field i
  en.methodOfEnum();         //Constant A has methodOfEnum()

  enums en1 = enums.B;
  System.out.println(en1.i);  //Constant B has field i
  en1.methodOfEnum();         //Constant B has methodOfEnum()

  enums en2 = enums.C;
  System.out.println(en2.i);   //Constant C has field i
  en2.methodOfEnum();          //Constant C has methodOfEnum()
 }
}
  • If enum has only constants, then semicolon (;) at the end of constant declaration is not mandatory. But, if enum has other members, then semicolon is mandatory.
enum enums
{
 A, B, C, D     //semicolon at the end of this statement is not mandatory
}

enum enums
{
 A, B, C;    //semocolon at the end of this statement is mandatory, because it has other members

 int i;  //enums has a field

 void methodOfEnum()
 {
  //enums has a method
 }
}
  • Every enum in java extends java.lang.Enum class. Enum class is an abstract class in java.lang package. As every enum extends Enum class, it should not extend any other class. Because, Multiple inheritance is not allowed in java. But enums can implement any number of interfaces.
interface AnyInterface
{
 abstract void methodOfInterface();
}

enum enums implements AnyInterface
{
 A, B, C;

 @Override
 public void methodOfInterface()
 {
  //MethodOfInterface is implemented
 }
}
  • Enums can be declared inside a class. If declared inside a class, they are static by default and can be accessed directly by Class name.
class ClassContainingEnum
{
 enum enums
 {
  A, B, C
 }
}

public class MainClass
{
 public static void main(String[] args)
 {
  System.out.println(ClassContainingEnum.enums.A);  //Accessing enums directly using class name
 }
}
  • Enum constants can override generalized method defined in the enum body.
enum enums
{
 FIRST
 {
  @Override
  void commonMethod()
  {
   System.out.println("Common method Overridden in FIRST");
  }
 },

 SECOND
 {
  @Override
  void commonMethod()
  {
   System.out.println("Common method Overridden in SECOND");
  }
 },

 THIRD
 {
  @Override
  void commonMethod()
  {
   System.out.println("Common method Overridden in THIRD");
  }
 };

 void commonMethod()
 {
  System.out.println("Generalized method, Common to all constants");
 }
}

public class EnumsExample
{
 public static void main(String[] args)
 {
  enums.FIRST.commonMethod();     //Output : Common method Overridden in FIRST

  enums.SECOND.commonMethod();    //Output : Common method Overridden in SECOND

  enums.THIRD.commonMethod();     //Output : Common method Overridden in THIRD
 }
}
  • Enum can have abstract method declared in it’s body provided each enum constants must implement it.
enum enums
{
 FIRST
 {
  @Override
  void abstractMethod()
  {
   //Abstract Method Implemented
  }
 },

 SECOND
 {
  @Override
  void abstractMethod()
  {
   //Abstract Method Implemented
  }
 },

 THIRD
 {
  @Override
  void abstractMethod()
  {
   //Abstract Method Implemented
  }
 };

 abstract void abstractMethod();
}
  • Enum Constants can have their own fields and method defined in their body, but these fields and methods are visible only within the constant body.
enum enums
{
 FIRST
 {
  int j = 10;   // Field of FIRST

  void methodOfFirst()
  {
   System.out.println(j);  //Field j can be used within the constant body
  }

  @Override
  void abstractMethod()
  {
   methodOfFirst();     //methodOfFirst() can be used within the constant body
  }
 },

 SECOND
 {
  int k = 20;   //Field of SECOND

  void methodOfSecond()
  {
   System.out.println(k);  //Field k can be used within the constant body
  }

  @Override
  void abstractMethod()
  {
   methodOfSecond();     //methodOfSecond() can be used within the constant body
  }
 };

 int i;   //this field is available in all constants

 abstract void abstractMethod();  //this method is available in all constants
}

public class EnumsExample
{
 public static void main(String[] args)
 {
  System.out.println(enums.FIRST.j);   //Compile time error : Field j is not visible here

  enums.FIRST.methodOfFirst();  //Compile time error : methodOfFirst() is not visible here

  enums.FIRST.abstractMethod();

  System.out.println(enums.SECOND.k);   //Compile time error : Field k is not visible here

  enums.SECOND.methodOfSecond();  //Compile time error : methodOfSecond() is not visible here

  enums.SECOND.abstractMethod();
 }
}
  • After observing all the above features of enums, we come to know that enums can have constuctors, fields and methods. Enums can implement interface. Enums extend Enum class. That means they have all features of classes. Therefore they are special type of classes. Moreover, after compilation, .class files are generated for all enums. Then what enum constants are?….  You can treat them as static inner classes of enums as they can be referred directly using enum name and they can hold fields and methods in them.

Friday, 9 February 2018

Memory : Constant Pool







Constant pool is a part of .class file (and its in-memory representation) that contains constants needed to run the code of that class.
These constants include literals specified by the programmer and symbolic references generated by compiler. Symbolic references are basically names of classes, methods and fields referenced from the code. These references are used by the JVM to link your code to other classes it depends on.
For example, the following code
System.out.println("Hello, world!");
produces the following bytecode (javap output)
0:   getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;              
3:   ldc     #3; //String Hello, world!                                                  
5:   invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
#n here are references to the constant pool. #2 is a symbolic reference to System.out field, #3 is a Hello, world! string and #4 is a symbolic reference to PrintStream.println(String) method.
As you can see, symbolic references are not just names - for example, symbolic reference to the method also contains information about its parameters (Ljava/lang/String;) and return type (Vmeans void).
You can inspect constant pool of a class by running javap -verbose for that class.

Monday, 7 August 2017

SORTED SET



package java_topic.collection;

import java.util.SortedSet;
import java.util.TreeSet;

/**
 * Created by Akash on 8/7/2017.
 */
public class SortedSetClass {

   
public static void main(String[] args)
    {
        SortedSet sortedSet1 =
new TreeSet();

        sortedSet1.add(
1);
        sortedSet1.add(
2);
        sortedSet1.add(
3);
        sortedSet1.add(
4);
        sortedSet1.add(
5);
        sortedSet1.add(
6);
        sortedSet1.add(
7);
        sortedSet1.add(
8);
        sortedSet1.add(
9);
        sortedSet1.add(
10);

        System.
out.println("Full SortedSet : "+sortedSet1);

        System.
out.println("first() SortedSet : "+sortedSet1.first());

        System.
out.println("last() SortedSet : "+sortedSet1.last());

        System.
out.println("headset(Object fromElement) SortedSet : "+sortedSet1.headSet(4));

        System.
out.println("subset(Object fromElement, Object toElement) SortedSet : "+sortedSet1.subSet(3, 7));

        System.
out.println("tailSet(Object toElement) SortedSet : "+ sortedSet1.tailSet(6));

    }
}

************************************************************************
OUTPUT

Full SortedSet : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
first() SortedSet : 1
last() SortedSet : 10
headset(Object fromElement) SortedSet : [1, 2, 3]
subset(Object fromElement, Object toElement) SortedSet : [3, 4, 5, 6]

tailSet(Object toElement) SortedSet : [6, 7, 8, 9, 10]

Friday, 17 February 2017

Inner & Nested Class : LocalInnerClassWithVar



public class LocalInnerClassWithVar {

    int val = 50;    public void display()
    {
        int val = 100;        class Local{
            void msg()
            { System.out.println( "Hi, This is local inner class value : "+val );}
        }

        Local l = new Local();        l.msg();    }

    public static void main(String[] args)
    {
        LocalInnerClassWithVar localInnerClass = new LocalInnerClassWithVar();        localInnerClass.display();    }
}

Inner & Nested Class : NestedInterfaceWithinClass





class ABC
{
    interface XYZ{
        void msg();    }

}
public class NestedInterfaceWithinClass implements ABC.XYZ{

    @Override    public void msg()
    {
        System.out.println( "Hi, This is nested interface within class." );    }
    public static void main(String[] args)
    {
        ABC.XYZ nestedInterface1 = new NestedInterfaceWithinClass();        nestedInterface1.msg();    }
}

Inner & Nested Class : NestedInterface


interface D
{
    interface E{
     public void msg();    }

}
public class NestedInterface implements D.E{

    @Override    public void msg()
    {
        System.out.println( "Hi, This is nested interface." );    }
    public static void main(String[] args)
    {
        NestedInterface nestedInterface = new NestedInterface();        nestedInterface.msg();    }
}

Inner & Nested Class : StaticInnerClassWithStaticMethod




public class StaticInnerClassWithStaticMethod {

    static class InnerClass2
    {
        static void dispData1()
        {
            System.out.println( "Hi, This is static inner class with static method" );        }
    }
    public static void main(String[] args)
    {

        StaticInnerClassWithStaticMethod.InnerClass2 innerClass = new StaticInnerClassWithStaticMethod.InnerClass2();        innerClass.dispData1();        // OR, CAN CALL LIKE BELOW        StaticInnerClassWithStaticMethod.InnerClass2.dispData1();    }
}