Which Of The Following Are Variables That Store The Data For A Class?
1.3. Variables and Data Types¶
In this lesson, yous will learn about variables and primitive data types.
one.3.1. What is a Variable?¶
A variable is a proper noun associated with a retentiveness location in the computer. Reckoner memory can store a value and that value can change or vary.
The following video explains what a variable is and gives a couple of real discussion examples of variables.
i.3.2. Data Types¶
There are two types of variables in Java: archaic variables that hold primitive types and object variables that concur a reference to an object of a class. A reference is a way to discover the object (like a UPS tracking number helps you find your package). The primitive types presented in this chapter are:
-
int - which shop integers (numbers like iii, -76, 20393)
-
double - which store floating point numbers (decimal numbers like 6.3 -0.9, and 60293.93032)
-
boolean - which shop Boolean values (either true or false).
Cord is an object type and is the proper noun of a class in Java. A string object has a sequence of characters enclosed in a pair of double quotes - like "Hello". You will larn more most String
and other object types in Unit of measurement 2.
Notation
Some languages use 0 to represent false and 1 to represent true, but Java uses the keywords true
and false
in boolean variables.
A type is a set of values (a domain) and a set of operations on them. For instance, y'all tin can exercise mathematical addition with ints and doubles but not with booleans and Strings.
Cheque your understanding
- int
- While you could use an int, this would throw away whatsoever digits after the decimal point, and so it isn't the best choice. Y'all might want to round upwards a grade based on the average (89.5 or above is an A).
- double
- An average is calculated by summing all the values and dividing by the number of values. To continue the most amount of information this should exist done with decimal numbers so use a double.
- boolean
- Is an average true or fake?
- String
- While yous can apply a string to represent a number, using a number blazon (int or double) is better for doing calculations.
1-three-2: What blazon should you use to correspond the boilerplate grade for a course?
- int
- The number of people is a whole number so using an integer brand sense.
- double
- Tin yous have 2.five people in a household?
- boolean
- Is the number of people something that is either true or simulated?
- String
- While you can utilise a string, a number is better for doing calculations with (similar finding the average number of people in a household).
one-three-3: What type should y'all utilise to represent the number of people in a household?
- int
- People don't usually have whole numbers like 7 as their first name.
- double
- People don't normally have decimal numbers similar 3.5 every bit their start name.
- boolean
- This could only be used if the proper noun was truthful or simulated. People don't unremarkably have those equally start names.
- String
- Strings concur sequences of characters similar you accept in a person's name.
1-three-iv: What type should you utilize to hold the outset name of a person?
- int
- While yous could utilize an int and use 0 for false and 1 for true this would waste material 31 of the 32 bits an int uses. Java has a special type for things that are either true or false.
- double
- Java has a special blazon for variables that are either true or false.
- boolean
- Java uses boolean for values that are only true or false.
- Cord
- While you can use a string to represent "True" or "Simulated", using a boolean variable would be better for making decisions.
i-3-5: What type should you use to tape if information technology is raining or not?
- int
- The integer type (int) can't exist used to stand for decimal numbers so you couldn't use it if you had any cents.
- double
- The double type tin can be used to correspond an amount of money.
- boolean
- Java uses boolean for values that are only true or false.
- String
- While y'all tin utilise a string to correspond the corporeality of money you accept it is easier to do calculations on the numeric types (int or double).
1-3-six: What type should you use to represent the amount of money you lot have?
ane-3-7: What type should you use for a shoe size like 8.5?
1-iii-8: What type should you use for the number of tickets purchased?
1.3.three. Declaring Variables in Coffee¶
A variable allows you lot to store a value in a named retentivity location. To create a variable, you must tell Java its data type and its name. Creating a variable is also called declaring a variable. The blazon is a keyword similar int, double, or boolean, but you lot become to brand up the name for the variable. When you create a primitive variable Java volition set aside plenty $.25 in memory for that primitive type and associate that retention location with the variable proper noun that you used.
To declare (create) a variable, yous specify the type, get out at least one space, then the name for the variable and end the line with a semicolon ( ;
). Java uses the keyword int for integer, double for a floating point number (a double precision number), and boolean for a Boolean value (true or false).
Here is an example declaration of a variable called score that has type int.
Afterwards declaring a variable, you can give it a value like below using an equals sign =
followed by the value. The first time a variable is assigned a value is referred to every bit variable initialization.
Or you tin set up an initial value for the variable in the variable declaration. Here is an instance that shows declaring a variable and initializing it all in a single statement.
The equal sign here =
doesn't mean the same as it does in a mathematical equation where it implies that the two sides are equal. Here information technology means set the value in the memory location associated with the variable proper name on the left to a re-create of the value on the right. The line above sets the value in the retentiveness location called score to 4.
Note
The equal sign =
operator performs variable assignment. score=4
results in the value 4 beingness copied into the memory location for variable score.
Coding Exercise:
Run the post-obit code to see what is printed. Then, alter the values and run it once again.
Click the Show CodeLens
button and so use the Adjacent
button to stride through the program one line at a time. Stepping through a program lets y'all see how memory is assigned for each variable.
When you are printing the value of a variable, never put double quotes " "
around the variable because that will print out the variable name letter of the alphabet past letter of the alphabet. For instance, System.out.println("score");
will print out the cord "score", rather than the value iv stored in the variable. Usually y'all practise not want to impress out the variable name, but the value of the variable in memory. If you're non sure what this means, endeavour putting quotes around the variables in the impress statements above and see what happens.
Note
Avoid putting a variable inside quotes " "
in a print argument since that would print the variable name instead of its value.
Check Your Agreement
one-three-10: Click on all of the variable declarations in the following lawmaking. Variable declarations start with a type and then a name.
public class Test2 { public static void master(Cord[] args) { int numLives; numLives = 0; System.out.println(numLives); double health; wellness = 8.v; Arrangement.out.println(health); boolean powerUp; powerUp = true; System.out.println(powerUp); } }
1-3-11: Click on all of the variable initializations (first time the variable is set to a value) in the following code. Variables are initialized using assignment proper name = value; Initialization occurs one time per variable.
public grade Test2 { public static void master(String[] args) { int numLives; numLives = 0; Arrangement.out.println(numLives); double wellness = 8.5; System.out.println(health); boolean powerUp = true; Arrangement.out.println(powerUp); numLives = 5; System.out.println(numLives); powerUp = false; System.out.println(powerUp); } }
one-3-12: Click on all of the statements that both declare and initialize a variable in one argument. Variables are initialized using name = value;
public class Test2 { public static void main(String[] args) { int numLives; numLives = 0; Organisation.out.println(numLives); double health = 8.5; System.out.println(health); boolean powerUp = true; System.out.println(powerUp); } }
Cheque Your Agreement - Mixed upwards Code Problems
The following code declares and initializes variables for storing a number of visits, a person'southward temperature, and if the person has insurance or not. It besides includes extra blocks that are not needed in a right solution. Drag the needed blocks from the left area into the right club (declaring numVisits, temp, and hasInsurance in that order) in the correct area. Check your solution.
int numVisits = five; --- Int numVisits = 5; #paired --- double temp = 101.2; --- Double temp = 101.2; #paired --- boolean hasInsurance = false; --- Boolean hasInsurance = false; #paired
Cheque Your Agreement
1-3-14: Fill in the post-obit: [blank] age = [blank]; to declare age to be an int and set its value to 5.
1-three-15: Make full in the post-obit: Declare a double variable named gpa.
i-3-16: Fill in the following: Declare in int named studentCount and initialize it to 46. Follow the textbook style of using one space before and after the equal sign.
ane-iii-17: Fill up in the following: Declare in boolean variable isRaining and initialize information technology to true.
i.3.four. String Chain¶
You frequently demand to print a bulletin that mixes text with a variable value. You can use the cord concatenation operator +
to combine strings. So "hi " + "in that location"
will create a new Cord object with the value "hello there"
. If the variable proper noun has a value "Jose", and so the code "How-do-you-do " + name
will create a new String object with value "Hi Jose"
.
Coding Do:
Run the post-obit lawmaking to encounter what is printed.
If y'all want spaces between words and variables when printing, you must put the space inside the quoted string. For example, notice the space in the string "Hello " in the terminal impress statement. If y'all forget to add spaces, you will get smushed output like "HiJose" instead of "Hi Jose".
- Organisation.out.println("Cost is + toll");
- This volition print: Price is + cost
- System.out.println("Cost is " price);
- This results in a compile time error. Missing + for cord concatenation
- System.out.println("Toll is " + cost);
- Correct!
- Organization.out.println(Toll is + cost);
- This results in a compile time error. Missing quotes "Toll is "
- System.out.println("Toll is " + "price");
- This will print: Cost is price
ane-3-19: Presume variable proclamation double cost = ix.50;
. Which print statement will consequence in the output: Cost is nine.50
Add together a print statement to concatenate the string literal "Favorite color is " with the value stored in the colour
variable.
Also note that the variable has to exist on the left side of the =
and the value on the right. Switching the two is chosen assignment dyslexia.
Coding Exercise:
This is an example of assignment dyslexia, when the coder has put the value on the left and the declaration on the right side. Endeavor to set up the following code to compile and run.
i.3.5. Naming Variables¶
While y'all can name your variable almost anything, there are some rules. A variable name should outset with an alphabetic character (like a, b, c, etc.) and tin include letters, numbers, and underscores _
. It must be all one give-and-take with no spaces.
Yous can't use whatsoever of the keywords or reserved words as variable names in Java ( for
, if
, class
, static
, int
, double
, etc). For a complete listing of keywords and reserved words see http://docs.oracle.com/javase/tutorial/coffee/nutsandbolts/_keywords.html.
The proper name of the variable should describe the data information technology holds. A proper name like score
helps make your code easier to read. A proper name like ten
is usually not a practiced variable name in programming, because it gives no clues as to what kind of data it holds. Do not name your variables crazy things like thisIsAReallyLongName
. You desire to make your lawmaking piece of cake to empathize, not harder.
The convention in Java and many programming languages is to always beginning a variable name with a lower case letter and then uppercase the start letter of each additional discussion. Variable names can not include spaces so uppercasing the starting time letter of each additional word makes it easier to read the proper noun. Uppercasing the first letter of each additional word is called camel instance. Another selection is to employ underscore _
to separate words, simply yous cannot have spaces in a variable name.
Note
-
Employ meaningful variable names!
-
Beginning variable names with a lower case letter and use camelCase.
-
Variable names are instance-sensitive and spelling sensitive! Each employ of the variable in the code must match the variable name in the declaration exactly.
-
Never put variables within quotes (" "), unless y'all actually want to print the name of the variable rather than its value.
Coding Exercise:
Coffee is instance sensitive so playerScore
and playerscore
are not the same. Run the lawmaking beneath to run into the difference.
Check Your Understanding
1-3-23: What is the camel case variable name for a variable that represents a shoe size?
1-three-24: What is the camel case variable name for a variable that represents the top score?
1.3.6. Debugging Claiming : Weather Report¶
Debug the following code. Can you notice the all the bugs and get the code to run?
i.iii.7. Summary¶
-
A variable is a proper noun for a retentiveness location where you tin store a value that tin can change or vary.
-
A variable announcement indicates the type and name of the variable.
-
Use the assignment operator
=
to assign a value to the variable. You lot must initialize a variable before using it every bit an expression. -
Data types tin can be categorized as either archaic type (like int) or reference type (similar String).
-
The 3 primitive data types used in this course are int (integer numbers), double (decimal numbers), and boolean (true or fake).
-
Each variable has associated memory that is used to hold its value.
-
The memory associated with a variable of a primitive type holds an bodily primitive value.
-
When a variable is declared concluding, its value cannot exist changed once it is initialized.
You have attempted of activities on this page
Which Of The Following Are Variables That Store The Data For A Class?,
Source: https://runestone.academy/ns/books/published/csjava/Unit1-Getting-Started/topic-1-3-variables.html
Posted by: stephensexameste1969.blogspot.com
0 Response to "Which Of The Following Are Variables That Store The Data For A Class?"
Post a Comment