- cannot store the value of a variable directly in memory.
- stores a reference or address (memory location) of value.
- Strings, Arrays, Objects, Classes, Interfaces
| Type | Storage (byte) | Range ( Inclusive ) | specifier | Default value |
|---|---|---|---|---|
| Reference types | null |
- The String data type is used to store a sequence or array of characters (text). But in Java, a string is an object that represents an array or sequence of characters.
- The java.lang.String is the class is used for creating a string object.
- String literals should be enclosed within double-quotes. The difference between a character array and a string is that in the string a special character ‘\0’ is present
String <String_variable_name> = “<sequence_of_strings>"
Two ways of creating string:
- using string literal
String myString = “Hello World” - using new keyword
String myLine = **new** String(“Hello World!!!”);
- An Array in Java is a single object which can store multiple values of the same data type.
- Arrays are homogeneous data structures that store one or more values of a specific data type and provide indexes to access them.
- A particular element in an array can be accessed by its index.
Two steps in creating arrays:
-
Array Declaration:
data-type array_name [ ];ordata-type[ ] array_name; -
Array Initialization:
array_name = **new** data-type [size **of** array];orarray_name = **new** data-type[] {comma seperated values};
Example:
// Declaration
int daysInMonth[];
char[] lettersInSentence;
// Initialization
daysInMonth = new int[100];
lettersInSentence = new char[] {'b','c','d','e'};
// declaration and initialization in same lie
int[] arr = {1,2,3,4,5};
int[] arr1 = new int[]{1,2,3,4,5,6};
// Two dimensional array
double[][] a = new double[m][n];
System.out.println(daysInMonth.length); // array length
// array copying
int[] primes = { 7, 11, 5, 2, 3};
int[] primesCopy = Arrays.copyOf(primes, primes.length);
int[] luckyNums = {350, 400, 150, 200, 250};
System.arraycopy(primes, 1, luckyNums, 3, 2); // [350, 400, 150, 11, 5]Multidimensional arrays: The same notation extends to arrays that have any number of dimensions. For instance, we can declare and initialize a three-dimensional array with the code
double[][][] a = new double[n][n][n];Ragged arrays: There is no requirement that all rows in a two-dimensional array have the same length—an array with rows of nonuniform length is known as a ragged array. The possibility of ragged arrays creates the need for more care in crafting array-processing code.
int[][] arr = new int[3][];
arr[0] = new int[2];
arr[1] = new int[3];
arr[2] = new int[5];