0

I am trying to learn enum in java, i wrote a code to understand the use of valueOf & values, i understood my mistake as the valueOf is case sensitive, so exception was thrown.

But i was surprised to see that output was not in order as i expected, as per my understanding this can only happen when more than one thread is involved, Bur here only one main thread is running. here is my program:

public enum Currency {
PENNY(1) {
        @Override
        public String color() {
            return "bronze";
        }
    }, 



    NICKLE(5) {
        @Override
        public String color() {
            return "bronze";
        }
    }, DIME(10) {
        @Override
        public String color() {
            return "silver";
        }
    }, QUARTER(25) {
        @Override
        public String color() {
            return "silver";
        }
    };
    private int value;

    public abstract String color();

    private Currency(int value) {
        this.value = value;
    }  


    public static void main(String[] args) {


        for(Currency i: Currency.values()){
            System.out.println(i.toString());

        }

        System.out.println(Currency.valueOf("penny"));

    }
}

and this is the output i got:

Exception in thread "main" java.lang.IllegalArgumentException: No enum const class learn.enumeration.Currency.penny
    at java.lang.Enum.valueOf(Unknown Source)
    at learn.enumeration.Currency.valueOf(Currency.java:1)
    at learn.enumeration.Currency.main(Currency.java:54)
PENNY
NICKLE
DIME
QUARTER

According to me first for-each loop should be executed and then this exception should appear.When i tried it executing again, i get this result also... it gave me hint of two thread involvement in this scenario... But where did i create the another thread?? Thanks in Advance

awksp
  • 11,764
  • 4
  • 37
  • 44
  • I ran this code multiple times and always got expected result, i.e. list of coins and the exception. What platform/JVM you're running this on? PS. overriding `color` for every enum value is quite redundant here, why don't you just pass the color as an argument of constructor? – Crozin Jun 21 '14 at 11:12

1 Answers1

2

There's only one thread involved. You see the exception before the rest of the output because the exception is output into standard error stream (stderr, System.err), not standard output stream (stdout, System.out).

Standard output stream is usually buffered, so it may not output what you push into it immediately, while standard error stream is usually not buffered. For more information on this topic, see Why do System.err statements get printed first sometimes?.

Community
  • 1
  • 1
izstas
  • 5,004
  • 3
  • 42
  • 56