Java Switch Statement

  1. Syntax
  2. Switch Statement (int) in Java
  3. Switch Statement (char) in Java
  4. Switch Statement (enum) in Java

Note
Here I am using,
OS : Linux (Ubuntu 12.04)
IDE : Eclipse Tool
Eclipse : Juno (Version 4.2.0)
Package : Default package

A. Syntax


Switch Statement

switch(caseValue) {
 
case caseValue1 :
	// Statement-1 if caseValue1 = caseValue
	break;
case caseValue2 :
	// Statement-2 if caseValue2 = caseValue
	break;
case caseValue3 :
	// Statement-3 if caseValue3 = caseValue
	break;
default :
	// Statement-4 if caseValue is not available..
}





B. Switch Statement (int) in Java


Switch_Ex1.java

public class Switch_Ex1 {
	
	void display(int n) {
		
		switch(n) {
		
		case 1 :
			System.out.println("Switch Case : 1");
			break;
		case 2 :
			System.out.println("Switch Case : 2");
			break;
		case 3 :
			System.out.println("Switch Case : 3");
			break;
		default :
			System.out.println("Switch Case : Default");
		}
	}
}
 
class MainClass {
	
	public static void main(String args[]) {
		
		Switch_Ex1 obj = new Switch_Ex1();
		obj.display(2);
		obj.display(10);
	}
}

Sample Output

Switch Case : 2
Switch Case : Default




C. Switch Statement (char) in Java


Switch_Ex2.java

public class Switch_Ex2 {
	
	void display(char name) {
		
		switch(name) {
		
		case 'A':
			System.out.println("Switch Case : A");
			break;
		case 'B' :
			System.out.println("Switch Case : B");
			break;
		case 'C' :
			System.out.println("Switch Case : C");
			break;
		default :
			System.out.println("Switch Case : Default");
		}
	}
}
 
class MainClass {
	
	public static void main(String args[]) {
		
		Switch_Ex2 obj = new Switch_Ex2();
		obj.display('B');
		obj.display('A');
		obj.display('Y');
		
	}
}

Sample Output

Switch Case : B
Switch Case : A
Switch Case : Default




D. Switch Statement (enum) in Java


Switch_Ex3.java

public class Switch_Ex3 {
	
	enum friends {Boobalan, Vinoth, Mani, Rahul, Kumaresan};
		
	void display() {
		
		for(friends guys : friends.values()) {
			
			switch(guys) {
			
			case Boobalan :
				System.out.println("Boobalan");
				break;
			case Vinoth :
				System.out.println("Vinoth");
				break;
			case Mani :
				System.out.println("Mani");
				break;
			case Rahul :
				System.out.println("Rahul");
				break;
			case Kumaresan :
				System.out.println("Kumaresan");
				break;
			default :
				System.out.println("Friends");
			}
		}
	}
}
 
class MainClass {
	
	public static void main(String args[]) {
		
		Switch_Ex3 obj = new Switch_Ex3();
		obj.display();
	}
}

Sample Output

Boobalan
Vinoth
Mani
Rahul
Kumaresan






SHARE THIS PAGE



product 2

product 3

Feedbacks : balaji.scz@gmail.com