×

Maximum length of string in java

In java, String can act as a data type and a class. The string can be defined as the collection of characters that are enclosed with double quotes(“ “). The string class consists of characters. String can’t be changed if it is created. The objects of the string can’t be changed because they are immutable.

Example :

String s=“Increase”;

String s can be converted into character array as

char ch[]={‘I’,’n’,’c’,’r’,’e’,’ a’,’s’,’e’};

String s =new String(ch);

In the above example, the String class has the length() method, which is used to find the length of the string. For finding the length of the string, there is the length() method.

The length () method returns the length of the string, which is an integer data type. This method counts the number of characters in the string.

Java uses UTF-16 for the representation of the character. Each character occupies two bytes.

The size of int is 4 bytes. The range of integers is -2^31 to 2^31-1. This means (-2147483648 to 2147483647) accepts this range; we can’t be able to store the 2147483647th character. Hence maximum length should be from 0 to 2147483647.

We can find the maximum length using the java program.

Example

import java.util.Arrays;  
public class MaximumSize   
{  
public static void main(String args[])   
{  
for (int i = 0; i < 1000; i++)   
{  
try   
{  
//Integer.max value stores maximum value of the string 
char[] array = new char[Integer.MAX_VALUE - i];  
//specific value is arranged to each datatype  
Arrays.fill(array, 'a');  
//Constructor is created for String class ang passing array as an argument
String str = new String(array);  
//prints the string length  
System.out.println(str.length());  
}   
catch (Throwable e)   
{  
// throws a message  
System.out.println(e.getMessage());  
//returns the maximum value of string
System.out.println("Max: " + (Integer.MAX_VALUE - i));  
System.out.println("Max: " + i);  
}  
}  
}  
} 

Output

Maximum Length Of String In Java

As the output, for example, users can run 1000 times. In the exception occurring block

An array of integers.MAX_VAlue-i. After that, we used the fill method to use the Array class.

The fill method assigns a particular data type value for each array element.

In the example, the program catch block is used to throw an exception caught in the try block. The getMessage() method in the catch block throws an exception.

Each character in Java stores two bytes of memory because strings can be stored as UTF-16 codes. We need twice the memory for storing old and new strings to add strings.

If we insert the strings more than their size, the memory will overflow, and we get a negative result. Consider an example for extending the string beyond the limit.

//Program for beyond the size

public class SizeBeyondLimit  
{   
public static void main(String[] arg)   
{   
try   
{   
System.out.println( "Trying to initialize" + " a n with value" + " Integer.MAX_VALUE + 1");   
// to store maximum integer value  
int n = Integer.MAX_VALUE + 1;   
 // preturn the result as negative num as size exceeded 
System.out.println("n = " + n);   
}   
catch(Exception e)   //used for handling the exception
{   
System.out.println(e);   
}   
}   
}  

Output

Maximum Length Of String In Java

From the output of the above program, we can see that it was printed as a negative integer.

Because of exceeding the actual size of the String.


Related Topics

Java Integer parseUnsignedInt() method

The parseUnsignedInt() method of Java Integer class parses the string argument as an unsigned decimal integer. The second parameter parses the string argument as an unsigned integer in the radix specified...

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

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

Display Unique Rows in a Binary Matrix in Java

To solve this problem, we must first locate and display the distinct rows of a supplied binary matrix afterward. We will go through how to show distinct rows inside a...

12 minutes read.

Java Implements Keyword

To understand about the keyword implements we need to learn about the concept of the interfaces and inheritance in java programming languages. So let us learn about the interface and...

3 minutes read.

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a...

5 minutes read.

Java Get Time in UTC

UTC is the abbreviation for Universal Time Coordinated. Before the beginning of UTC, it is mentioned as the Greenwich Mean Time (GMT) but Now it is mentioned as the universal...

4 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

Normal and Trace of a Matrix in Java

Normal of a matrix The square root of the total squares of each element in a matrix is known as the matrix's normal. Think of the following matrix as an example. Example: [[1,2,3]  ...

3 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Java Static Keyword

It can be either said that static declares the value to be the same, not only in the instance of a class but also as the whole. To declare a variable...

6 minutes read.

Powerful Number in Java

We will define a powerful number in this article and write Java programs to determine whether a given number is a powerful number or not. Java coding interviews and academic...

6 minutes read.

Matrix Multiplication in Java

In Java, using the binary operator (*) we can perform matrix multiplication. A Matrix is a group of arrays. In the multiplication of matrices, the elements of each row are...

3 minutes read.

How to Iterate a HashMap in Java?

Hash-map is a class of Java collections framework which has the functionality to implement the Map interface of Java. It stores the data in key-value pairs and can be accessed...

5 minutes read.

Minimum Lights to Activate Java Snippet Class

Minimum Lights to Activate Problem in Java In prison, there is a hallway that is N units long. Given an N-dimensional array A. If the light at the ith position is...

3 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.