Variables In Java (Including If & Operators)

variables in java

Hello friend, in this short guide I explain what variables are in java and I give some examples using fun and easy to understand programs.

After that I explain how to use if statement in Java with examples.

Lastly, I touched operators in java too. All of them are simple to understand. And please enjoy as you read.

In simple terms, variables can be defined as memory locations that are used to store data in the program.

A very related example is your wardrobe where you keep your wears at home.

The wardrobe keeps your wears but different wears are kept in different locations. Just like how you can’t keep your shoes where your shirts are, you can’t store a decimal number like 3.7 in place of an integer like 9.

Types of Variables In Java

There are two types of variable in java, Primitive and classes.

Primitive Variables In Java

The primitive variables are used to store simple data and they are of three types.

  1. Numbers
  2. Char
  3. Boolean

Numbers can either be an Integer or a Real number.

Depending on the size, an Integer variable type can either be int, long, short or byte. And Real numbers can be either be float or double.

Char can be any character like 9, a, *, (, # anything.

Boolean is the variable that stores true or false.

Classes In Java

Classes are used to store complex data.

Tips On Using Variables in Java

All variables must start with small letter except String.

For example: int first = 9; int is the variable type and it starts with a small letter.

The variable name too must start with small letter including String.

For example: int boyAge = 13; boyAge is the variable name and it starts with small letter.

Each java statement (meaning each line of code) must end with a semi colon (;).

To further understand variables in Java, the following are Java programs that perform simple and specific tasks.

A Simple Java Program

class Add
{
               Public static void main(String[] args)
               {
                               System.out.println(8+2);
               }
}

This is a simple java program that adds 8 and 2 together.

Starting from the top, the ‘class Add’: all java programs are written inside a class because java is an object-oriented programming language, and class keyword is among the features that make OOP possible.

‘Add’ is the class identifier, also called the name of the class. As a convention, the name of the main class in a java program must be used as the of the source code file.

Every other part of the program resides in the class and all of them are called class definition.

The ‘Public static void main(String[] args)’ is another important part of a java program and it usually follows the main class.

The statement in the program above, ‘System.out.println(8+2);’, prints the result of the calculation to the screen. Your focus should be on the two added numbers since we are discussing variables in java.

Here is a quick question…

What do you think will happen is you need to change the numbers? Let’s say you change 8+2 to 8+8.

System.out.println(8+8);

You will have to change the values manually as above.

Editing the code manually like that is called hard coding and there are many things wrong with that. One of them being that you can’t easily reuse that same value in other parts of the program.

A recommended solution to that is to store the value(s) in a location and give it a name. and when there is need to use a value, you will just call it using its name.

So variable can be defined as a memory location use to store data in a program.

So abetter way to write the code using implementing variable will be:

int numberA = 8;

int numberB = 2;

System.out.println(numberA + numberB);

numberA and numberB are the variable names. These names are what will be used to call/use the values in any other part of the program.

You will see that numberA and numberB instead of 8+2. If numberA and numberB are the variable names, what is int then?

Just like there are names to identify each variable, there is a need to have a location to store them. int is a type of location used to store a variable.

Int stands for integer and it’s a type of Data Type. Data types are used to specify the type of variables and the size of the location that will be given to the variable. There are many other types of Datatypes.

In the beginning, the common datatypes you will need will be:

int, double, and char.

Int stores only integer values and has a memory size of 4 bytes.

Double use to store real numbers and has memory size of 8 bytes

Char used to store any of the characters on the keyboard and has a memory location of 2 bytes.

Variables are called that name because you the programmer, can decide to change their value at any time in the program.

Imagine if values aren’t stored anywhere and there are thousands of them you need to modify in your program. The modification will be very stressful.

Take for example:

int numberA = 8;
int numberB = 2;
numberA = 7;
System.out.println(numberA + numberB);

After running the result will be 9 because I have modified the value of numberA to be 7 in just a line of code.

Now think about this:

What if I didn’t use variables and I only put 8 in the program like this:

System.out.println(8+2);

And I have many places in my program where this 8 is used. Imagine how tedious it will be to change 8 to 7. I hope you understand the idea of variables in java now.

Note that data type is only used once in the program for the same variable. I don’t need to restate the data type of numberA again when I modified its value.

Simple Java Program That Prints Variables to The Screen

SOURCE CODE

int first = 7;
int second = 19;
System.out.println(“First = ”+first+”, Second ”+second);

OUTPUT

First = 7, Second = 19

On the last line of the code, the digits in the “quotes” will be printed out as they are while those without quotes will have their values printed out.

Those with their values printed are the variables.

Variable Value Replacing Exercise In Java

This program will swap the value of one variable with the value of one variable.

int first = 7;
int second = 19;
int third;
third = second;
second = first;
first = third;
System.out.println(“First = ”+first+”, Second ”+second);

OUTPUT

First = 19, Second = 7

We set the initial values for the two variable as 7 and 19, and we created a third variable.

To further understand this idea:

Take for example, you want to swap the content of two cups. In one cup you have Coca-Cola and in the other you have Pepsi, what will you do to swap the drinks in the cups?

The easy solution is to get another empty cup, the third.

You will put the Pepsi in the third, now the second cup is empty. Then you put the Coca-Cola in the first cup into the second cup which was for the Pepsi.

And lastly, you put the content of the third cup (Pepsi) into the first cup.

Java Program That Converts Temperature in Celsius into Fahrenheit

System.out.println(“What is the temperature value in Celsius? : ”);
Java.util.Scanner sc = new java.util.Scanner(System.in);
double Celsius = sc.nextInt();
double fahrenheit = 9.0 / 5.0 * Celsius + 32.0;
System.out.println(“Fahrenheit value is:  ”+fahrenheit);

The first line of the code asks the user to give the Celsius value.

The second line uses a Java utility tool to take in the Celsius value provided by the user.

And the third line stores the value.

The double variable type is used here because we are dealing calculation that involves division and we are likely to get remainders or decimal numbers.

Or in a simple term, this calculation involves decimal numbers.

And as you know numbers can either be an integer or Real. Real is numbers with decimal number and allows us to use the decimal part during our calculation.

Integer on the other hand doesn’t allow the use of the decimal part of a number.

There are two examples of a Real variable: float and double. Where double is the most used type.

A Program That Uses If Statement to Determine if Water is Boiling or Not

System.out.println(“Please Give The Value Of The Temperature In Celsius: ”);
java.util.Scanner sc = new java.util.Scanner(System.in);
int temp = sc.nextIntInt();
if (temp > = 100) {
System.out.println(“The Water Is Boiling”);
} else if (temp <=  0) {
System.out.println(“The Water Is Freezing”);
} else {
System.out.println(“The Water Is In Normal State”);
}

We first take the input from the user and store in into the temp variable name.

Now comes the fun part.

The first if tells the program that if the value stored in temp is greater than or equals to 100 it should print out ‘The Water Is Boiling’.

Else if the value is less than or equals 0 it should print ‘The Water Is Freezing’.

And the last part contains the last scenario that we can have if the water isn’t boiling or freezing, which is normal state.

This simple program explains the principle of if statement in Java programing.

It is quite simple and very much related to how we speak within ourselves.

Using Operators in Java

Operators in Java are used to combine two expressions and determine the output that the program should take as right or wrong.

For example:

Using the program above,

if (temp > 0 &amp;&amp; temp < 100) {
      System.out.println(“The Water Is In Normal State”);
}

The operator used here is the AND operator (&&) and it executes the next line if both conditions are true.

The other common operators in Java are:

|| OR Operator

Will be true is one or both conditions are true.

! Negate Operator

This will simply negate the condition.

For example:

if ( temp ! = 100) {
      System.out.println(“The Temperature Is Not 100”)
}

How Does Float Datatype Works

Float is another type of data type that stores real numbers like double but it operates a bit differently. The following program looks cool on the eye but it will always give an error:

float numberA = 7.2;
float numberB = 1.3;
System.out.println(numberA + numberB);

The reason for this is because in java, all real numbers are stored inside double data type and requires a little tweak if any related data type is to be used for the same purpose.

See how double is used:

double numberA = 7.2;
double numberB = 1.3;
System.out.println(numberA + numberB);

You will get the right answer using double. However, double takes up more memory space. So let’s see how you can implement float for this same purpose.

float numberA = 7.2f;
float numberB = 1.3f;
System.out.println(numberA + numberB);

The above code will give the same result as when you use double. The only difference is that float uses less memory space to store it variables. Float takes up 4 bytes of memory while double takes 8 bytes.

This might seem little but when the program becomes big little space like that can sum up to have a big impact on the speed of the whole program.

How Does Char Datatype Behaves

Take for example:

               char number = ‘10’;
               System.out.println(number);

The output will be 10 but do you notice something different? The value ‘10’ that is assigned to the char variable is enclosed in a single quote. This is the conventional way of declaring a char variable.

Consider this code too:

               char alph = ‘A’;
               System.out.println((int) alph);

The result of the above program will be 65. Why is that?

Computer stores every key on your keyboard in binary form because that’s the only language it understands. The computer only understands 0s and 1s. But you and I cant use 0s and 1s to communicate with the computer, it will be very difficult for us.

So a method was developed. This method will assigne a unique integer number to all the keys on your keyboard and when a key is pressed, its integer number will be converted to binary fro the computer to understand.

This method is called ASCII.

Back to the code above, char alph = ‘A’; stores character A and assigned variable name alph to it using char data type. This is quite easy to understand. The real magic is at the last line of the program.

System.out.println((int) alph); The (int) there tells the program to print the integer value of alph variable. And the result of the program gives you the equivalent ASCII code for ‘A’.

Alternatively:

You can get the char value of a number using:

System.out.println((char) 65);
Share via
Copy link
Powered by Social Snap