Today in my Java course I began a new statement about control flow statements. Here is what the official Java documentation defines control flow as:

The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code. This section describes the decision-making statements (if-thenif-then-elseswitch), the looping statements (forwhiledo-while), and the branching statements (breakcontinuereturn) supported by the Java programming language.

I pretty much get it but I think it’s one of those things that the knowledge you really want about it is obtained by putting into action.

The type of control flow statement that I did today was the Switch statement. My understanding is that it’s similar to if statements. He did explain the difference but I didn’t quite understand it. Below is the code I wrote.

public class Main {

public static void main(String[] args) {

char switchValue = 'd';

switch(switchValue){
case 'a':
System.out.println("Value was A");
break;

case 'b':
System.out.println("Value was B");
break;

case 'c':
System.out.println("Value was C");
break;

case 'd':
System.out.println("Value was D");
break;

case 'e':
System.out.println("Value was E");
break;

default:
System.out.println("Could not find A, B, C, D or E");
}
}
}

The way it works is the variable switchValue is declared and assigned the value ‘d’. It’s char (character) type. I learned that char type variables need to be in single quotes.

Then there is a switch statement. I suppose in the brackets is where the variable that it’s testing has to go. Then below in the code block are listed what to do in various cases. In this code it simply prints out a string saying what the switch value was or an error message.

Note that it has break after each case. This is required because if it doesn’t then it will continue to run everything below that until it gets to either a break statement or the end of the switch statement.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s