Java Exercises: Compare two numbers
Java Basic: Exercise-32 with Solution
Write a Java program to compare two numbers.
Test Data:
Input first integer: 25
Input second integer: 39
Pictorial Presentation:
Sample Solution:
Java Code:
import java.util.Scanner;
public class Exercise32 {
public static void main( String args[] )
{
// create Scanner to obtain input from command window
Scanner input = new Scanner(System.in);
int number1; // first number to compare
int number2; // second number to compare
System.out.print( "Input first integer: " ); // prompt
number1 = input.nextInt(); // read first number from user
System.out.print( "Input second integer: " ); // prompt
number2 = input.nextInt(); // read second number from user
if ( number1 == number2 )
System.out.printf( "%d == %d\n", number1, number2 );
if ( number1 != number2 )
System.out.printf( "%d != %d\n", number1, number2 );
if ( number1 < number2 )
System.out.printf( "%d < %d\n", number1, number2 );
if ( number1 > number2 )
System.out.printf( "%d > %d\n", number1, number2 );
if ( number1 <= number2 )
System.out.printf( "%d <= %d\n", number1, number2 );
if ( number1 >= number2 )
System.out.printf( "%d >= %d\n", number1, number2 );
}
}
Sample Output:
Input first integer: 25 Input second integer: 39 25 != 39 25 < 39 25 <= 39
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to check whether Java is installed on your computer.
Next: Write a Java program and compute the sum of the digits of an integer.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework