In this lesson, you will certainly learn about assignment statements and also expressionsthat contain mathematics operators and also variables.

You are watching: To add a value 1 to variable x, you write


1.4.1. Assignment Statements¶

Remember the a change holds a worth that can adjust orvary. Assignment statements initialize or change the worth storedin a variable utilizing the assignment operator =. An assignment statement constantly has asingle variable on the left hand side of the = sign. The value of theexpression on the ideal hand side ofthe = sign (which deserve to contain mathematics operators and other variables) is copiedinto the memory place of the change on the left hand side.


*

Figure 1: Assignment declare (variable = expression)¶


Instead the saying equals for the = operator in one assignment statement,say “gets” or “is assigned” toremember that the variable on the left hand side it s okay or is assigned the worth on the right.In the figure above, score is assigned the worth of 10 time points(which is another variable) plus 5.

The following video clip by Dr. Colleen Lewis shows just how variables can change values inmemory using assignment statements.


As we saw in the video,we can collection one variable to a copy of the value of an additional variable favor y = x;.This won’t adjust the value of the variable that you are copying from.

Coding Exercise:


Click ~ above the show CodeLens switch to step through the code and see just how the values of the variables change.


public course VariableAssignment public revolution void main(String<> args) int x = 3; int y = 2; System.out.println(x); System.out.println(y); x = y; System.out.println(x); System.out.println(y); y = 5; System.out.println(x); System.out.println(y); ====

The regimen is supposed to number out the total money value given the variety of dimes, quarters and also nickels.There is one error in the calculation of the total. Fix the error to compute the correct amount.


public class CalculateMoney public static void main(String<> args) int numDimes = 7; int numQuarters = 3; int numNickels = 8; int complete = numDimes * 10 + numQuarters + 25; System.out.println("Total = " + total); ==== import revolution org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; income java.io.*; public class moment-g.comTests extend CodeTestHelper
Test publicly void test1() String calculation = getMethodOutput("main"); String mean = "Total = 185\n"; boolean happen = getResults(expect, output, "Expected output from main"); assertTrue(passed);
Test publicly void test2() throw IOException wire target1 = "numQuarters * 25"; boolean passed1 = checkCodeContains("numQuarters * 25", target1); assertTrue(passed1);
Test public void test3() throw IOException string target1 = "numNickels * 5"; boolean passed1 = checkCodeContains("numNickels * 5", target1); assertTrue(passed1);

Calculate and also print the complete pay given the weekly salary and the variety of weeks worked.Usestring concatenation through the totalPay variable to develop the output complete Pay = $3000.Don’t hardcode the number 3000 in your publish statement.


public course SalaryExample public static void main(String<> args) int weeklySalary = 500; int numWeeks = 6; int totalPay; ==== import revolution org.junit.Assert.*; import org.junit.After; income org.junit.Before; import org.junit.Test; income java.io.*; public course moment-g.comTests expand CodeTestHelper
Test publicly void test1() String output = getMethodOutput("main"); String mean = "Total salary = $3000\n"; boolean passed = getResults(expect, output, "Expected calculation from main"); assertTrue(passed);
Test publicly void testPrintStringsB() throws IOException String password = getCode(); int count = countOccurences(code, "totalPay = weeklySalary * numWeeks") + countOccurences(code, "totalPay = numWeeks * weeklySalary") ; boolean happen = count >= 1; happen = getResults("1", "" + count , "correct totalPay calculation", passed); assertTrue(passed);
Test publicly void testStrConcat() litter IOException string target1 = "+ totalPay);"; boolean passed1 = checkCodeContains("print statement concatenation of totalPay variable", target1); assertTrue(passed1);

Check your understanding


1-4-5:

*
The code over shows the variable state in memory after heat 9 is executed. What is printed when line 10 is executed?


Coding Exercise:


Assume you have a package v a offered height 3 inches and also width 5 inches. If the parcel is rotated 90 degrees, you have to swap thevalues for the height and also width.The code listed below makes an effort to swap the values stored in two variables h and also w, which represent height and also width. Variable h should finish up through w’s initialvalue the 5 and w should acquire h’s initial worth of 3. Regrettably this code has actually an error and also does not work.Use the CodeLens to action through the password to know why it fails to swap the values in h and w.


public class ErrorSwap public revolution void main(String<> args) int h = 3; int w = 5; System.out.println(h); //3 System.out.println(w); //5 h = w; w = h; System.out.println(h); //expected 5 System.out.println(w); //expected 3 ====

1-4-7: describe in your very own words why the ErrorSwap regime code does not swap the worths stored in h and also w.


Check her understanding

Swapping 2 variables needs a third variable. Prior to assigning h = w, you should store the initial value of h in the temporary variable.In the blended up programs below, traction the blocks to the right to placed them in the appropriate order.


The following has the correct password that provides a 3rd variable named “temp” to swap thevalues in h and w.

The password is combined up and also contains one extra block which is no neededin a exactly solution. Drag the required blocks native the left right into the correctorder on the right, then inspect your solution.You will certainly be called if any of the blocks space in the wrong order or if you need to removeone or much more blocks.

After 3 incorrect attempts you will be able to use the help Me switch to do the trouble easier.


Fix the code listed below to execute a exactly swap the h and also w.You need to include a new variable named temp to use for the swap.


public course CorrectSwap public static void main(String<> args) int h = 3; int w = 5; System.out.println(h); System.out.println(w); h = w; w = h; System.out.println(h); System.out.println(w); ==== import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; income org.junit.Test; income java.io.*; public class moment-g.comTests extend CodeTestHelper
Test publicly void test1() String output = getMethodOutput("main"); String expect = "3\n5\n5\n3\n"; boolean passed = getResults(expect, output, "Expected output from main"); assertTrue(passed);
Test publicly void test2() String password = getCode(); String suppose = "int temp"; int counting = countOccurences(code, expect); boolean pass = counting >= 1; passed = getResults("1 temp declaration", "" + counting + " temp declaration", "Declare change temp", passed); assertTrue(passed);
Test windy void test3() String code = getCode(); String intend = "temp = h"; int count = countOccurences(code, expect); boolean happen = count >= 1; passed = getResults("1 temp assignment to h", "" + count + " temp assignment to h", "Assign change temp come h", passed); assertTrue(passed);
Test publicly void test4() String password = getCode(); String suppose = "w = temp"; int count = countOccurences(code, expect); boolean happen = counting >= 1; passed = getResults("1 w assignment come temp", "" + counting + " w assignment to temp", "Assign variable w to temp", passed); assertTrue(passed);

1.4.2. Incrementing the worth of a variable¶

If you use a variable to keep score you would most likely increment it(add one to the existing value) at any time score must go up.You deserve to do this by setup the variable to the current value of thevariable to add one (score = score + 1) as displayed below. The formulalooks a small crazy in math class, but it makes sense in codingbecause the variable on the left is collection to the value of the arithmeticexpression on the right. So, the score change is set to theprevious worth of score + 1.

See more: What Is The Function Of Setae In Biology? What Is The Function Of Setae In Earthworms

Coding Exercise:


public course UpdateScore public revolution void main(String<> args) int score = 0; System.out.println(score); score = score + 1; System.out.println(score); score = score + 1; System.out.println(score); ====// Test password for lesson 1.4 expressions - iccv1 import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; income org.junit.Test; income java.io.*; public class moment-g.comTests extends CodeTestHelper
Test windy void test1() String calculation = getMethodOutput("main"); String suppose = "0\n1\n2\n"; boolean passed = getResults(expect, output, "Expected output from main", true); assertTrue(passed);

Check her understanding


1.4.3. Operators¶

Java uses the standard mathematical operator for addition (+), individually (-), multiplication (*), and division (/). Arithmetic expressions have the right to be of kind int or double. An arithmetic operation that uses two int worths will advice to an int value. An arithmetic procedure that supplies at the very least one twin value will certainly evaluate to a twin value. (You may have actually noticed the + was likewise used to placed text together in the entry program over – more on this when we talk around strings.)

Java uses the operator == to test if the value on the left is equal to the worth on the right and != to test if 2 items are not equal. Don’t obtain one equal authorize = perplexed with two equal indicators ==! lock mean various things in Java. One equal sign is provided to assign a worth to a variable. 2 equal indications are used to test a change to see if that is a certain value and also that returns true or false together you’ll check out below. Usage == and also != just with int values and not doubles because double values room an approximation and also 3.3333 will not same 3.3334 even though lock are very close.