Find the output of Java programs | Enumeration | Set 1: Enhance the knowledge of Java Enumeration concepts by solving and finding the output of some Java programs.
Question 1:
public class EnumEx {
enum Week {
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
}
public static void main(String[] args) {
Week W1 = Week.Tue;
Week W2 = Week.Thu;
int W = 0;
W = W1 + W2;
System.out.println("W: " + W);
}
}
Question 2:
public class EnumEx {
enum Week {
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
}
public static void main(String[] args) {
Week W1 = Week.Tue;
Week W2 = Week.Thu;
int W = 0;
W = (int) W1 + (int) W2;
System.out.println("W: " + W);
}
}
Question 3:
public class EnumEx {
enum Week {
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
}
public static void main(String[] args) {
Week W1 = Week.Tue;
Week W2 = Week.Thu;
String W = "";
W = W1.toString() + W2.toString();
System.out.println(W);
}
}
Question 4:
public class EnumEx {
enum Week {
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
}
public static void main(String[] args) {
System.out.println(Week.valueOf("Mon"));
System.out.println(Week.valueOf("Fri"));
}
}
Question 5:
public class EnumEx {
enum Week {
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
}
public static void main(String[] args) {
System.out.println(Week.Wed.ordinal());
System.out.println(Week.Sat.ordinal());
}
}
Answer Question 1:
Output:
Explanation:
The above program will generate syntax error because we cannot add two enumeration operands using plus + operator directly.
Answer Question 2:
Output:
Explanation:
The above program will generate syntax error because enumeration Week does not contain integer values.
Answer Question 3:
Output:
Explanation:
In the above program, we created a class EnumEx that contains a user define enumeration Week and a main() method. The Week enumeration contains 7-week values.
Now look to the main() method, here we created two enum variables W1 and W2 that are initialized with Week. Tue and Week.Thu respectively,
W = W1.toString() + W2.toString();
In the above statement, we converted the values of W1 and W2 into the string and then concatenating them and assigned them to the string W and then print W on the console screen.
Answer Question 4:
Output:
Explanation:
In the above program, we created a class EnumEx that contains a user define enumeration Week and a main() method. The Week enumeration contains 7-week values.
System.out.println(Week.valueOf("Mon")); System.out.println(Week.valueOf("Fri"));
In the above statements, we printed the value of specified enum constant on the console screen.
Answer Question 5:
Output:
Explanation:
In the above program, we created a class EnumEx that contains a user define enumeration Week and a main() method. The Week enumeration contains 7-week values.
System.out.println(Week.Wed.ordinal()); System.out.println(Week.Sat.ordinal());
In the above statements, we printed the value of the index of enum constants.
need an explanation for this answer? contact us directly to get an explanation for this answer