Array and String with Examples in Java
Array in Java:
An array in Java is a group of variables with similar types that have a common name. The arrays used in Java differ from those used in C/C++.
Key points
- Java uses dynamically allocated arrays extensively.
- Arrays are objects in the Java programming language, and the object attribute length may be used to estimate their length ().
- The array's variables are ordered, and each variable's index starts at 0.
- A Java array can be used with a static field, a local variable, or a method parameter.
- The Cloneable and java.io interfaces are implemented by each array type that may be serialized.
- The immediate superclass of the common array type is Object.
- Object (or non-primitive) class references and basic data types like int and char can both be stored in arrays. The common values of fundamental data kinds are stored in adjacent memory regions. The original objects for class objects are stored in a heap region.
One Dimensional Array:
Normal declaration of one dimensional array is
type var-name[];
OR
type[] var-name;
The type and name of an array can both be specified separately. The word "type" denotes the nature of the elements in the array. The element type determines the data type for each array element. We may construct an array of numerous primitive data types, including char, float, double, and so on, as well as user-defined data types, in a manner similar to how we would generate an array of integers (objects of a class). As a result, the element type of an array determines the kind of data that it may include. Making an Array Instantiate:
Only a reference to an array is produced when it is defined.
An array must first be made in the way described below in order to produce data from it or add memory to it.
The following is how new is expressed for one-dimensional arrays:
var-name = new type [size];
The array's size is determined by the number of elements, the kind of data being allocated, and var-name, the name of the array variable connected to the array. You must provide the type and quantity of the elements to be allocated when allocating an array using new.
Declaring an Array>> int intArray[];
Allocating memory to Array>> intArray = new int[20];
Point to Remember:
When new allocates an array, its default values are 0 for numeric types, false for boolean types, or null for all other types (for reference types). Use Java's default array values.
Getting an array requires a two-step process. Make a variable of the necessary array type first. Use new and then assign it to the array variable to create a memory for the array. Java employs dynamic allocation for all arrays as a result.
Array Literal:
Array literals can be utilized when the array's size and its variables are known.
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
The length of this array defines the length of the newly constructed array, which need not be written in Java's most current iterations.
Array program using for loop
class TAE{
public static void main (String[] args){
// declares an Array
int[] arr;
// allocating memory
arr = new int[5];
// initialize the first element of an array
arr[0] = 5;
// initialize the second element of an array
arr[1] = 10;
//so on...
arr[2] = 15;
arr[3] = 20;
arr[4] = 25;
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i +" : "+arr[i]);
}
}
Output:
Element at index 0 : 5
Element at index 1 : 10
Element at index 2 : 15
Element at index 3 : 20
Element at index 4 : 25
Arrays of Object:
Student[] arr = new Student[5]; //student is a user-defined class
Each of the five memory spaces in the studentArray, one for each student class, may store the addresses of five Student objects. The Student class's Object() function must be used to construct the Student objects, and the references to those objects must be allocated to the elements of the array as shown below.
Student[] arr = new Student[5];
class Student{
public int roll_no;
public String name;
Student(int roll_no, String name){
this.roll_no = roll_no;
this.name = name;}
}
// Elements of the array
public class TAE{
public static void main (String[] args){
// declares an Array
Student[] arr;
// allocating memory
arr = new Student[5];
// initializing first element
arr[0] = new Student(1,"Ajay");
// initializing second element
arr[1] = new Student(2,"Kaishav");
// so on...
arr[2] = new Student(3,"Rakesh");
arr[3] = new Student(4,"Zaid");
arr[4] = new Student(5,"Kasim");
// accessing the elements of specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at " + i + " : " +
arr[i].roll_no +" "+ arr[i].name);
}
}
Output:
Element at 0 : 1 Ajay
Element at 1 : 2 Kaishav
Element at 2 : 3 Rakesh
Element at 3 : 4 Zaid
Element at 4 : 5 Kasim
String in Java
Strings are a collection of characters that are often used in Java programming. In Java, strings are referred to as objects.
The Java platform class "String" allows you to create and manage strings.
A null and empty string in Java:-
NULL STRING:- The term "Null String" refers to a string that is empty.
Java allows us to use null strings in the following ways:
Empty String: When the null is assigned to the string variable, the attribute has no connection to any heap memory address.
NOTHING STRING
An empty string is a string type with no characters and a clearly specified length of zero. On an empty string, we may do all string operations.
Blank String
String#trim can be used to identify blank strings if we also wish to do that. Any leading and trailing whitespaces will be eliminated before running the check.
Java allows us to use empty strings in the following ways:
String x = "";
The string "x" is empty in this case. When we give an attribute to the string variable, the empty string indicates that the attribute corresponds to a memory location of a string in a clump.
Ways to determine whether a string is empty or null
Calculating string length:
The length () function of the String class is referred to in the Empty () method. We can use the length () method in place of the is Empty () method as Java 6 and earlier don't support it:
public class IsEmpty{
public static void main(String args[]){
String s1=””;
String s2=”helloworld”;
String s3=”star”;
System.out.println(s1.isEmpty()); // Command to print
System.out.println(s2.isEmpty());
System.out.println(s3.isEmpty());
}}
// It gives true when the length is zero otherwise it throws false
Output:
True
False
False
String Equals Method:
class Main
{
private static String EMPTY = ""; // Empty class
public static void main(String[] args)
{
String str = ""; //Empty Class
System.out.println(str == null || str.equals(EMPTY));
System.out.println(str == null || EMPTY.equals(str));
}
}
Output
True
True
Guava Library Method:
If the supplied string is empty or null, the static utility function isNullOrEmpty(String) in Guava's Strings class returns true.
class Main
{
public static void main(String[] args)
{
System.out.println(Strings.isNullOrEmpty("")); //empty class
System.out.println(Strings.isNullOrEmpty(null)); //null class
System.out.println(Strings.isNullOrEmpty("Hello"));
}
}
Output
True
True
False
Empty Method: Starting with Java 7, it is advised to use the String.isEmpty() function to determine whether a string is empty. To prevent a NullPointerException, a null verification should come before the method call if the string is null.
class Main{
public static void main(String[] args)
{
String str = ""; //Empty string
System.out.println(str == null || str.isEmpty());
}
}
OUTPUT:
True
Apache:
The Apache Commons Lang library's StringUtils.isEmpty(String) function determines whether a string is empty or null. Additionally, it has a function that searches for whitespace called StringUtils.isBlank(String).
class Main{
public static void main(String[] args)
{
System.out.println(StringUtils.isEmpty("")); // Empty
System.out.println(StringUtils.isEmpty(null)); // Null
System.out.println(StringUtils.isEmpty("Java")); // String
System.out.println(StringUtils.isBlank(" ")); // Blank
}
}
OUTPUT:
True
True
False
True