×

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

Related Topics

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

Java Math decrementExact() Method

The decrementExact() method of Math class returns the argument which is decremented by one, throwing an exception is the result overflows an int or long. Syntax: public static int decrementExact (int a) Parameters: The...

1 minute read.

Java For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

4 minutes read.

Why to use Enum in Java?

In this article, you will be acknowledged about the Enum in java, its uses and mainly its purpose. Enum has various functionalities. Each of them will be discussed. Enum In a computer...

3 minutes read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

Java Try Keyword

The try block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java try block has...

3 minutes read.

Can we override Private Method in Java

In this article we will learn the concept of override, private method in java and we will now whether we can override private method in java or not. Override in Java Any...

3 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

Memory Areas in Java

Let’s have a look at how memory management in Java works. We will be going to discuss how the objects get destroyed, the working of a garbage collector, and things...

5 minutes read.

Longest Arithmetic Progression Sequence in Java

The task is to find the length of the largest sequence in an array to form an arithmetic progression. The array arr[] is given. Longest Arithmetic Progression Sequence in Java Algorithm set...

5 minutes read.

How to Convert long to String in Java

How to Convert long to String in java It is used if we have to display a long number in the text field because everything is displayed as a String. A...

3 minutes read.

Java Speech Recognition

The customer experience and convenience are improved with its utilization. Command and control interest in buying and voice synthesizers are supported by the cross-platform API defined by the API. For...

4 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

How to download Eclipse for Java

Introduction: We write a java program, and when we want to run it, we need software to run it. Eclipse is a kind of software used to execute a JavaFX...

3 minutes read.

Java Read File

Java provides its users with many ways of reading a file. To read a text file, you can use a FileReader, BufferedReader, or Scanner. Each utility offers something special for...

6 minutes read.

Timestamp Operation in Java

JDBC escape syntax is supported by Timestamp's formatting and parsing functions. Additionally, it adds support for fractional seconds values for SQL TIMESTAMP.java.util.Date is wrapped in a lightweight wrapper that enables...

3 minutes read.

Java Thread class

Thread class The thread represents a part of the process. Every process can have multiple associated threads in which every thread may execute the same or different job. By default, each thread assigns...

16 minutes read.