Manipulating Variables in Java

[S1E3]

Hritika Agarwal
7 min readAug 30, 2020

Introduction

Let’s say we are writing a program that represents a user’s bank account.

With variables, we know how to store a balance! We’d use a double, the primitive type that can hold big decimal numbers.

But how would we deposit and withdraw from the account?

Java has built-in math operations that perform calculations on numeric values!

To deposit:

// declare initial balance
double balance = 20000.99;
// declare deposit amount
double depositAmount = 1000.00;
// store result of calculation in new variable
double updatedBalance = balance + depositAmount;

Throughout this lesson, we will learn how to perform math on different datatypes and compare values.

public class GuessingGame {

public static void main(String[] args) {

int mystery1 = 8 + 6;

int mystery2 = 8–6;

System.out.println(mystery2);

}

}

Addition and Subtraction

In our bank account example from the last exercise, we used + to add!

double balance = 20000.99;
double depositAmount = 1000.0;
double updatedBalance = balance + depositAmount;
//updatedBalance now holds 21000.99

If we wanted to withdraw from the balance, we would use -:

double withdrawAmount = 500;
double updatedBalance = balance - withdrawAmount;
//updatedBalance now holds 19500.99

Addition and subtraction work with ints as well!

int numPicturesOfCats = 60 + 24;
int x = y +2;

If you had 60 pictures of cats on your phone, and you took 24 more, you could use the above line of code to store 84 in numPicturesOfCats.

Multiplication and Division

Let’s say that our employer is calculating our paycheck and depositing it to our bank account. We worked 40 hours last week, at a rate of 15.50 an hour. Java can calculate this with the multiplication operator *:

double paycheckAmount = 40 * 15.50;
//paycheckAmount now holds 620.0

If we want to see how many hours our total balance represents, we use the division operator /:

double balance = 20010.5;
double hourlyRate = 15.5;
double hoursWorked = balance / hourlyRate;
//hoursWorked now holds 1291.0

Division has different results with integers. The / operator does integer division, which means that any remainder is lost.

int evenlyDivided = 10 / 5;
//evenlyDivided holds 2, because 10 divided by 5 is 2
int unevenlyDivided = 10 / 4;
//unevenlyDivided holds 2, because 10 divided by 4 is 2.5

evenlyDivided stores what you expect, but unevenlyDivided holds 2 because ints cannot store decimals!

Java removes the 0.5 to fit the result into an int type!

public class MultAndDivide {

public static void main(String[] args) {

double subtotal = 30;

double tax = 0.0875;

double total = subtotal + (subtotal*tax);

System.out.println(total);

double perPerson = total/4 ;

System.out.println(perPerson);

}

}

Modulo

If we baked 10 cookies and gave them out in batches of 3, how many would we have leftover after giving out all the full batches we could?

The modulo operator %, gives us the remainder after two numbers are divided.

int cookiesBaked = 10;
int cookiesLeftover = 10 % 3;
//cookiesLeftover holds 1

You have 1 cookie left after giving out all the batches of 3 you could!

Modulo can be a tricky concept, so let’s try another example.

Imagine we need to know whether a number is even or odd. An even number is divisible by 2.

Modulo can help! Dividing an even number by 2 will have a remainder of 0. Dividing an odd number by 2 will have a remainder of 1.

7 % 2
// 1, odd!
8 % 2
// 0, even!
9 % 2
// 1, odd!

Greater Than and Less Than

Now, we’re withdrawing money from our bank account program, and we want to see if we’re withdrawing less money than what we have available.

Java has relational operators for numeric datatypes that make boolean comparisons. These include less than (<) and greater than (>), which help us solve our withdrawal problem.

double balance = 20000.01;
double amountToWithdraw = 5000.01;
System.out.print(amountToWithdraw < balance);
//this will print true, since amountToWithdraw is less than balance

You can save the result of a comparison as a boolean, which you learned about in the last lesson.

double myBalance = 200.05;
double costOfBuyingNewLaptop = 1000.05;
boolean canBuyLaptop = myBalance > costOfBuyingNewLaptop;
//canBuyLaptop is false, since 200.05 is not more than 1000.05

Equals and Not Equals

So how would we validate our paycheck to see if we got paid the right amount?

We can use another relational operator to do this. == will tell us if two variables are equal:

double paycheckAmount = 620;
double calculatedPaycheck = 15.50 * 40;
System.out.print(paycheckAmount == calculatedPaycheck);
//this will print true, since paycheckAmount equals calculatedPaycheck

Notice that the equality check is two equal signs, instead of one. One equal sign, =, is how we assign values to variables! It’s easy to mix these up, so make sure to check your code for the right number of equal signs.

To check if two variables are not equal, we can use !=:

double balance = 20000.0;
double amountToDeposit = 620;
double updatedBalance = balance + amountToDeposit;
boolean balanceHasChanged = balance != updatedBalance;
//depositWorked holds true, since balance does not equal updatedBalance

Greater/Less Than or Equal To

How could we make sure we got paid at least the amount we expected in our paycheck? We could use greater than or equal to, >=, or less than or equal to, <=!

double paycheckAmount = 620;
double calculatedPaycheck = 15.50 * 40;
System.out.println(paycheckAmount >= calculatedPaycheck);
//this will print true, since paycheckAmount equals calculatedPaycheck

public class GreaterThanEqualTo {

public static void main(String[] args){

double recommendedWaterIntake = 8;

double daysInChallenge = 30;

double yourWaterIntake = 235.5;

double totalRecommendedAmount = recommendedWaterIntake*daysInChallenge ;

boolean isChallengeComplete = (yourWaterIntake >= totalRecommendedAmount);

System.out.println(isChallengeComplete);

}

}

.equals()

So far, we’ve only been using operations on primitive types. It doesn’t make much sense to multiply Strings, or see if one String is less than the other. But what if we had two users logging into a site, and we wanted to see if their usernames were the same?

With objects, such as Strings, we can’t use the primitive equality operator. To test equality with Strings, we use a built-in method called .equals().

To use it, we call it on one String, by using ., and pass in the String to compare against in parentheses:

String person1 = "Paul";
String person2 = "John";
String person3 = "Paul";
System.out.println(person1.equals(person2));
//prints false, since "Paul" is not "John"
System.out.println(person1.equals(person3));
//prints true, since "Paul" is "Paul"

String Concatenation

We have covered a lot of built-in functionality in Java throughout this lesson. We’ve seen +, -, <, ==, and many other operators. Most of these only work on primitives, but some work on Strings too!

Let’s say we want to print out a variable, and we want to describe it as we print it out. For our bank account example, imagine we want to tell the user:

Your username is: <username>

With the value of the variable username displayed.

The + operator, which we used for adding numbers together, can be used to concatenate Strings. In other words, we can use it to join two Strings together!

String username = "PrinceNelson";
System.out.println("Your username is: " + username);

This code will print:

Your username is: PrinceNelson

We can even use a primitive datatype as the second variable to concatenate, and Java will intelligently make it a String first:

int balance = 10000;
String message = "Your balance is: " + balance;
System.out.println(message);

This code will print:

Your balance is: 10000

Review of this lesson

What’s the use of having variables if you can’t do anything with them? We’ve now seen some ways you can operate on variables and compare them. The possibilities are endless!

We covered:

  • Addition and subtraction, using + and -
  • Multiplication and division, using * and /
  • The modulo operator for finding remainders, %
  • Greater than, >, and less than, <
  • Equal to, ==, and not equal to, !=
  • Greater than or equal to, >=, and less than or equal to, <=
  • equals() for comparing Strings and other objects
  • Using + to concatenate Strings

Practice some of these concepts here, to make sure you have a solid foundation for learning more complicated and exciting Java concepts!

To review, let’s try building some of the bank account functionality we talked about throughout the lesson.

public class BankAccount {

public static void main(String[] args){

double balance = 1000.75;

double amountToWithdraw = 250;

double updatedBalance = balance — amountToWithdraw;

double amountForEachFriend = updatedBalance/3;

boolean canPurchaseTicket = (amountForEachFriend>= 250);

System.out.println(canPurchaseTicket);

System.out.println(“I gave each friend “ + amountForEachFriend + “…” );

}

}

Read Previous — Variables in Java

Read Next — Classes in Java

--

--