Differentiate switch and if statements in java.
Explain nested switch with example.
how can we use break as a form of GOTO statements

Recommended Answers

All 4 Replies

int i=0;
switch (i) 
{
  case 1:
      System.out.println("Value 1");
      break;
case 2:
      System.out.println("Value 2");
	break;
}

The code checks 'i''s value. When it finds a case that has that value, it executes what is under it.
So the above code will print: "Value 1". Then break will be executed and it leave the switch. If you ommit break, then it will go to print the next 'case'. It will not make a check at each case:

int i=0;
switch (i) 
{
  case 1:
      System.out.println("Value 1");
case 2:
      System.out.println("Value 2");
	break;
}

The above will print:
"Value 1"
"Value 2"
And then break. If you add default, it will be executed if no case is found with the number at the switch

int i=3;
switch (i) 
{
  case 1:
      System.out.println("Value 1");
case 2:
      System.out.println("Value 2");
	break;
default:
      System.out.println("Default");
}

Will print: "Default"
Again with this all of them will be printed, since the break is missing:

int i=1;
switch (i) 
{
  case 1:
      System.out.println("Value 1");
case 2:
      System.out.println("Value 2");
default:
      System.out.println("Default");
}

"Value 1"
"Value 2"
"Default"

Now you don't need brackets at the switch, case. It will execute anything that is below it until it finds break

int i=1;
switch (i) 
{
  case 1:
      System.out.println("Value 1");
//command 1
//command 2
//.......
      break;
case 2:
      System.out.println("Value 2");
default:
      System.out.println("Default");
}

Meaning that you can add anything you want at "command 1" even a second switch/case

commented: Been fooled by silly request, but provide great work +10

Well, looks as though he successfully fooled you with his homework/test question.

I thought that he was trying to understand how the switch statements works. But now that you mentioned it the question looks a lot like a question from a test

I thought that he was trying to understand how the switch statements works. But now that you mentioned it the question looks a lot like a question from a test

not really...

looked like he was even to lazy to copy the entire assignment as given to him..

as an answer for Atif Azmi's question: either read the material your teacher gave you, do just a very little trouble trying to find the information you need on the world wide web, or buy "Java 4 Dumm13z"

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.