Java Planet

O Javie i jej otoczeniu

Magiczny switch-case

Nigdy nie podobała mi się konstrukcja switch/case w javie. Może dlatego, że jej działanie jest nie do końca intuicyjne.

public class SwithCase {

	// zmienna nie może być typu long
	// Cannot switch on a value of type long. Only convertible int values or enum constants are permitted
	//static public long i = 10;

	// za to możemy mieć zmienną typu byte (bo byte "rzutuje" się na int)
	static public byte i = 10;

	public static void main(String argv[]) {
		switch (i) {
		default:
			System.out.println("no value given");
		case 1:
			System.out.println("one");
		case 10:
			System.out.println("ten");
		case 5:
			System.out.println("five");
		case 2:
			System.out.println("two");
			break;
		case 0:
			System.out.println("zero");
		}
		/**
		 * REZULTAT wykonania:
		 * ten
		 * five
		 * two
		 */
	}
}

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

COMMENTS

No Comments

There are no comments posted yet. Be the first one!

Leave a Replay