ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Programming in Java Netbeans - A Step by Step Tutorial for Beginners: Lesson 8

Updated on October 16, 2019
dwachira profile image

Danson Wachira is a certified Trainer in Computer Science, Information Technology and related studies.

Table of Contents

<< Lesson 7 | Lesson 9 >>

_______________________________________

Lesson 8: Control Structures in Java – IF ... ELSE statement

Source

Welcome to Lesson 8 of Programming in Java. In Lesson 7, we learnt about the IF statement and we also did one practical example to compare whether a number is positive or negative.

We also learnt about various Java programming operators, how we use them in a condition and we actually used some of these operators in our examples. Remember the code we had in Lesson 7? Below, have a look at it again.

Java program to determine positive and negative numbers

Source

As you can see, we had to use two IF statement to get our output. Another better option is to use IF .. ELSE statement. The structure of IF .. ELSE statement look as shown below:

if (condition) {

}
else {

}

The first part of IF .. ELSE statement has the condition you want to test for. Inside the curly braces you put the code to be executed if the condition is TRUE. In the second part, the else part, you put the code to be executed inside the curly braces if the condition is FALSE.

So, IF .. ELSE statement has two parts, one to cater for when condition is TRUE and another for when condition is FALSE. Modify your code to look like shown below and run the program.

Java program to determine positive and negative numbers

package myfirstprogram;
import javax.swing.JOptionPane;

class MyCondition {
     public static void main(String[] args) {
        String num;
        int num2;
        
        num = JOptionPane.showInputDialog("Enter a number: ");
        num2 = Integer.parseInt(num);
        
        if(num2 < 0){       //Check if number is negative
        JOptionPane.showMessageDialog( null,"The number is Negative");
        System.exit(0);
        }
        else{       //If it wasn't negative, then it is positive
        JOptionPane.showMessageDialog( null,"The number is Positive");
        System.exit(0);
        }
     }
}

IF .. ELSE IF Statement

There may be situations where we would like to test many conditions at the same time. Take for example the grading of students marks. Suppose we want to grade students according to the following grading system:

Student Marks Grading System

Marks
Grade
80 - 100
A
60 - 79
B
50 - 59
C
30 - 49
D
0 - 29
FAIL

To grade the marks according to the above given grading system, you’ll need several IF .. ELSE IF statements. You’ll also need to use a logical operator. Let us create another class, call it Grading.

We are going to let the user enter the marks in a text box. We’ll then convert the user input from string to int and use the int value to find the grade using IF .. ELSE IF statement.

Type the following code carefully and let’s see what it will do. You can create your own variables or just use the one I have used. Pay attention to curly braces.

Java program to grade students' marks

package myfirstprogram;
import javax.swing.JOptionPane;
    public class Grading {
    public static void main(String[] args) {
         String user_marks;
         int marks;
         //Get marks from the user and convert from string to int
         user_marks = JOptionPane.showInputDialog("Enter marks: ");
         marks = Integer.parseInt(user_marks);
         //Compute the grade and ouput the grade
         if(marks >= 80 && marks <= 100){
              JOptionPane.showMessageDialog( null,"Grade = A");
         }
         else if(marks >= 60 && marks <= 79){
             JOptionPane.showMessageDialog( null,"Grade = B");
         }
         else if(marks >= 50 && marks <= 59){
             JOptionPane.showMessageDialog( null,"Grade = C");
         }
         else if(marks >= 30 && marks <= 49){
             JOptionPane.showMessageDialog( null,"Grade = D");
         }
         else if(marks >= 0 && marks <= 29){
             JOptionPane.showMessageDialog( null,"Grade = FAIL");
         }
    }
}

In the above code, we are getting the input from the user as user_marks. We are then converting the user_marks from string to int and assigning it to another int variable called marks.

It is the value in the marks variable that we are using in the IF .. ELSE IF statement to find if it is within our grading system, and if it is, we output the correct grading statement in a message box.

We are also using the && (AND) logical operator to factor in the range of our value. Now, run the program and see if it will output the correct grade. Try with different values of inputs.

Source
Source
Source
Source

Notice that you won’t get any message if you enter a value greater than 100 or less than zero. This is because those values are not within our grading system and our program does not recognize them.

Exercise:

Modify the code so that when you enter a value greater than100 or less than zero the program output an appropriate message.


Nested IF statement

Nested IF just means an IF statement inside another IF statement. Suppose we want to admit a movie goer into the movie theatre only if he/she is at least 18 years of age and only if he/she has paid the entrance fee. We can use the following Nested IF statement:

If(age >= 18){

If(entrance fee == “Paid”){

JOptionPane.showMessageDialog( null,"Allow into movie theatre");

}

}

Nesting can also be applied in IF .. ELSE and IF ... ELSE IF statements.

Exercise: Write a program of your choice that will implement Nested IF statement.


Boolean values in Java

A Boolean value is one with two choices: true or false, yes or no, 1 or 0. In Java, there is a variable type for Boolean values and that is boolean type. So if we want to specify that a variable paid is Boolean and assign a value of true into it, we’ll write like follow:

Boolean paid = true;

If we need to use the variable paid, we can write a code like shown below:

if (paid == true) {
System.out.println("
it's true");
}
else {
System.out.println("
it's false");
}

Notice that the assignment operator is a single equals sign ( = ), but to check if a variable "has a value of" something, you need two equal signs ( = =).

In our next lesson, we shall see what is a switch statement and how we can use switch statement in Java.


<< Lesson 7 | Lesson 9 >>

Comments

    0 of 8192 characters used
    Post Comment
    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 months ago from Nairobi, Kenya

      Thank you for finding time to stop by, read and comment.

    • profile image

      Karl 

      6 years ago

      This is a great Tutorial Ive ever seen

    • profile image

      Esther 

      7 years ago

      I wanted to say i like this tutorial very much and may you continue to write even more. THanks

    • profile image

      Jeny 

      7 years ago

      Niceeeee!! Tutorial, thnaks

    • profile image

      jason1972 

      7 years ago

      Are there results for the exercises? I got mine to work, just want to know if there is a better or different way. Also, good straight forward tutorial, thank you!!

    • dwachira profile imageAUTHOR

      Danson Wachira 

      8 years ago from Nairobi, Kenya

      Thanks heathermichelle12, am glad that you found it to be useful.

    • heathermichelle12 profile image

      heathermichelle12 

      8 years ago

      This is a great tutorial!!! I am so bad at programing but I have to do it for classes some times. Java is a plus to know in almost any media career as well. Thanks!

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://maven.io/company/pages/privacy

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)