Fiveable
Fiveable

or

Log in

Find what you need to study


Light

Find what you need to study

1.2 Variables and Primitive Data Types

8 min readdecember 26, 2022

Athena_Codes

Athena_Codes

user_sophia9212

user_sophia9212

Athena_Codes

Athena_Codes

user_sophia9212

user_sophia9212

Variables and Data Types

Primitive Data Types

In Java, everything is either one of several or combinations of these (collections and objects). These combinations of are called . 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 . Entering an integer outside this range results in an integer and automatically converts it to Integer.MAX_VALUE if it’s too high and 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 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 object is an array of chars, so when you make a , you make an array of different chars combined into one .

Identifying Data Types Practice

In which data type would you store a student's GPA?

A. int

B. double

C. boolean

D.

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.

Answer: D.

What data type would you use to store a person's age?

A. int

B. double

C. boolean

D.

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.

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.

Answer: D.

Confused? The answer is “” 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 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. .

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 , where the first word is lowercase while the rest are capitalized and combined into one word. Variable and method names use . 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 

Note that there are sometimes scope modifiers with the variables, also called . If there are no scope or , 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, 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 

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. name; int age;

C. name; age;

D. int name; boolean age;

E. name; boolean age;

Answer: B. 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. make; int model;

C. make; model;

D. int make; boolean model;

E. make; boolean model;

Answer: C. make; 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. title; int author;

C. title; author;

D. int title; boolean author;

E. title; boolean author;

Answer: C. title; 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 

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 . 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 

Note that we can put non- types into the print statement and converts these to a . You will learn how in future units.

Key Terms to Review (15)

Access Modifiers

: Access modifiers are keywords in programming that determine the accessibility of classes, methods, and variables. They control whether other parts of the program can access and use these elements.

Camel Casing

: Camel casing is a naming convention where each word in a compound identifier is capitalized except for the first word, which starts with a lowercase letter. It is commonly used in programming languages to make variable and function names more readable.

Data Type Declaration

: A data type declaration specifies the type of data that a variable can hold in a programming language. It defines what kind of values can be stored and how those values can be manipulated.

Final Modifier

: The final modifier is used in programming languages to indicate that a variable cannot be changed once it has been assigned a value or that a method cannot be overridden by subclasses.

InputMismatchException

: An InputMismatchException is an exception that occurs when the input provided by the user does not match the expected data type or format. It is commonly thrown by methods in the Scanner class when trying to read a value of one type but encountering a different type.

Integer.MIN_VALUE

: Integer.MIN_VALUE is a constant in Java that represents the smallest possible value for an integer. It is equal to -2^31.

Key Term: Array of chars

: An array of chars is a data structure that stores a sequence of characters. It is often used to represent strings in programming.

nextBoolean()

: The nextBoolean() method is used in Java to read the next boolean value from the input source. It retrieves and returns the next boolean token as a boolean data type (either true or false).

nextDouble()

: The nextDouble() method is used in Java to read the next floating-point (decimal) value from the input source. It retrieves and returns the next double token as a double data type.

nextInt()

: The nextInt() method is used in Java to read the next integer value from the input source. It retrieves and returns the next integer token as an int data type.

Overflow

: Overflow occurs when a calculation exceeds the maximum value that can be represented by a given data type. This can result in unexpected behavior or errors in programs.

Primitive data types

: Primitive data types are basic data types that are built into a programming language and represent simple values. They include integers, floating-point numbers, characters, booleans, and more.

Protected Access

: Protected access is a level of access control in object-oriented programming that allows members (variables and methods) to be accessed within the same class, subclasses, and classes in the same package.

Reference Data Types

: Reference data types are data types that store references or memory addresses of objects rather than the actual values. They point to the location in memory where the object is stored.

String

: A String is a sequence of characters in Java, enclosed in double quotes. It represents text and can be manipulated using various methods.

1.2 Variables and Primitive Data Types

8 min readdecember 26, 2022

Athena_Codes

Athena_Codes

user_sophia9212

user_sophia9212

Athena_Codes

Athena_Codes

user_sophia9212

user_sophia9212

Variables and Data Types

Primitive Data Types

In Java, everything is either one of several or combinations of these (collections and objects). These combinations of are called . 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 . Entering an integer outside this range results in an integer and automatically converts it to Integer.MAX_VALUE if it’s too high and 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 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 object is an array of chars, so when you make a , you make an array of different chars combined into one .

Identifying Data Types Practice

In which data type would you store a student's GPA?

A. int

B. double

C. boolean

D.

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.

Answer: D.

What data type would you use to store a person's age?

A. int

B. double

C. boolean

D.

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.

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.

Answer: D.

Confused? The answer is “” 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 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. .

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 , where the first word is lowercase while the rest are capitalized and combined into one word. Variable and method names use . 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 

Note that there are sometimes scope modifiers with the variables, also called . If there are no scope or , 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, 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 

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. name; int age;

C. name; age;

D. int name; boolean age;

E. name; boolean age;

Answer: B. 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. make; int model;

C. make; model;

D. int make; boolean model;

E. make; boolean model;

Answer: C. make; 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. title; int author;

C. title; author;

D. int title; boolean author;

E. title; boolean author;

Answer: C. title; 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 

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 . 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 

Note that we can put non- types into the print statement and converts these to a . You will learn how in future units.

Key Terms to Review (15)

Access Modifiers

: Access modifiers are keywords in programming that determine the accessibility of classes, methods, and variables. They control whether other parts of the program can access and use these elements.

Camel Casing

: Camel casing is a naming convention where each word in a compound identifier is capitalized except for the first word, which starts with a lowercase letter. It is commonly used in programming languages to make variable and function names more readable.

Data Type Declaration

: A data type declaration specifies the type of data that a variable can hold in a programming language. It defines what kind of values can be stored and how those values can be manipulated.

Final Modifier

: The final modifier is used in programming languages to indicate that a variable cannot be changed once it has been assigned a value or that a method cannot be overridden by subclasses.

InputMismatchException

: An InputMismatchException is an exception that occurs when the input provided by the user does not match the expected data type or format. It is commonly thrown by methods in the Scanner class when trying to read a value of one type but encountering a different type.

Integer.MIN_VALUE

: Integer.MIN_VALUE is a constant in Java that represents the smallest possible value for an integer. It is equal to -2^31.

Key Term: Array of chars

: An array of chars is a data structure that stores a sequence of characters. It is often used to represent strings in programming.

nextBoolean()

: The nextBoolean() method is used in Java to read the next boolean value from the input source. It retrieves and returns the next boolean token as a boolean data type (either true or false).

nextDouble()

: The nextDouble() method is used in Java to read the next floating-point (decimal) value from the input source. It retrieves and returns the next double token as a double data type.

nextInt()

: The nextInt() method is used in Java to read the next integer value from the input source. It retrieves and returns the next integer token as an int data type.

Overflow

: Overflow occurs when a calculation exceeds the maximum value that can be represented by a given data type. This can result in unexpected behavior or errors in programs.

Primitive data types

: Primitive data types are basic data types that are built into a programming language and represent simple values. They include integers, floating-point numbers, characters, booleans, and more.

Protected Access

: Protected access is a level of access control in object-oriented programming that allows members (variables and methods) to be accessed within the same class, subclasses, and classes in the same package.

Reference Data Types

: Reference data types are data types that store references or memory addresses of objects rather than the actual values. They point to the location in memory where the object is stored.

String

: A String is a sequence of characters in Java, enclosed in double quotes. It represents text and can be manipulated using various methods.


© 2024 Fiveable Inc. All rights reserved.

AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.


© 2024 Fiveable Inc. All rights reserved.

AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.