Posted by: ahmedashfaque | March 5, 2015

why Java is so popular? part 6


Suppose you have a requirement to compare 2 numbers and find out which one of them is the smaller number. How you can do it in Java?

For doing it, we will create a class and create a function which will do the comparison of the 2 numbers.

public class CompareNumber{
   
   public static void main(String[] args) {
      int a = 112;
      int b = 434;
      int c = compareFunction(a, b);
      System.out.println("The smaller number is = " + c);
   }

   /** compare and return the smaller number */
   public static int compareFunction(int x, int y) {
      int min;
      if (x > y)
         min = y;
      else
         min = x;

      return min; 
   }
}

When you run this program, system will compare and find out which number is smaller 
and will print it.

Explanation:
We have created a method compareFunction. This function takes 2 parameters (x and y) 
and compares them and finds out smaller of the 2 numbers.
Next we call this method inside our main method. this method provides values for x and y 
and our compareFunction calculates and finds out the result. This result we print out
in the print statement.

Advertisements

Responses

  1. […] far in part 1, part 2, part 3, part 4, part 5 and part 6 we have covered many topics on Java. In this post we will see […]

  2. […] far in part 1, part 2, part 3, part 4, part 5, part 6 and part 7 we have covered many topics on Java. In this post we will see […]

  3. […] far in part 1, part 2, part 3, part 4, part 5, part 6, part 7 and part 8 we have covered many topics on Java. In this post we will see loop […]

  4. […] far in part 1, part 2, part 3, part 4, part 5, part 6, part 7, part 8 and part 9 we have covered many topics on Java. In this post we will see nested if […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: