πŸ“š

Β >Β 

πŸ’»Β 

Β >Β 

βž•

1.2 Variables and Primitive Data Types

7 min readβ€’december 26, 2022

Peter Cao

Peter Cao

user_sophia9212

user_sophia9212

Peter Cao

Peter Cao

user_sophia9212

user_sophia9212


AP Computer Science AΒ πŸ’»

130Β resources
See Units

Variables and Data Types

Primitive Data Types

In Java, everything is either one of several primitive data types or combinations of these primitive data types (collections and objects). These combinations of primitive data types are called reference data types. For this class, you have to know these three:
Intβ€”Stores an integer number from -2,147,483,648 to 2,147,483,647. The highest integer value is called Integer.MAX_VALUE and the lowest value is called Integer.MIN_VALUE. Entering an integer outside this range results in an integer overflow and automatically converts it to Integer.MAX_VALUE if it’s too high and Integer.MIN_VALUE if it’s too low.
Examples: 1, 3, 5, -1, 0
Doubleβ€”Stores a decimal number with high precision (15 decimal places). If you give more decimal places than 15, the decimal will be truncated.
Examples: 0.0, -13.55342323, 363.34334
Booleanβ€”Stores a truth value
Examples: true, false
Each of the primitive data types comes with its own set of defined operations. These are future topics within the course. With these three primitive types and their operations, we can do many mathematical and logical operations. There are also other primitive types that are not needed for this course. They are the byte (for small integers), the short (for integers that are slightly larger than a byte), the long (for very large integers), the float (for decimals with half the precision of a double), and the char (for characters). A string object is an array of chars, so when you make a string, you make an array of different chars combined into one string.

Identifying Data Types Practice

In which data type would you store a student's GPA?
A. int
B. double
C. boolean
D. String
Answer: B. double
If you wanted to store a person's name, which data type would you use?
A. int
B. double
C. boolean
D. String
Answer: D. String
What data type would you use to store a person's age?
A. int
B. double
C. boolean
D. String
Answer: A. int
If you wanted to store a student's enrollment status (enrolled or not enrolled), which data type would you use?
A. int
B. double
C. boolean
D. String
Answer: C. boolean
If you wanted to store a person's phone number, which data type would you use?
A. int
B. double
C. boolean
D. String
Answer: D. String
Confused? The answer is β€œString” because a phone number is a series of characters that represent a phone number, not a numerical value. In programming, we use the data type String to represent sequences of characters, such as words, sentences, or in this case, a phone number. The int data type is used to represent integer values, the double data type is used to represent decimal values, and the boolean data type is used to represent true or false values. None of these data types are suitable for representing a phone number, so the correct answer is D. String.

Variables

Variables are one way to store data in Java and are used again and again in method parameters and different operations as well. To initialize (make) a variable, we do this:
(scope) dataType variableName = dataValue
The special capitalization is called Camel Casing, where the first word is lowercase while the rest are capitalized and combined into one word. Variable and method names use Camel Casing. Class names use a different approach called Pascal Casing, where all words are capitalized. Variable names must follow these rules. The variable name can begin with a letter, underscore (_), or a dollar sign ($). The rest of the characters in the variable name can be letters and numbers. Under standard conventions, variable names are only letters (note that variable names are case sensitive). However, some names cannot be used as they are used for something else in Java (reserved words). Here's a list of them:
https://firebasestorage.googleapis.com/v0/b/fiveable-92889.appspot.com/o/images%2F-wYQ5cYnpZrZ0.jpeg?alt=media&token=24ecf320-2ff2-4d91-964f-9021cb53c487

Courtesy of O’Reilly Media.

When naming your variable, using descriptive variable names are preferred instead of a random name like "d" or "sksksksksksk"." "i" and "j" are allowed variable names that have a specific purpose, but we will cover this later. Also, notice how each variable has its data type. This is called a strongly typed language, more specifically statically typed. This is the opposite of a dynamically typed language, where variables can change partway through.
Examples of legal and illegal variable names:
Good names: iceCreamFlavor, carMake, name Legal, but not preferred: $ball, j, var4 Illegal: nf 23f, &jjjjd, 2fdjjkdk
Here is an example of initializing variables of all of the data types. The equal sign is the assignment operator that assigns/gives a value to the variable.
int daysInWeek = 7; private String name = "Bob"; protected double tax = 0.0775; public boolean goalMet = false;
Note that there are sometimes scope modifiers with the variables, also called access modifiers. If there are no scope or access modifiers, this is called default access, which means the variable is accessible by all classes in that package (also known as a folder in your computer).
Private access is where a variable, class, or method is only available to that own class. We already talked about public access when talking about the main method in 1.1. Finally, protected access with methods, variables, and classes is available to all classes in that package and any subclass as well (we will talk about subclasses in unit 9).
We can also declare the variable without initializing it like this:
private String name; private int age; private double gpa;
Some variables are constants, which means that they never change. We use the final modifier to show this and name the variable in all capitals. Here is how we denote them in Java:
final double TAX;

More Identifying Data Types Practice

These practice problems are similar to the data type questions you would see on the AP CSA exam!
Which of the following pairs of declarations are the most appropriate to store a student's name in the variable name and their age in the variable age?
A. int name; int age;
B. String name; int age;
C. String name; String age;
D. int name; boolean age;
E. String name; boolean age;
Answer: B. String name; int age;
Which of the following pairs of declarations are the most appropriate to store a product's price in the variable price and its quantity in stock in the variable quantity?
A. int price; int quantity;
B. double price; int quantity;
C. double price; double quantity;
D. int price; boolean quantity;
E. double price; boolean quantity;
Answer: B. double price; int quantity;
Which of the following pairs of declarations are the most appropriate to store a person's height in the variable height and their weight in the variable weight?
A. int height; int weight;
B. double height; int weight;
C. double height; double weight;
D. int height; boolean weight;
E. double height; boolean weight;
Answer: C. double height; double weight;
Which of the following pairs of declarations are the most appropriate to store a car's make in the variable make and its model in the variable model?
A. int make; int model;
B. String make; int model;
C. String make; String model;
D. int make; boolean model;
E. String make; boolean model;
Answer: C. String make; String model;
Which of the following pairs of declarations are the most appropriate to store a book's title in the variable title and its author in the variable author?
A. int title; int author;
B. String title; int author;
C. String title; String author;
D. int title; boolean author;
E. String title; boolean author;
Answer: C. String title; String author;

Input Using the Scanner Class

At some point in your AP CSA experience, you are going to have to do input. In Java, there are many ways to do input and you can see them here, but we're going to focus on using the Scanner class.
import java.util.Scanner; public class ScannerTest { public static void main(str[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an integer: "); public int sampleInputInt = input.nextInt(); System.out.print("Enter a double: "); public double sampleInputDouble = input.nextDouble(); System.out.print("Enter a boolean: "); public boolean sampleInputBoolean = input.nextBoolean(); System.out.print("Enter a String: "); public String sampleInputString = input.nextLine(); System.out.print("The string you entered was "); System.out.println(sampleInputString); System.out.print("The integer you entered was "); System.out.println(sampleInputInt); System.out.print("The double you entered was "); System.out.println(sampleInputDouble); System.out.print("The boolean you entered was "); System.out.println(sampleInputBoolean); input.close(); } }
To use the import shown above, you have to follow the following steps:
  1. Import java.util.Scanner because it is not in the basic Java package.
  2. Make a new scanner object that reads from System.in, which is the user input.
  3. For each data type, we ask for a response, which will prompt the user to enter a response, adding the result on the next line.
  • nextInt() gets the next integer
  • nextDouble() gets the next double
  • nextBoolean() gets the next boolean
  • nextLine() gets the next line of text
You can see the scanner method receives data in the snippet above. If you enter the wrong data type, the program will crash, and you have an InputMismatchException. In the final print statement, you can see that we put a variable in the parameter, and it will print the value saved in the variable. After, we close the scanner object before we end the program. Here is an example of the console output with user input in italics.
Enter an integer: *7* Enter a double: *3.14159* Enter a boolean: *true* Enter a String: *Hi.* The string you entered was Hi. The integer you entered was 7 The double you entered was 3.14159 The boolean you entered was true
Note that we can put non-String types into the print statement and converts these to a string. You will learn how in future units.
Browse Study Guides By Unit
πŸ“±Unit 2 – Using Objects
πŸ–₯Unit 3 – Boolean Expressions & if Statements
πŸ•ΉUnit 4 – Iteration
βš™οΈUnit 5 – Writing Classes
⌚️Unit 6 – Array
πŸ’ΎUnit 7 – ArrayList
πŸ’»Unit 8 – 2D Array
πŸ–²Unit 9 – Inheritance
πŸ–±Unit 10 – Recursion
πŸ™Exam Reviews