Java Question Set I – Conditional Statements in Java

In our previous articles we have shown you what is Java and how to write & run your first program in Java using command prompt & Java JDK only. In this article we will go through 7 basic questions that will be using “Condition Statement” of Java i.e ‘if – else’ & ‘else – if’ statements.

If you are an absolute beginner with programming, we would suggest you to go through the 3 ways of assigning value to variables in Java, that will help you in understanding these practice questions.

So, Let’s Begin

1. Find the largest number of the three numbers, taking numbers as input from the user.

Logic of the solution:

  1. Declare n1 , n2  and n3 to store user input into them.
  2. Print a message for  the user using System.out.println and ask for the numbers one by one and store them in separate variables
  3. Compare the values in the variable using the conditional statements
  4. If number 1 is greater than number 2 and number 3 both then, number one is greater.
  5. If number 2 is greater than number 1 and number 3 both then, number two is greater.
  6. Otherwise number 3 is definitely greater.
import java.util.*;
class largest
	public static void main(String [] arg)
		Scanner sc = new Scanner(;
		int n1,n2,n3;
		System.out.println("Enter 1st Number");
		System.out.println("Enter 2nd Number");
		System.out.println("Enter 3rd Number");
		if(n1>n2 && n1>n3)
			System.out.println(n1+" is greatest");
		else if(n2>n1 && n2>n3)
			System.out.println(n2+" is greatest");
			System.out.println(n3+" is greatest");


largest program

Alternative logics that can be applied:

Here we have to find the largest number of the 3 numbers, but when we have to do the same with a huge list of numbers, then this method will create a lot of mess, then a more sophisticated logic can be applied that is:

  1. Use Array to store numbers
  2. Store the first element of the Array into a variable largest
  3. Run a for  loop from 1 to the length of the array using for(int i=1; i< numbers.length; i++)
    1. Check if the first variable is smaller than the current element of the array, where element position changes using numbers[i] where i  is the number of iterations of the loop.
    2. If the value of the current element of the Array is larger than then
      1. Pass the value of the current element into the variable largest
  4. After the loop is complete, print the value of the largest  variable.
 for(int i=1; i< numbers.length; i++)
    if(numbers[i] > largest)
			largest = numbers[i];

Continue to next page for another question.

0 Responses on Java Question Set I - Conditional Statements in Java|

Leave a Message

Your email address will not be published. Required fields are marked *

CommentLuv badge

Pin It on Pinterest