LEARN JAVA: MANIPULATING VARIABLES

Throughout this lesson, we will learn how to perform math on different datatypes and compare values.
Java has built-in math operations that perform calculations on numeric values!
Java Basics




Addition and Subtraction

Lets Take a example, suppose that you own a bank account, we will use  and If we wanted to withdraw from the balance, we would use -:

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

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

Addition and subtraction work with ints as well!
int numOfDogs = 60 + 30;
If you had 60 pictures of Dogs on your Pc/Phone, and you took 30 more, you could use the above line of code to store 90 in numOfDogs.

Multiplication and Division

Let’s say that our employer is calculating our paycheck and depositing it to our bank account. We worked 35 hours last week, at a rate of 16.11 an hour.  Java can calculate this with the multiplication operator *:
double paycheckAmount = 35 * 16.11; //paycheckAmount now holds 563.85
If we want to see how many hours our total balance represents, we use the division operator /:
double balance = 20010.5; double hourlyRate = 16.11; double hoursWorked = balance / hourlyRate; //hoursWorked now holds 1242.11669770329
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 Data type!

Modulo

If we make 10 candies 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 ccandiesMade = 10; int ccandiesLeftover = 10 % 3; //candiesLeftover holds 1
You have 1 Candy 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 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

.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 = "Maggi"; String person2 = "yippee"; String person3 = "Maggi"; System.out.println(person1.equals(person2)); //prints false, since "Maggi" is not "Yippee" System.out.println(person1.equals(person3)); //prints true, since "Maggi" is "Maggi"

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

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 , to make sure you have a solid foundation for learning more complicated and exciting Java concepts!




No comments:

Powered by Blogger.