1

How to create a variable that only allows 3 different values ? For example, the variable color can only take either one of the 3 values {RED, BLACK, ORANGE} and nothing else.

Obviously, I know that I can define String color , but is there a better way to do this ?

mynameisJEFF
  • 4,073
  • 9
  • 50
  • 96

4 Answers4

6

Define an enum

public enum Color {
   RED, BLACK, ORANGE;
}

and use it like this:

Color red = Color.RED;

You can define in or outside of the enclosing class.

If you wish to define it inside the class, the enum will be implicitly static (by default) and will be accessible it like this

SomeClass.Color red = SomeClass.Color.RED;
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
0

You can use an Enum. It allows only to use specific Objects.

Enum Color { RED, GREEN, BLUE };
Color var = Color.RED;
kostja93
  • 3
  • 2
0

If you want a simple way to define a color with no particular meaning:

public enum Color {
    RED, BLACK, ORANGE;
}

If you want to define a variable which can allows real java.awt.Color:

import java.awt.Color;


public enum MyColor
{
    RED (Color.RED),
    BLACK (Color.BLACK),
    ORANGE (Color.ORANGE);


    private Color value;

    private MyColor(Color value) {
        this.value = value;
    }

    public Color getValue() {
        return value;
    }
}
Giulio Biagini
  • 935
  • 5
  • 8
0

Enum-variables/fields can hold null aswell, so you will have 4 possible values, BLACK,RED,ORANGE and null. Try to use null as BLACK.

enum Color {RED,ORANGE;
  static boolean isBlack(Color c){
    return c == null;
  }
  static boolean isRed(Color c){
    return c == RED;
  }
  static boolean isOrange(Color c){
    return c == ORANGE;
  }
};
Grim
  • 1,938
  • 10
  • 56
  • 123