Java - Conditional Statements

Example 1: Sum, Subtraction, and Multiply using methods

							  
public class FunctionDemo {
	public static void main(String[] args) {
		int a=10;
		int b=20;
		sum(a,b);
		sub(a,b);
		mul(a,b);

	}

	static void sum(int x,int y)
	{
		int res=x+y;
		System.out.println("Sum is : "+res);
	}
	
	static void sub(int x,int y)
	{
		int res=x-y;
		System.out.println("Sub is : "+res);
	}
	
	static void mul(int x,int y)
	{
		int res=x*y;
		System.out.println("Mul is : "+res);
	}
	
}

							  

RESULT

Sum is : 30
Sub is : -10
Mul is : 200


Example 2: Sum of array of elements using methods

							  
public class FunctionDemo {
	public static void main(String[] args) {
		int a[]={10,20,30,40,50};
		int sum_res=sum(a);
		System.out.println("Sum is :"+sum_res);
	}

	static int sum(int x[])
	{
		int res=0;
		for(int i=0;i<x.length;i++){
			res=res+x[i];
		}
		return res;
	}
	
}				  

							  

RESULT

Sum is :150


Example 3: Sum, Substraction and Multiply using switch and functions

							  
public class FunctionDemo {

	public static void main(String[] args) {
		int a=10,b=20;
		int choice=2;
		switch(choice)
		{
		case 0:
			sum(a,b);
			break;
		case 1:
			sub(a,b);
			break;
		case 2:
			mul(a,b);
			break;
		default:
			System.out.println("Invalid number.");	
			break;
		}

	}
	static void sum(int x,int y)
	{
		int res=x+y;
		System.out.println("Sum is : "+res);
	}

	static void sub(int x,int y)
	{
		int res=x-y;
		System.out.println("Sub is : "+res);
	}

	static void mul(int x,int y)
	{
		int res=x*y;
		System.out.println("Mul is : "+res);
	}

}


							  

RESULT

Mul is : 200


BytecodeTechnosolutions.com | Raju