Advertisements

Swapping Two numbers without using a third variable

This is a simple method for swapping the values of two numeric variables without using a third variable.
The sample java code is given below.

public void Swapping(int a, int b)
	{
                System.out.println(Values Before Swapping);
		System.out.println(a+" , "+b);
		a=a+b;
		b=a-b;
		a=a-b;
                System.out.println(Values After Swapping);
		System.out.println(a+" , "+b);
	}
Advertisements

Checking for Odd or Even without using any Conditional Statements

Last day my friend asked me a question to write a program which tells whether a given number is odd or even without using any conditional statements. It is very simple. There may be several solutions. Two of the solutions are given below. The code is given below

Using Array


public void OddEven(int num)
	{
		String []store = {"even","odd"};
		System.out.println("The number is "+store[(num%2)]);	
	}

Using try-catch

public void EvenOdd ( int num)
	{
		int temp = num%2;
		try {
			int ans = 10/temp;
			System.out.println("Number is odd");
		}
		catch (Exception e) {
			System.out.println("Number is Even");
		}
	}