The if statement

We have to make decisions in our daily life: If tutor tells me thisI’m going to answer that, otherwise I’ll do something else. Java program can use if and else statements to realize a decision.

Let’s modify the method dive() in the class Fish


In Fish class, the dive method is override as the new dive(int howDeep) method has an assumption howDeep as an integer. we can see the if … else … is used in the method. If the currentDepth is greater than 100, the fish can not dive that deep; else, if the currentDepth is smaller or equal to 100, yes, the fish can dive that deep.

The object myfish in FishMaster Class calls the new dive(int howDeep). We try two different assumptions of 12 and 120, each of them will go to the different decision.


Check your console to see the different output when you run the application.


Please practice:

  1. Create a new package
  2. Create a new class named TemperatureConverter.
  3. Add the method convertTemp() so the code of the class looks like this:
    public class TemperatureConverter {
        public static float convertTemp (float temperature,
                                   char convertTo) {
  4. Write the if statement inside the method convertTemp to check the value of the argument convertTo. If it’s F, the temperature has to be converted to Fahrenheit, and if it’s C, convert it to Celsius. Return the result. The method convertTemp should look like this:
        public static String convertTemp (float temperature, char convertTo) {
            if (convertTo=='F'){
                 return "The temperature in Fahrenheit is " + (9*temperature/5 + 32);
             } else if(convertTo=='C') {
                return "The temperature in Celsius is " + (temperature - 32) * 5/9;
            }  else{
                return "You can enter either F or C as convertTo argument";
  5. Add the method main should look like this:
        public static void main(String[] args) {
            System.out.println("Converting 21C to Fahrenheit. " +  convertTemp(21,'F'));
            System.out.println("Converting 70F to Celsius. " +  convertTemp(70,'C'));
  6. Run the program TemperatureConverter If you did everything right, you should see the following output on the IDEA console:
    Converting 21C to Fahrenheit. The temperature in Fahrenheit is 69.8
    Converting 70F to Celsius. The temperature in Celsius is 21.11111
    reference to The book "Java for Kids" was written by Yakov Fain, Java Champion

Leave a Reply

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

You are commenting using your 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