Wednesday, 2 October 2013

Tricky Examples 1

1. Assignment operator always returns the value which is assigned. Here I am giving some examples.
public class Test
{
    public static void main(String[] args) 
    {
    boolean a = true;
    float b = 0.0f;
    double c = 0.0;
    int d = 0;
   
    if(a = false)
    {
    System.out.print("\nThis is will not executed");
    }//if
    else
    {
    System.out.print("\nThis is false : " + (a = false));
    }//else
   
    if(a = true)
    {
    System.out.print("\nThis is will executed now because (a = true) = " + (a = true));
    }//if
    else
    {
    System.out.print("\nThis is will not executed");
    }//else
    /* In java if(condition) statement will always need boolean value
    * so following all code will fail to compile
    * if(b = 2.3)
    * if(c = 4.3)
    * if(d = 3)
    * Lets see what will be return value for these
    */
    System.out.print("\n(b = 2.3) = " + (b = 2.3f));
    System.out.print("\n(c = 4.3) = " + (c = 4.3));
    System.out.print("\n(d = 3) = " + (d = 3));
    }//PSVM
}//class Test

2. For down cast you will need explicit casting.
public class Test
{
    public static void main(String [] args) 
    {
    byte b = 10;
    short s = 20;
    int i = 30;
    float f = 40f;
    double d = 50;
    // Here are few valid assignments
    d = f;
    f = i;
    i = s;
    s = b;
    //Here are few invalid assignments
    b = s;
    s = i;
    i = f;
    f = d;
    //To make this working you have to cast explicitly
    b = (byte)s;
    s = (short)i;
    i = (int)f;
    f = (float)d;
    }//PSVM
}//class Test

3. Only byte, short, int, char, String and enum is allowed in switch case. Here I am giving example.
public class Test 
{
    public static void main(String args[]) 
    { 
    String f ="0";
    switch (f) 
    {
    }
    int f1 = 0;
    switch (f1/2) 
    {
    }
    byte f2 = 0;
    switch (f2 + 3) 
    {
    }
    short f3 = 0;
    switch (f3) 
    {
    }
    char f4 = '0';
    switch (f4) 
    {
    }
    /*
    It will fail for float, double, long    
    float f4 = 2.3f;
    switch(f4)
    {
    }
    */
    } 
}

Sunday, 29 September 2013

Printing triangle pattern in java

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main 
{
public static void main(String args[])
{
int n = 0;
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter the number of rows : ");
n = Integer.parseInt(br.readLine());

for(int i = 0; i < n; i++)
{
for(int j= 0; j < (n-i); j++)
{
System.out.print(" ");
}//for j
for(int j = 0; j <= i; j++)
{
System.out.print("* ");
}//for j
System.out.print("\n");
}//for i

for(int i = 0; i < n; i++)
{
for(int j = 0; j <= i; j++)
{
System.out.print(" ");
}//for j
for(int j= 0; j < (n-i); j++)
{
System.out.print("* ");
}//for j
System.out.print("\n");
}//for i

}//try
catch(Exception e)
{
System.out.print("\nException : " + e);
}//catch
}//PSVM
}//class Main

Output:-
Enter number of rows : 5
     * 
    * * 
   * * * 
  * * * * 
 * * * * * 

Printing diamond pattern in java

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main 
{
public static void main(String args[])
{
int n = 0;
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter the number of rows : ");
n = Integer.parseInt(br.readLine());

for(int i = 0; i < n; i++)
{
for(int j= 0; j < (n-i); j++)
{
System.out.print(" ");
}
for(int j = 0; j <= i; j++)
{
System.out.print("* ");
}
System.out.print("\n");
}//for i

for(int i = 0; i < n; i++)
{
for(int j = 0; j <= i; j++)
{
System.out.print(" ");
}
for(int j= 0; j < (n-i); j++)
{
System.out.print("* ");
}
System.out.print("\n");
}//for i

}
catch(Exception e)
{

}
}
}

Output :-
     *
    * *
   * * *
  * * * *
 * * * * *
 * * * * *
  * * * *
   * * *
    * *
     *

Monday, 15 July 2013

Windows 7 Shortcuts

Here I am giving few windows 7 useful shortcuts,

1. You pin your favorite application to your task-bar say edit-plus (Assume that this is your first application task-bar). Now you can access that application with keyboard shortcut Win + 1. In this way you can access 10 applications with Win + 2, Win + 3,....,Win + 10.

2. You have any one window open now if you want to adjust that window to half left of your computer screen then you can use Win + Left or Right Arrow. If you want to adjust this windows to right half of your screen, you can keep pressing Win + Left or Right Arrow.

3. If you want to restore down your active window then press Win + Down Arrow. If you want to maximize your active window then press Win + Up Arrow key.

4. If you want to browse through your folder hierarchy then use Alt + Arrow keys. This will work with your windows explorer. Here you can use Up, Left or Right arrow keys

5. Win + Alt + N will allow you to access jump list of Nth pinned application on your task-bar. Here N = 1, 2, ...,9 means number keys.

6. You can create shortcut for your favorite application for launching that application. Right click on your favorite application icon => Go to properties => shortcuts. Now click on shortcut field and press shortcut that you want. Ex. Alt + A.

7. Very useful is opening command prompt for particular folder. If you are in some folder say C:\a\b\c\d and now you want to open command prompt at this folder then press "Shift key + Right click" in your folder and you will get "open command window here" option. You click this option and you will get command prompt for that folder.

8. You know that after pressing Shift key five times opens Sticky key dialog box. If you want to avoid that follow the link in the same dialog box and here you can disable this feature.

Tuesday, 21 May 2013

Flyweight Pattern Example - JAVA


Flyweight pattern is mainly used to reuse objects. This one of the structural pattern. We can understand this pattern by following example. Here we are using bikes with different type, color and cc.

1. Create interface as given below.
public interface Bike {
Bike getBike(String type);
void setColor(String color);
void setCc(int cc);
String getDetails();
}//Bike 

2. Create class HondaBike as given below.
public class HondaBike implements Bike {
private int cc;
private String color, type;

public HondaBike(String type) {
this.type = type;
}//HondaBike

public Bike getBike(String type) {
return new HondaBike(type);
}//getBike

public void setColor(String color) {
this.color = color;
}//setColor

public void setCc(int cc) {
this.cc = cc;
}//setCc

public String getDetails() {
return "\nColor : " + color + "\tCC : " + cc + "\tType : " + type;
}//getDetails
}//class HondaBike

3. Create BikeGenerator as given below.
import java.util.HashMap;

public class BikeGenerator {
private HashMap<String, Bike> bikeStore = new HashMap<>();
public Bike getBike(String type) {
Bike bike = (Bike) bikeStore.get(type);

if(bike == null) {
bikeStore.put(type, new HondaBike(type));
System.out.print("\nGenerating new bike object with type : " + type);
}//if
else {
System.out.print("\nReturning existing object.");
}//else
return (Bike)bikeStore.get(type);
}//getBike
}//BikeGenerator

4. Now we can create our main class as given below.
public class Main {
public static void main(String args[]) {
BikeGenerator bg = new BikeGenerator();

Bike hondaSimple = bg.getBike("simple");
hondaSimple.setColor("Red");
hondaSimple.setCc(100);
System.out.print("\n" + hondaSimple.getDetails());

Bike hondaDelux = bg.getBike("delux");
hondaDelux.setColor("Red");
hondaDelux.setCc(150);
System.out.print("\n" + hondaDelux.getDetails());

Bike  hondaGold = bg.getBike("gold");
hondaGold.setColor("Red");
hondaGold.setCc(350);
System.out.print("\n" + hondaGold.getDetails());

Bike hondaAgainSimple = bg.getBike("simple");
hondaAgainSimple.setColor("Black");
hondaAgainSimple.setCc(350);
System.out.print("\n" + hondaAgainSimple.getDetails());

}//PSVM
}//Main

And now you are ready to run example. Output will explain you waht we have achieved.

Monday, 20 May 2013

Facade Pattern Example


Facade pattern is one of the structural pattern which is used to hide internal complexity. Here I am giving one example of color filling. You can use following steps to get working example of facede pattern.

1. First create Color interface.
public interface Color {
void fillColor();
}//Color

2. Now create class Redcolor
public class RedColor implements Color {
public void fillColor() {
System.out.print("\nFilling red color");
}//fillColor
}//RedColor

3.Now create class BlueColor
public class BlueColor implements Color {
public void fillColor() {
System.out.print("\nFilling blue color");
}//fillColor
}//BlueColor

4. Now create class GreenColor
public class GreenColor implements Color {
public void fillColor() {
System.out.print("\nFilling green color");
}//fillColor
}//GreenColor

5. Here we go for creating ColorFiller class which is going to hide complexity.
public class ColorFiller {
private Color redColor;
private Color blueColor;
private Color greenColor;

public ColorFiller() {
redColor = new RedColor();
blueColor = new BlueColor();
greenColor = new GreenColor();
}//ColorFiller

public void fillRedColor() {
redColor.fillColor();
}//fillRedColor

public void fillBlueColor() {
blueColor.fillColor();
}//fillBlueColor

public void fillGreenColor() {
greenColor.fillColor();
}//fillGreenColor
}//CollerFiller

6. Here Main class where we have to use this pattern.
public class Main {
public static void main(String args[]) {
ColorFiller cf = new ColorFiller();
cf.fillRedColor();
cf.fillBlueColor();
cf.fillGreenColor();
}//PSVM
}//Main

Sunday, 19 May 2013

Composit Pattern Example

Composit design pattern is one of the structural pattern. You can use this pattern for maintaining hierarchy of objects. Here I am going to explain example with college staff hierarchy. You can follo steps to get working example.

1. Create StaffMember class as given below. Here remember that composit pattern class will always have list of objects of its own type.
import java.util.ArrayList;
import java.util.List;

public class StaffMember {
    private int ID;
    private String name, desg;
    public List<StaffMember> subMember;
   
    public StaffMember(int ID, String name, String desg) {
        this.ID = ID;
        this.name = name;
        this.desg = desg;
        subMember = new ArrayList<StaffMember>();
    }//StaffMember
   
    public void addSubMember(StaffMember staffMember) {
        subMember.add(staffMember);
    }//addSubMember
   
    public List<StaffMember> getSubMember(StaffMember staffMember) {
        return subMember;
    }//getSubMember
   
    public String toString() {
        return "\nID : " + ID + "\tName : " + name + "\tDesg : " + desg;
    }//toString
   
}//class StaffMember

2. Now create Main class for demo as given below.
import java.util.List;

public class Main {
    public static void main(String args[]) {
        StaffMember headMaster = new StaffMember(1, "A", "HeadMaster");
        StaffMember subHeadMaster = new StaffMember(2, "B", "Sub-HeadMaster");
        StaffMember supervisor1 = new StaffMember(3, "C", "Supervisor-1");
        StaffMember supervisor2 = new StaffMember(4, "D", "Supervisor-2");
        StaffMember teacher1 = new StaffMember(5, "E", "Teacher-1");
        StaffMember teacher2 = new StaffMember(6, "F", "Teacher-2");
        StaffMember teacher3 = new StaffMember(7, "G", "Teacher-3");
        StaffMember teacher4 = new StaffMember(8, "H", "Teacher-4");
        headMaster.addSubMember(subHeadMaster);
        subHeadMaster.addSubMember(supervisor1);
        subHeadMaster.addSubMember(supervisor2);
        supervisor1.addSubMember(teacher1);
        supervisor1.addSubMember(teacher2);
        supervisor2.addSubMember(teacher3);
        supervisor2.addSubMember(teacher4);
       
        System.out.print("\nHead master hierarchy : ");
        printHierarchy(headMaster);
        System.out.print("\n=========================================");
        System.out.print("\nSub head master hierarchy : ");
        printHierarchy(subHeadMaster);
        System.out.print("\n=========================================");
        System.out.print("\nSupervisor 1 hierarchy : ");
        printHierarchy(supervisor1);
        System.out.print("\n=========================================");
        System.out.print("\nSupervisor 2 hierarchy : ");
        printHierarchy(supervisor2);
       
    }//PSVM
   
    public static void printHierarchy(StaffMember staffMember) {
        System.out.print(staffMember.toString());
        List<StaffMember> member = staffMember.getSubMember(staffMember);
        for(int i = 0; i < member.size(); i++) {
            printHierarchy(member.get(i));
        }//for i
    }//printHierarchy
   
}//class Main

Now you modify StaffMember class for additional information like you can store parent of that object. You can put some checks when adding member. You can add method for removing member from hierarchy.

Friday, 17 May 2013

Filter Pattern Example - JAVA


Filter pattern is mainly used to filter group of objects based on some criteria  We can see one simple example of this filter pattern. Here we are going to filter laptops based on company and OS. Use following steps to build example.
1. Create class Laptops as given below.
public class Laptops {
String company, os;
int bits;
public Laptops(String company, String os, int bits) {
this.company = company;
this.os = os;
this.bits = bits;
}//Laptops
public String getCompany() { return company; }
public String getOs() { return os; }
public int getBits() { return bits; }
}//class Laptops

2. Create interface Filter as given below.
import java.util.List;
public interface Filter {
List<Laptops> filterObjects(List<Laptops> laptops);
}

3. Create class HclFilter as given below.
import java.util.ArrayList;
import java.util.List;
public class HclFilter implements Filter {
public List<Laptops> filterObjects(List<Laptops> laptops) {
List<Laptops> hclLaptops = new ArrayList<>();
for(int i = 0; i < laptops.size(); i++)
if(laptops.get(i).getCompany().equalsIgnoreCase("hcl"))
hclLaptops.add(laptops.get(i));
return hclLaptops;
}//filterObjects
}//HclFilter

4. Create class WindowsOsFilter as given below.
import java.util.ArrayList;
import java.util.List;
public class WindowsOsFilter implements Filter {
public List<Laptops> filterObjects(List<Laptops> laptops) {
List<Laptops> windowsOsLaptops = new ArrayList<>();
for(int i = 0; i < laptops.size(); i++)
if(laptops.get(i).getOs().equalsIgnoreCase("windows"))
windowsOsLaptops.add(laptops.get(i));
return windowsOsLaptops;
}//filterObjects
}//WindowsOsFilter

5. And now our demo class for filter pattern.
import java.util.ArrayList;
import java.util.List;
public class FilterDemo {
public static void main(String args[]) {
List<Laptops> allLaptops = new ArrayList<Laptops>();
allLaptops.add(new Laptops("hcl", "windows", 32)); allLaptops.add(new Laptops("hcl", "linux", 32));
allLaptops.add(new Laptops("hcl", "solaries", 64)); allLaptops.add(new Laptops("dell", "windows", 32));
allLaptops.add(new Laptops("dell", "linux", 32)); allLaptops.add(new Laptops("dell", "solaries", 64));
Filter hclLaptops = new HclFilter();
Filter windowsOsLaptops = new WindowsOsFilter();
List<Laptops> filteredLaptops = hclLaptops.filterObjects(allLaptops);
System.out.print("\nAll HCL laptops : ");
for(int i = 0; i < filteredLaptops.size(); i++)
System.out.print("\nCompany : " + filteredLaptops.get(i).getCompany() + "\tOs : " + filteredLaptops.get(i).getOs());
filteredLaptops = null;
filteredLaptops = windowsOsLaptops.filterObjects(allLaptops);
System.out.print("\nAll windows os laptops : ");
for(int i = 0; i < filteredLaptops.size(); i++)
System.out.print("\nCompany : " + filteredLaptops.get(i).getCompany() + "\tOs : " + filteredLaptops.get(i).getOs());
}//PSVM
}//class FilterDemo

You can add more filters and can add "AND" & "OR" filters as well.

Thursday, 16 May 2013

Adapter pattern example


Adapter pattern is one of the structural pattern which makes two incompatible interfaces to work together. Idea can be more clear with example. For implementing adapter pattern you can follow given steps.

Here example is of ColorProvider class. This ColorProvider class implements interface called BasicColors which can provide only red, green and blue colours. There is another interface called AdvancedColors whic provides yellow, pink, white and black colors. In this case adapter pattern will make BasicColors and AdvancedColors to work together without any changes in interface of ColorProvider class.

1. Create interface BasicColors as given below.
public interface BasicColors {
void getColor(String color);
}

2. Create interface AdvancedColors as given below.
public interface AdvancedColors {
void getColor();
}

3. Now we can create class ColorProvider which will be used by user.
public class ColorProvider implements BasicColors {
ColorAdapter colorAdapter;
public void getColor(String color) {
if(color.equalsIgnoreCase("red") || color.equalsIgnoreCase("green") || color.equalsIgnoreCase("blue")) {
System.out.print("\nBasic colour " + color + " by BasicColor interface.");
}//if
else {
colorAdapter = new ColorAdapter();
colorAdapter.getColor(color);
}//else
}//getColor
}//class ColorProvider

4. Here we go for ColorAdapter as given below.
public class ColorAdapter implements BasicColors {
AdvancedColors advColor;

public void getColor(String color) {
if(color.equalsIgnoreCase("yellow")) {
advColor = new Yellow();
advColor.getColor();
}//if
else if(color.equalsIgnoreCase("pink")) {
advColor = new Pink();
advColor.getColor();
}//else if
else if(color.equalsIgnoreCase("black")) {
advColor = new Black();
advColor.getColor();
}//else if
else if(color.equalsIgnoreCase("white")) {
advColor = new White();
advColor.getColor();
}//else if
}//getColor
}//class ColorAdapter

5. Now we can implement concreet classes of advanced colors as given below.
public class Yellow implements AdvancedColors {
public void getColor() {
System.out.print("\nAdvanced yellow color.");
}
}

public class Pink implements AdvancedColors {
public void getColor() {
System.out.print("\nAdvanced pink color.");
}
}

public class Black implements AdvancedColors {
public void getColor() {
System.out.print("\nAdvanced black color.");
}
}

public class White implements AdvancedColors {
public void getColor() {
System.out.print("\nAdvanced white color.");
}
}

6. Here we go for demo i.e. for Main class.
public class Main {
public static void main(String args[]) {
ColorProvider cp = new ColorProvider();
cp.getColor("red");
cp.getColor("yellow");
cp.getColor("green");
cp.getColor("pink");
}
}

You can draw UML diagram for better understanding.

Tuesday, 14 May 2013

Factory Design Pattern Example


Factory pattern is creational pattern which hides object creation logic from user. We can see one example of factory patter for clear understanding. To execute your factory pattern use following steps:-

1. Create interface called Car as given below. It will be common reference to all Car objects that we are going to create.
public interface Car {
void myCar();
}

2. Now create one concreet class called Bmw. This class will be implementing interface Car.
public class Bmw implements Car {
public void myCar() {
System.out.print("\nBmw is my car.");
}
}


3. Now create another concreet class called Tata. This class will be implementing interface Car.
public class Tata implements Car {
public void myCar() {
System.out.print("\nTata is my car.");
}
}


4. Now create one more class called Maruti. Thisclass will be implementing interface Car.
public class Maruti implements Car {
public void myCar() {
System.out.print("\nMaruti is my car.");
}
}

5. Now you have to create one more class called CarFactory as given below. 
public class CarFactory {
public Car getCar(String carName) {
if(carName.equalsIgnoreCase("Tata"))
return new Tata();
else if(carName.equalsIgnoreCase("Maruti"))
return new Maruti();
else if(carName.equalsIgnoreCase("Bmw"))
return new Bmw();
return null;
}
}


6. Now our pattern is ready. Let's write one class to implement this pattern.
public class CarShop {
public static void main(String args[]) {
CarFactory cf = new CarFactory();
Car c1 = cf.getCar("Tata");
c1.myCar();

c1 = cf.getCar("Maruti");
c1.myCar();
}
}

Here you are ready to execute your application.

Now you can see that if you want to add one more car to shop you just need to add one more class implementing Car interface and you are done. In this was this pattern provides flexibility and hides creational logic from user.

Monday, 13 May 2013

Thread class - JAVA


Thread class is present in java.lang package. This class implements Runnable interface. This class allows user to create multiple threads in application. These threads can execute code in concurrent way. Every thread 
is having some priority between 1 to 10. By default it set to 5. Every thead can create another thread. The priority of newly created thread is same as that of parent thread, but you can change this mannually. Thread 
can be daemon thread so new thread created by daemon will be daemon thread. 
We can create thread by extendding class Thread or by implementing Runnable interface. Best way is to implement Runnable interface because it will allow your class to extend another class so it will be flexible 
architecture.
Here is example by extending thread class,

class ThreadClass extends Thread {
public void run() {
try {
System.out.println("In run : 1");
Thread.sleep(2000);
System.out.println("In run : 2");
} catch(Exception e) { 
System.out.print("Exception : " + e);
}
}
public static void main(String args[]) {
ThreadClass tc = new ThreadClass();
tc.start();
}
}


And here is example by implementing runnable interface,

class ThreadClass implements Runnable {
private Thread th;
public ThreadClass() {
th= new Thread(this);
th.start();
}
public void run() {
try {
System.out.println("In run : 1");
Thread.sleep(2000);
System.out.println("In run : 2");
} catch(Exception e) { 
System.out.print("Exception : " + e);
}
}
public static void main(String args[]) {
ThreadClass tc = new ThreadClass();
}
}


Here you can see that class extending Thread class is not having any chance to extends any class but class implementing Runnable is having that chance.

Thread class is having many constructors like given below,
Thread();
Thread(String name);
Thread(ThreadGroup group, String name);
Thread(Runnable target, String name);
Thread(ThreadGroup group, Runnable target, String name);
Thread(ThreadGroup group, Runnable target, String name, long stackSize);
Every constructor internally calls init method of Thread class which is described below.

Thread class gives start() method which is synchronised by nature and you can't restart any thread which has completed its execution or you can't call start() method more than onse on same thread otherwise it will throw
IllegalThreadStateException. This start method calls another start0() native method. 

stop() method stops the execution of thread. In this method SecurityManager comes into picture. For stoping thread help of ThreadDeath class which is subclass of Error class is taken.

Thread.currentThread() method returns reference to current thread. Onse you are getting reference to current thread you can perform different operations on it.

Thread.sleep(timeInMilliSec) This method makes thread to sleep for given time.

Thread.sleep(milliSec, nanoSec) This makes thread to sleep for given milli seconds and nano seconds.

Thread.init(group, target, name, stackSize); This method initializes thread where group is the thread group, target is the target object whose run method we have to execute, name of thread an stack size for thread.
Other properties like priority, daemon or not will be copied from parent thread or you can set then mannually.

Thread.yield() method makes current thread to pause temporarly and allows other threads to run.

interrupt() method interrupts thread. This methos calls interrupt0() native method internally.

isInterrupted() method tells you whether given thread is interrupted or not.

isAlive() method returns boolean value stating whether thread is alive or not.

setPriority() method sets priority of thread. This priority can be between 1 to 10 where 1 is lower priority and 10 is higher priority.

activeCount() returns number of active threads in current thread group.

join(), join(milliSec), join(milliSec, nanoSec) waits for thread to die.

setDaemon(boolean), isDaemon() are methods related with daemon threads.

Along with these methods Thread class gives other methods like suspend(), resume() etc.

Enumerations - JAVA


We can make use of enumerations, when we need some constant values. Example is in coffee shop we may have only three types of coffee mugs like small, medium and large. In such a situation enumeration will reduce the possibility of errors. Let's see how to use enumerations in our code.

There are some rules that you have to follow while using enumerations.
1. Enumerations can be defined outside of class but with public access modifier only (It may be without access modifier i.e. default access).
2. You can define enumerations inside class with public, private, protected and static modifires only. 
3. You can't define enumerations in methods.
Now let's see example of this,

enum Outer {
SMALL, MID, LARGE
}//enum Size
class MainClass {
enum Inner {
SMALL, MID, LARGE
}//enum Size

public static void main(String args[]) {
System.out.print("\nOuter enum : " + Outer.LARGE + "\nInner enum : " + Inner.LARGE);
}//PSVM
}//MainClass

Now we can continue looking more features of enumerations,
4. You can place constructors in enum class and can overload those constructors.
5. You can have variables in enum class.
6. You can have getter and setter methods in enum class
Let's see example of this,
enum Outer{
SMALL(8), MID(10), LARGE(15);
private int value;
private Outer(int value) {
this.value = value;
}//Outer
public int getValue() {
return value;
}
}//enum Outer

class MainClass {
enum Inner {
SMALL, MID, LARGE
}//enum Size

public static void main(String args[]) {
System.out.print("\nOuter enum : " + Outer.LARGE.getValue() + "\nInner enum : " + Inner.LARGE);
}//PSVM
}//MainClass

Another important thing is that you can't place enums in static block. They can be placed only in top level class, interface or outside of everything i.e. as independent  But you can place enum in static inner class. Here is example of that,
class MainClass {
static class InnerClass {
enum Inner
{
SMALL, MID, LARGE
}//enum Size
}

public static void main(String args[]) {
System.out.print("\nInner enum : " + InnerClass.Inner.LARGE);
}//PSVM
}//MainClass
Even following peace of code is valid,
interface OuterInterface {
enum OuterEnum {
SMALL
}//OuterEnum
static interface InnerInterface {
enum InnerEnum {
SMALL
}//InnerEnum
}//InnerInterface
}//OuterInterface
You can explore this with all combinations.