Unit 1: Primitive Data Types
Variables in Java
Introduction to Variables in Java
Definition
Variables in Java are symbolic names for storage areas that can hold data. They are foundational in programming, enabling data manipulation and logic implementation in applications. Variables are declared with a data type and a name, and they can be initialized with a value at the time of declaration or assigned a value later in the code.
Importance of Variables
Variables are essential in programming, enabling data storage and manipulation, and logic implementation in applications. They are foundational in Java and other programming languages, and understanding their types, declaration, initialization, and assignment is crucial for developers.
Variable Types
Primitive Data Types
Primitive data types are the most basic data types in Java and include byte, short, int, long, float, double, boolean, and char. String is often included in primitive data types, but it is a special data type that is treated as a primitive data type in Java.
byte
Range(-128 to 127)
The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.
short
Range(-32,768 to 32,767)
The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.
int
Range(-2,147,483,648 to 2,147,483,647)
The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For int literals, you can also use the hexadecimal, octal, or binary number systems, as shown in the following example:
// A variable with the type of int and a value of 4352
int iAmAnIntVariables = 4352;
long
Range(-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int. A capital L is used to indicate that the variable should be stored as a long, as shown in the following example:
// A variable with the type of long and a value of 9,223,372,036,854,775,807
long iAmALongVariable = 9,223,372,036,854,775,807L;
float
Range(3.4e−038 to 3.4e+038)
The float data type is a single-precision 32-bit IEEE 754 floating-point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating-point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.
// A variable with the type of float and a value of 3.4e+038
float iAmAFloatVariable = 3.4e+038f;
double
Range(1.7e−308 to 1.7e+308)
The double data type is a double-precision 64-bit IEEE 754 floating-point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
// A variable with the type of double and a value of 1.43
double iAmADoubleVariable = 1.43;
boolean
Values(true or false)
The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
// A variable with the type of boolean and a value of true
boolean iAmABooleanVariable = true;
char
Range('\u0000' to '\uffff' or 0 to 65,535)
The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
// A variable with the type of char and a value of 'A'
char iAmACharVariable = 'A';
String
Range(0 to 2^31 - 1) or (0 to 2,147,483,647)
The String is listed under primitive and reference data types because it is the most used data type in Java and is a special data type that is treated as a primitive data type in Java. A String is a sequence of characters. In Java, objects of String are immutable, which means a constant and cannot be changed once created.
// A variable with the type of String and a value of "NerdBrainz is here to help!"
String iAmAStringVariable = "NerdBrainz is here to help!";
Reference Data Types
Reference data types are used to reference memory locations and can be used to store the location of data rather than the data itself. Reference data types include String, Array, Classes, and Interfaces.
String
As referenced above, the String is listed under primitive and reference data types because it is the most used data type in Java and is a special data type that is treated as a primitive data type in Java. A String is a sequence of characters. In Java, objects of String are immutable, which means a constant and cannot be changed once created. The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use StringBuffer & StringBuilder Classes.
// A variable with the type of String and a value of "NerdBrainz is here to help!"
String iAmAStringVariable = "NerdBrainz is here to help!";
Array
An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++. Following are some important point about Java arrays.
In Java all arrays are dynamically allocated.
Since arrays are objects in Java, we can find their length using the object property length. This is different from C/C++ where we find length using sizeof.
A Java array variable can also be declared like other variables with [] after the data type.
// declaring array int[] arr;
Classes
A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order:
Modifiers: A class can be public or has default access (Refer this for details).
Class name: The name should begin with a initial letter (capitalized by convention).
// declaring class public class MyClass { // class body }
Variables Types in Java
In Java, there are three types of variables:
- local
- instance
- static
Local variables
Local variables are defined inside methods, constructors, or blocks and are only accessible within their defined area. Local variables are created when the method, constructor, or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
public class MyClass {
public static void main(String[] args) {
// Create a variable inside the method. It can only be used inside the method.
int x = 5;
System.out.println(x);
}
}
Instance variables
Instance variables are declared in a class, but outside a method, constructor, or any block. When a space is allocated for an object in the heap, a slot for each instance variable value is created. Instance variables are created when an object is created with the use of the keyword new and destroyed when the object is destroyed.
public class MyClass {
// Instance variable
int x = 5;
public static void main(String[] args) {
MyClass myObj = new MyClass();
System.out.println(myObj.x);
}
}
Static variables
Static variables are declared similarly as instance variables, the difference is that static variables are declared using the keyword static. Static variables are created when the program starts and destroyed when the program stops.
public class MyClass {
// Static variable
static int x = 5;
public static void main(String[] args) {
MyClass myObj1 = new MyClass(); // Object 1
MyClass myObj2 = new MyClass(); // Object 2
myObj1.x = 25;
myObj2.x = 35;
System.out.println(myObj1.x); // Outputs 35
System.out.println(myObj2.x); // Outputs 35
}
}
Scope
Variable Scope
The scope of a variable is the part of the program where the variable is accessible. Variables have only one scope, which is defined by where they are declared. The scope of a variable starts from the point where it is declared and lasts until the end of the block containing the declaration. For example, if a variable is declared in a method, it can be used anywhere within the method's body.
public class MyClass {
public static void main(String[] args) {
// Code here cannot use x
int x = 100;
// Code here can use x
System.out.println(x);
}
}
Variable Naming Conventions
Naming Conventions in Java
Naming conventions make code more readable and understandable for developers. In Java, there are some naming conventions to follow when naming variables. These conventions are:
- Variable names should start with a letter, $, or _.
- Variable names cannot start with a number.
- Variable names are case sensitive (myVar and myvar are different variables).
- Variable names should not be Java keywords.
Camel Case
When naming variables, it is common to use camel case. This means the first word is all lowercase, and then every word after that has its first letter capitalized.
// Camel case
int myNum = 5;
Pascal Case
Another common convention is Pascal case. This means the first letter of each word is capitalized.
// Pascal case
int MyNum = 5;
Variable Declaration
Declaring Variables
int myNum = 3;
float myFloatNum = 6.99f;
char myLetter = 'E';
boolean myBool = false;
String myText = "NerdBrainz is here to help!";
Variables are declared with a data type and a name, and they can be initialized with a value at the time of declaration or assigned a value later in the code.
// Variable declaration
int x;
Variable Initialization
Variables can be initialized with a value at the time of declaration or assigned a value later in the code.
// Variable initialization
int x = 5;
Variable Assignment
Variables can be assigned a value later in the code.
// Variable assignment
int x;
x = 5;
Summary
Variables are essential in programming, enabling data storage and manipulation, and logic implementation in applications. They are foundational in Java and other programming languages, and understanding their types, declaration, initialization, and assignment is crucial for developers.
References
AP CSA Homework Assignment
Assignment
Instructions
Create a new project and practice declaring and initializing variables of each primitive data type. Print each variable to the console.
- Create a new Java project called Variables
- Create a new Java class called Variables
- Create a main method
- Create a variable for each primitive data type
- Print each variable to the console
- Create a variable for each reference data type
- Print each variable to the console
- Create a variable for each primitive data type and initialize it with a value
- Print each variable to the console