Java 7 Switch Case PRO

As of Java 7 we can write a switch case statement that works on strings. This new capability might assist us with writing a shorter code.

package com.abelski.samples;

public class Demo
{
	public static void main(String[] args)
	{
		String operator = args[1];
		double numA = Double.parseDouble(args[0]);
		double numB = Double.parseDouble(args[2]);
		String result;
		switch(operator)
		{
		case "+":
			result = numA+"+"+numB+"="+(numA + numB);
			break;
		case "-":
			result = numA+"-"+numB+"="+(numA-numB);
			break;
		case "*":
			result = numA+"*"+numB+"="+(numA*numB);
			break;
		case "/":
			result = numA+"/"+numB+"="+(numA/numB);
			break;
		default:
			result = "you can use one of the following operators +,-,/ or *";
			break;
		}
		System.out.println(result);
	}
}

The following video clip overviews this code sample and shows its execution.

Share:

The Visitor Design Pattern

The Visitor Design Pattern

The visitor design pattern allows us to add operations to objects that already exist without modifying their classes and without extending them.

The Beauty of Code

Coding is Art! Developing Code That Works is Simple. Develop Code with Style is a Challenge!

Update cookies preferences