7 min read•Last Updated on June 18, 2024
Avanish Gupta
user_sophia9212
Avanish Gupta
user_sophia9212
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.
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 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:
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;
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;
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()](https://www.fiveableKeyTerm:nextInt());
System.out.print("Enter a double: ");
public double sampleInputDouble = input.[nextDouble()](https://www.fiveableKeyTerm:nextDouble());
System.out.print("Enter a boolean: ");
public boolean sampleInputBoolean = input.[nextBoolean()](https://www.fiveableKeyTerm: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:
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.
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.
Term 1 of 15
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.
Term 1 of 15
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.
Term 1 of 15
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.
Variables: Variables are used to store and manipulate values in a program. They can be assigned primitive data types or other objects.
Operators: Operators perform operations on operands (values) to produce a result. They can be used with primitive data types for mathematical calculations or logical comparisons.
Constants: Constants are fixed values that cannot be changed during program execution. They can be assigned primitive data types to represent specific values.
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.
Primitive Data Types: These are basic data types that directly store values, such as integers or booleans.
Object: An object is an instance of a class and can have its own set of properties and methods.
Null: Null is a special value that represents the absence of any valid reference. It means that no object is being referred to.
Integer.MIN_VALUE is a constant in Java that represents the smallest possible value for an integer. It is equal to -2^31.
Integer.MAX_VALUE: This constant represents the largest possible value for an integer in Java.
Overflow: Overflow occurs when a calculation or operation results in a value that exceeds the maximum value that can be stored in a data type.
Data Type: In programming, a data type defines what kind of values can be stored and manipulated by variables.
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.
Underflow: Underflow occurs when a calculation results in a value smaller than what can be represented by a given data type.
Integer Division: Integer division refers to dividing two integers and discarding any remainder.
Range Limitations: Range limitations refer to the minimum and maximum values that can be stored by different data types.
A String is a sequence of characters in Java, enclosed in double quotes. It represents text and can be manipulated using various methods.
length(): This method returns the number of characters in a String.
substring(): This method extracts a portion of a String based on specified indices.
equals(): This method compares two Strings for equality and returns true if they are equal.
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.
Pascal Casing: Pascal casing is similar to camel casing, but it capitalizes the first letter of every word, including the first one. For example, instead of writing "studentName," you would write "StudentName."
Reserved Words: Reserved words are specific words that have predefined meanings in programming languages and cannot be used as identifiers (such as variable or function names). Examples include keywords like "if," "while," and "for."
Snake Case: Snake case is another naming convention where words are written in lowercase letters and separated by underscores. For example, instead of writing "studentName," you would write "student_name."
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.
Private Access: This refers to an access modifier that restricts the visibility of a class, method, or variable to only within its own class.
Public Access: This refers to an access modifier that allows unrestricted visibility and accessibility to a class, method, or variable from any part of the program.
Protected Access: This refers to an access modifier that allows visibility within its own package and subclasses outside the package.
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.
Public Access: Allows unrestricted access to members from any class or package.
Private Access: Restricts access to only within the same class.
Default Access: Allows access within the same package but not outside it.
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.
NoSuchElementException: Another exception thrown by methods in the Scanner class when there are no more tokens available for reading.
try-catch block: A programming construct used to handle exceptions. The code within the try block is executed, and if any exceptions occur, they can be caught and handled in the catch block.
parseInt() method: A method provided by the Integer class in Java that converts a string representation of an integer into its corresponding int value.