1.3.1. What is a Variable?¶

A variable is a name associated with a memory location in the computer, where you have the right to store a value that can adjust or vary. The following video explains what a variable is and also gives a pair of genuine word examples of variables.

You are watching: Which of the following is not a variable data type?


When girlfriend play a game, it will often have a score. Scores regularly start at 0 and also increase, for this reason they can change. A score have the right to be save on computer in a variable.


*

Figure 1: A pong video game in scrape with a score presented in the top left.¶


1.3.2. Data Types¶

There space two varieties of variables in Java: primitive variables that hold primitive varieties and object or referral variables that hold a reference to things of a class. A recommendation is a means to discover the thing (like a UPS tracking number help you uncover your package). The primitive varieties on the advanced Placement computer system Science A exam are:


int - which save integers (numbers like 3, -76, 20393)

double - which save floating point numbers (decimal numbers favor 6.3 -0.9, and 60293.93032)

boolean - which store Boolean worths (either true or false).


String is one of the object varieties on the exam and also is the surname of a class in Java. A string object has actually a sequence of characters enclosed in a pair of twin quotes - choose “Hello”. You will learn much more about wire objects in Unit 2.


Note

Some languages use 0 to represent false and 1 to represent true, but Java supplies the keywords true and also false in boolean variables.


A type is a collection of worths (a domain) and a collection of to work on them. For example, you have the right to do enhancement with int’s and double’s but not through booleans and also Strings.

Check her understanding


1-3-2: What kind should you use to stand for the typical grade for a course?

intWhile you can use one int, this would throw away any digits after the decimal point, so the isn"t the best choice. You might want to round up a grade based upon the median (89.5 or over is an A). DoubleAn median is calculate by summing every the values and also dividing through the variety of values. To keep the most amount of information this must be done through decimal number so use a double. BooleanIs an median true or false? StringWhile you deserve to use a wire to stand for a number, utilizing a number form (int or double) is better for law calculations.

1-3-3: What kind should you usage to represent the number of people in a household?

intThe number of people is a whole number so utilizing an integer make sense. DoubleCan you have 2.5 world in a household? booleanIs the number of people something that is one of two people true or false? StringWhile you deserve to use a string, a number is far better for doing calculations through (like finding the average variety of people in a household).

1-3-4: What kind should you usage to host the an initial name of a person?

intPeople don"t typically have totality numbers like 7 together their first name. DoublePeople don"t usually have actually decimal numbers favor 3.5 together their an initial name. BooleanThis could only be supplied if the surname was true or false. Human being don"t usually have those as very first names. StringStrings organize sequences of characters like you have in a person"s name.

1-3-5: What kind should you use to document if the is raining or not?

intWhile you could use one int and use 0 because that false and 1 for true this would waste 31 that the 32 bits one int uses. Java has actually a special kind for points that space either true or false. DoubleJava has a special form for variables that room either true or false. BooleanJava provides boolean for worths that are just true or false. StringWhile you can use a wire to represent "True" or "False", utilizing a boolean variable would be much better for do decisions.

1-3-6: What form should you use to stand for the quantity of money friend have?

intThe integer type (int) can"t be supplied to represent decimal number so friend couldn"t usage it if friend had any kind of cents. DoubleThe twin type have the right to be offered to represent an amount of money. BooleanJava provides boolean for values that are only true or false. StringWhile you can use a wire to represent the lot of money you have actually it is much easier to carry out calculations on the numeric varieties (int or double).

1.3.3. Heralding Variables in Java¶

To produce a variable, you have to tell Java the data form and the name. Producing a variable is likewise called declaring a variable. The kind is a keyword favor int, double, or boolean, however you gain to make up the surname for the variable. When you produce a primitive variable Java will set aside enough bits in memory for the primitive kind and associate that memory place with the name the you used.

Computers save all values making use of bits (binary digits). A bit can represent 2 values and also we typically say the the worth of a bit is either 0 or 1. As soon as you explain a variable, you have to tell Java the form of the variable since Java requirements to know how plenty of bits come use and how to stand for the value. The 3 different primitive typesall call for different number of bits. One integer it s okay 32 bits that memory, a double gets 64 bits the memory and a boolean can be stood for by just one bit.


*

Figure 2: instances of variables v names and also values. Notification that the different types get a different amount of memory space.¶


To declare (create) a variable, you specify the type, leaving at least one space, climate the surname for the variable and also end the line v a semicolon (;). Java uses the keyword int because that integer, double for a floating allude number (a dual precision number), and boolean because that a Boolean value (true or false).

Here is an example declaration the a variable referred to as score.


After declaring a variable, friend can offer it a worth like listed below using an equals sign = adhered to by the value.


Or friend can set an initial worth for the variable in the variable declaration. Here is an example that shows proclaiming a variable and also initializing it all in a solitary statement.


When you are printing the end variables, you deserve to use the string concatenation operator + to add them to one more string within System.out.print. Never ever put variables inside price quotes “” since that will print out the variable surname letter by letter. You do not desire to print out the change name, yet the value of the variable in memory. If you’re not sure what this means, try putting quotes roughly the variable and also see what happens. In the print out, if you want spaces in between words and variables, you must put the an are in the quotes. If friend forget to include spaces, friend will get smushed output choose “HiJose” instead of “Hi Jose”.

Coding Exercise:


Run the adhering to code to check out what is printed. Then, adjust the values and also run it again. Shot adding estimates to variables and removing spaces in the print statements to see what happens.


public course Test2 public revolution void main(String<> args) int score; score = 0; System.out.print("The score is "); System.out.println(score); double price = 23.25; System.out.println("The price is " + price); boolean winner = false; System.out.println(won); winner = true; System.out.println(won); String surname = "Jose"; System.out.println("Hi " + name); ====// must pass if/when they operation codeimport revolution org.junit.Assert.*;import org.junit.*;;import java.io.*;public course rebab.netTests expand CodeTestHelper
Test public void testMain() throw IOException String calculation = getMethodOutput("main"); String suppose = "The score is 0 The price is 23.25 false true Hi Jose"; boolean passed = getResults(expect, output, "Expected output from main", true); assertTrue(passed);

Note

Variables are never put inside quotes (“”) in System.out.print statements. This would print the variable name out letter through letter instead of print its value.


Check your Understanding


1-3-8: Click on all of the variable declarations in the following code.Variable declarations start with a type and then a name.

public class Test2 public static void main(String<> args) int numLives; numLives = 0; System.out.println(numLives); double health; wellness = 8.5; System.out.println(health); boolean powerUp; powerUp = true; System.out.println(powerUp);
1-3-9: Click on every one of the change initializations (first time the change is collection to a value) in the complying with code.Variables space initialized utilizing name = value;public course Test2 public static void main(String<> args) int numLives; numLives = 0; System.out.println(numLives); double health = 8.5; System.out.println(health); boolean powerUp = true; System.out.println(powerUp);
The equal sign below = doesn’t median the very same as it does in a mathematical equation where it implies that the two sides space equal. Here it means set the value in the storage location connected with the variable name on the left to a copy that the value on the right. The very first line above sets the worth in the box dubbed score come 4. A variable constantly has to it is in on the left next of the = and also a value or expression on the right.

Coding Exercise:


public course Test3 public revolution void main(String<> args) int score; 4 = score; System.out.println(score); ====// should pass if/when they run codeimport static org.junit.Assert.*;import org.junit.*;;import java.io.*;public class rebab.netTests extend CodeTestHelper
Test windy void testMain() throw IOException String calculation = getMethodOutput("main"); String mean = "4"; boolean happen = getResults(expect, output, "Expected output from main"); assertTrue(passed);

Check your Understanding





Mixed up password Problems


The following code declares and initializes variables because that storing a number of visits, a who temperature, and if the person has insurance or not. It additionally includes extra block that space not required in a exactly solution. Drag the needed blocks indigenous the left area right into the exactly order (declaring numVisits, temp, and also hasInsurance in that order) in the best area. Click the “Check Me” button to check your solution.


int numVisits = 5;---Int numVisits = 5; #paired---double temp = 101.2;---Double temp = 101.2; #paired---boolean hasInsurance = false;---Boolean hasInsurance = false; #paired
The keyword final have the right to be supplied in front of a change declaration to do it a constant that can not be changed. Constants room traditionally capitalized.


Coding Exercise:


Try the following code and an alert the syntax error as soon as we try to adjust the continuous PI. Put the comment icons // in prior of the line to eliminate the error and run that again.


public class TestFinal public static void main(String<> args) final dual PI = 3.14; System.out.println(PI); PI = 4.2; // This will reason a syntax error ====// should pass if/when they operation codeimport static org.junit.Assert.*;import org.junit.*;;import java.io.*;public class rebab.netTests extend CodeTestHelper
Test windy void testMain() throw IOException String calculation = getMethodOutput("main"); String expect = "3.14"; boolean pass = getResults(expect, output, "Expected calculation from main", true); assertTrue(passed);

1.3.4. Specify name Variables¶

While you have the right to name her variable virtually anything, there are some rules. A change name should start with an alphabetic character (like a, b, c, etc.) and also can include letters, numbers, and underscores _. It must be all one word through no spaces.

You can not use any of the keywords or reserved words as variable surname in Java (for, if, class, static, int, double, etc). Because that a finish list the keywords and also reserved words, watch https://docs.oracle.com/javase/specs/jls/se14/html/jls-3.html#jls-3.9.

The surname of the variable should explain the data it holds. A name like score help make her code easier to read. A name like x is not a good variable surname in programming, because it offers no clues regarding what sort of data it holds. Perform not nameyour variables stunner things favor thisIsAReallyLongName, particularly on the AP exam. You want to make her code straightforward to understand, not harder.


Note

Use coherent variable names!

Start change names through a lower situation letter and use camelCase.

Variable names space case-sensitive and also spelling sensitive! Each usage of the variable in the code must complement the variable name in the declaration exactly.

Never put variables inside price quotes (” “).


The convention in Java and also many programming languages is to constantly start a change name with a lower instance letter and also then uppercase the first letter the each extr word, for example gameScore. Variable names can not incorporate spaces so uppercasing the first letter that each additional word makes it much easier to check out the name. Uppercasing the first letter that each extr word is called camel case because it looks choose the humps that a camel. One more option is to usage underscore _ to separate words, however you cannot have actually spaces in a change name.

See more: Which Skin Cancer Arises From The Youngest Epidermal Cells ?


Java is instance sensitive therefore gameScore and also gamescore are not the same. Run and also fix the code listed below to usage the appropriate variable name.


public course CaseSensitiveClass public revolution void main(String<> args) int gameScore = 0; // change name using camel instance // this is using a various variable there is no camel case! System.out.println("gameScore is " + gamescore); ====import revolution org.junit.Assert.*;import org.junit.*;;import java.io.*;public course rebab.netTests extends CodeTestHelper
Test windy void testMain() throws IOException String calculation = getMethodOutput("main"); String mean = "gameScore is 0 "; boolean passed = getResults(expect, output, "Expected calculation from main", true); assertTrue(passed);