ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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

Updated on October 21, 2019
dwachira profile image

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

Table of Contents

<< Lesson 3 | Lesson 5 >>

Lesson 4: Working with variables in Java

Source

In Lesson 3, we learnt how to write a Java program in the Java code window and how to Run a Java program. In this lesson, we shall learn how to work with variables in Java and how to manipulate computer memory using variables.

Data is an important part of programming and programs work by operating on data. Data can be text, numbers, pointers, objects or some specified memory location.

Data is accessed by giving it a name and then assigning a value to it. The name of the data and its value is referred to as a variable. Now, let’s see how we can work with number variables in Java.

To use a number variable in Java, you must specify what type it is i.e. its data type. Whole numbers e.g. 5, 13, 28 etc. have a data type of int (for integer) while floating point numbers e.g. 1.6, 7.34, 0.8 etc. use a double data type. To store a value into a variable we use the equal sign (=) operator. For example, to store a value 20 to a variable called age we write the following:-

int age;

age = 20;

To workout with a practical example, let’s open the program we had in Lesson 3 and modify inside the “main” part to look like shown below:

public static void main(String[ ] args) {

int age;

age = 20;

}

So, to store a whole number, you first type the word int, followed by a space and then the name of your integer variable. To assign the value, you type the name of the variable followed by a space, then the equal sign (=) and finally the value itself, don’t forget the semicolon.

What the above code mean is that we want to store a value of 20 into an integer variable called “age”. Notice the above code can also be written using one line like shown below:

public static void main(String[ ] args) {

int age = 20;

}

To see the output when you run your program, we have to include the Java function for displaying the output on the output window. So, modify the code again to include the output function println(). Your code now should look like shown below:

Source

What we have between the round brackets of println is some direct text enclosed in double quotes:

("My age = "

We also have a plus sign, followed by the name of our variable:

+ age );

The plus sign tells Java to "join together" the output. So we're joining together the direct text, "My age = ", and the name of our variable, age. The joining together is known as concatenation. Notice each line of the code ends with a semicolon (;). Now, run the program and you should be able to see the following output.

Source

The value of age that we stored in the variable called “age” is output after the equals sign.

Variables in Java can be called any name but Java has some rules to be followed when naming your variables. Here are some of the rules:-

  • A variable name cannot start with a number. So you cannot call a variable 1stsalary or 20years.
  • A variable name cannot be the same as a keyword used in Java. Keywords in Java NetBeans appear in blue in the code window, like int, so you can’t miss them.
  • A variable name cannot have a space e.g. my Age. If you want to have two words for a variable name, just join them e.g. myAge or use an underscore e.g my_age.
  • Variable names are case sensitive. So Age and age are different variable names.

Arithmetic operators in Java

Java uses the commonly known computer arithmetic operators for calculations:

+ (the plus sign) for addition
- (the minus sign) for subtraction
* (the asterisk sign) for multiplication and
/ (the forward slash) for division

Working with variables of int type

Let's try some simple calculations. Modify your code and add three int variables. One to store basicSalary, another to store allowances and another to store grossSalary. Go ahead and assign 20000 to basicSalary and 12000 to allowances. What we want to do here is to add basicSalary and allowances and store the sum value in the variable called grossSalary and then output the grossSalary as the sum value. Your code now should look like shown below:

Source

If you run the program at this stage, you won’t be able to see the expected output. This is because we have not included the function to display the output. Now, include the following line of code in your program to enable you to see the sum output. We have modified the output statement to be more meaningful just like we did with age output.

System.out.println(“My Gross Salary is: “+grossSalary);

Your code should now look like shown below:

Source

Run the program and you should be able to see the output. You’ll see that the values in basicSalary (20000) and allowances (12000) have been summed up and stored in grossSalary as 32000, then 32000 is displayed together with the text, My Gross Salary is:, as the output.

Source

Java can store quite large numbers in the int variable type. The maximum value is 2147483647. If you want a minus number the lowest value you can have is -2147483648. If you want larger or smaller numbers than that then you can use a number variable of type double.

The double variable type is also used to hold floating point numbers i.e. numbers with a decimal point like 18.7, 10.3,154.108 etc. If you store a floating point value in an int variable, NetBeans will underline the faulty code and if you run the program, the compiler will display an error message.

Working with variables of double type

Up to this point you’ve been working with variables of int type. Let us now try to work with variables of type double. Modify your code to make your variables to be of type double. Then assign double type values to these variables like shown below:

Source

Notice that because we expect a double variable as the output, we also need to change the type of our output variable (grossSalary) from int to double type. Run the program again, this time you should be able to get a double output.

Source
Source

Working with variable of float type

The double values can store really big numbers of the floating point type. So, Instead of using double, float type can be used. When storing a value of a float type, we add letter "f" at the end of that value but before the semicolon. See below:

float basicSalary = 20000.78f;

float allowances = 12000.88f;

To experiment with a float data type values, modify your code again like shown below and run it.

Java order of Operators Precedence

The order in which arithmetic’s operations are executed in Java is very important to understand. This order is called Operator Precedence.

  • Multiplication and Division are treated equally, but have high priority than Addition and Subtraction
  • Addition and Subtraction are treated equally but have a lower priority than multiplication and division

If you are going to use more than one arithmetic operator in one statement, it's a good practice to always use some brackets so as to avoid some output errors derived from operators’ precedence.

Working with variables of String type (text)

As well as storing number values, variables can also store text values. Some text type variables can only store one character while others can store lots of characters. To store just one character, the char type variable is used, but to store more than one character String type variable is used. Mostly you will use String type variable as you may need to store lots of characters. We’ll create two String variables to hold the name of a person.

To define a string variable, type the word String followed by the name for your variable. Note that there is an uppercase "S" for String and the line ends with a semicolon.

String sir_name;

String other_name;

To assign values to the string variables, type an equal sign and then the text which should be between two sets of double quotes:

sir_name = “Benta”;

other_name = “Smith”;

Remember the above code can also be written as:

String sir_name = “Benta”;

String other_name = “Smith”;

To display both names, add the following code:

System.out.println(sir_name + " " + other_name);

In between the round brackets of println(), we have this:

sir_name + " " + other_name

We are telling Java to display the two names together but with a space in between. Now, modify your code like shown below and run once again.

Source

If you want to store a single character, use a variable of type char (lowercase "c") and then surround the character with single quotes and not double quotes:

char grade = 'B';

Remember: A String variable has double quotes and a char variable has single quotes.

In the next lesson we shall learn how we can accept inputs from the user, how we can manipulate such inputs and what more functions are there in Java.


<< Lesson 3 | Lesson 5 >>

Comments

    0 of 8192 characters used
    Post Comment
    • profile image

      Pujitha 

      6 years ago

      it is very good

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      Hi The Coder,

      I am glad this tutorial was helpful, thanks for the visit and comment.

    • profile image

      The Coder 

      7 years ago

      This is what i was looking for and you have done it well, very helpful tutorial. Thanks dwachira.

    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)