×

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

Why we use static in Java

Many reserved keywords in Java cannot be used as variable names or identifiers. Java uses static keywords frequently because of its effective memory management system. In most cases, you must...

3 minutes read.

Vector in Java

Java Vector Class The Vector class is a legacy class that implements a growable array of objects. The components that it contains can be accessed using an integer index. The size of...

26 minutes read.

Java Numbers

We use primitive data types like byte, int, long, double, etc to work with the numbers, When we need objects, we use wrapper class like Integer, Double, Long, Byte, etc....

2 minutes read.

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

How to Read XML Files in Java?

Introduction Today, we are going to learn about how to read XML files in java. Before, reading the XML Files let us learn about XML. XML Files The full form of XML is...

8 minutes read.

Dangling Else problem in Java

A language interpretation uncertainty is the hanging other issue. The following two types of condition executed code are both possible in programming: 1. if-then-else form 2. if-then form When dealing with the nested...

3 minutes read.

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

3N+1 problem program in Java

The 3N+1 problem is a hypothesis in the field of abstract mathematics (not yet proven). Collectively known as the Collatz problem. This tutorial will describe about the 3N+1 problem and...

3 minutes read.

Best Java Libraries

One of the most widely used programming languages is Java. Java has a large number of libraries, including the standard Java library that includes libraries such as java.lang, java.util, and...

7 minutes read.

Java StringReader Class

StreamReader Class technique enables character reading from a string. The java.io package contains this class. A string serves as a source in the character stream. While the Stream class is...

4 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.

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

Least Operator to Express Number in Java

In this article, we will learn about how to obtain a target number using a single number or a single integer by leveraging least operators in Java. There can be...

3 minutes read.

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Java Case Keyword

Case keyword: In this article we are going to learn the concept of a java case keyword.Generally, java case keyword is used with the switch statements.Case keyword is implemented in conditional...

3 minutes read.

Find the Frequency of Each Element in the Array in Java

We may count the occurrence of each element in the array of items. Maintaining one array to store the counts of each array element is one strategy for solving this issue....

3 minutes read.

Program to find and replace characters on string in java

In JAVA, Strings are immutable. To overcome this Java String class contains a lot of methods to do operations on Strings. One such method is replace method. String Replace It returns a...

3 minutes read.

How to run java program in ubuntu

To run the java programming in ubuntu, we need to follow several steps: Let's see the process. Step1: Install the Java compiler or JDK to the system. To run the java program, we...

3 minutes read.