JIYIK CN >

Current Location:Home > Learning > PROGRAM > Java >

Difference between size and length in Java

Author:JIYIK Last Updated:2025/04/14 Views:

This tutorial explains the difference between size and length in Java. We have also listed some sample codes to help you understand the topic.

Java has a size()method and a lengthproperty. Beginners may think that they are interchangeable and perform the same task because they sound somewhat the same. In Java, size and length are two different things. Here, we will learn about the difference between the two.


Array lengthProperties in Java

Arrays store a fixed number of data of the same type in an ordered manner. All arrays in Java have a length field which is used to store the space allocated for the elements of that array. It is a constant value which is used to find out the maximum capacity of the array.

  • Keep in mind that this field does not give us the number of elements present in the array, but rather the maximum number of elements that can be stored (regardless of whether the elements exist or not).

.lengthExample in Java Array

In the following code, we first initialize an 7array of length . Even though we haven't added any elements, the length field of the array is still displayed 7. This 7simply indicates the maximum capacity.

public class Main {
  public static void main(String[] args) {
    int[] intArr = new int[7];
    System.out.print("Length of the Array is: " + intArr.length);
  }
}

Output:

Length of the Array is: 7

Now, let's add 3 elements to the array using their indices and then print the length field. It still displays 7.

public class Main {
  public static void main(String[] args) {
    int[] intArr = new int[7];
    intArr[0] = 20;
    intArr[1] = 25;
    intArr[2] = 30;
    System.out.print("Length of the Array is: " + intArr.length);
  }
}

Output:

Length of the Array is: 7

The length field is constant because the size of the array is fixed. We have to define the maximum number of elements we will store in the array during initialization (the capacity of the array), and we cannot exceed this limit.


size()Example of methods in Java array

Arrays do not have size()a method; it will return a compilation error. See the example below.

public class SimpleTesting {
  public static void main(String[] args) {
    int[] intArr = new int[7];
    System.out.print("Length of the Array is: " + intArr.size());
  }
}

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Cannot invoke size() on the array type int[]

	at SimpleTesting.main(SimpleTesting.java:7)

length()Find the length using the method in Java

Java strings are just ordered collections of characters, and unlike arrays, they have length()a method instead of lengtha field. This method returns the number of characters present in the string.

Please refer to the following example.

public class Main {
  public static void main(String[] args) {
    String str1 = "This is a string";
    String str2 = "Another String";
    System.out.println("The String is: " + str1);
    System.out.println("The length of the string is: " + str1.length());
    System.out.println("\nThe String is: " + str2);
    System.out.println("The length of the string is: " + str2.length());
  }
}

Output:

The String is: This is a string
The length of the string is: 16

The String is: Another String
The length of the string is: 14

Note that we cannot use the property on strings length, and length()the method does not work on arrays. The following code shows the error we get when we misuse them.

public class SimpleTesting {
  public static void main(String[] args) {
    String str1 = "This is a string";
    System.out.println("The length of the string is: " + str1.length);
  }
}

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	length cannot be resolved or is not a field

	at SimpleTesting.main(SimpleTesting.java:7)

length()Likewise, we cannot use string methods on arrays .

public class SimpleTesting {
  public static void main(String[] args) {
    int[] intArray = {1, 2, 3};
    System.out.println("The length of the string is: " + intArray.length());
  }
}

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Cannot invoke length() on the array type int[]

	at SimpleTesting.main(SimpleTesting.java:7)

Java Collections size()Methods

size()is java.util.Collectionsa method of the class. CollectionsThe class is used by many different collections (or data structures), such as ArrayList, LinkedList, HashSetand HashMap.

size()The method returns the number of elements currently present in the collection. Unlike the array's lengthproperty, size()the value returned by the method is not constant, but varies based on the number of elements.

All collections in Java Collection Frameworkare dynamically allocated, so the number of elements may vary. size()The method is used to keep track of the number of elements.

In the code below, it is clear that when we create a new without any elements ArrayList, size()the method returns 0.

import java.util.ArrayList;
import java.util.List;
public class Main {
  public static void main(String[] args) {
    List<Integer> list = new ArrayList<Integer>();
    System.out.println("The ArrayList is: " + list);
    System.out.println("The size of the ArrayList is: " + list.size());
  }
}

Output:

The ArrayList is: []
The size of the ArrayList is: 0

But this value changes as we add or remove elements. After adding three elements, the size increases to 3. Next, we remove two elements and the size of the list becomes 1.

import java.util.ArrayList;
import java.util.List;
public class Main {
  public static void main(String[] args) {
    List<Integer> list = new ArrayList<Integer>();
    System.out.println("The ArrayList is: " + list);
    System.out.println("The size of the ArrayList is: " + list.size());
    list.add(20);
    list.add(40);
    list.add(60);
    System.out.println("\nAfter adding three new elements:");
    System.out.println("The ArrayList is: " + list);
    System.out.println("The size of the ArrayList is: " + list.size());
    list.remove(0);
    list.remove(1);
    System.out.println("\nAfter removing two elements:");
    System.out.println("The ArrayList is: " + list);
    System.out.println("The size of the ArrayList is: " + list.size());
  }
}

Output:

The ArrayList is: []
The size of the ArrayList is: 0

After adding three new elements:
The ArrayList is: [20, 40, 60]
The size of the ArrayList is: 3

After removing two elements:
The ArrayList is: [40]
The size of the ArrayList is: 1

Difference between size and length in Java

Although size and length can sometimes be used in the same context, they have completely different meanings in Java.

The field of an array lengthis used to represent the maximum capacity of the array. The maximum capacity refers to the maximum number of elements that can be stored in it. This field does not take into account the number of elements present in the array and remains unchanged.

The method of a string length()is used to indicate the number of characters that occur in a string. The method Collections Frameworkof size()is used to see how many elements are currently present in the collection. Collectionshas a dynamic size, so size()the return value of may vary.

Previous:Mutex Locks in Java

Next: None

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Mutex Locks in Java

Publish Date:2025/04/14 Views:198 Category:Java

In the field of computer science, mutual exclusion or mutex is known as the property of concurrency control. Every computer uses a minimum sequence of program instructions called a thread. At a time, the computer works on one thread. For be

How to compare characters for equality in Java

Publish Date:2025/04/14 Views:128 Category:Java

This tutorial shows you how to check if two characters are equal in Java. In Java, we can use the equals( == ) operator or the Character compare() equals() method of the Character class to compare two characters. If you are working with pri

Compile multiple Java files with a single command in Java

Publish Date:2025/04/14 Views:192 Category:Java

This tutorial explains how to compile multiple java files using a single command in Java. Compilation is a term used to refer to the process of converting java source code into bytecode using JDK. To execute any Java file, we need to follow

Arrow operator in Java ->

Publish Date:2025/04/14 Views:113 Category:Java

This tutorial explains - the role of the arrow operator ( ) in Java and lists some sample code to understand the topic. In Java 8, a new feature lambda expression was added, and the arrow operator appeared in Java to form lambda expressions

>> operator in Java

Publish Date:2025/04/14 Views:66 Category:Java

This guide will introduce you to the operator in Java . To understand this concept, you need to be familiar with some lower-level computing concepts. For example, bits, bytes, etc. Let's take a deeper look. Operators in Java In Java, the op

Check if a Post exists in PHP

Publish Date:2025/04/13 Views:170 Category:PHP

PHP $_POST is a super global variable that can contain key-value pairs of HTML form data submitted through the post method. We will learn different ways to check $_POST if a and contains some data in this article. These methods will use iss

Store Div Id in PHP variable and pass it to JavaScript

Publish Date:2025/04/13 Views:51 Category:PHP

This article shows you how to div id store a in a PHP variable and pass it to JavaScript code. We will answer the following questions. What is div id ? How to div id store in a PHP variable? How to pass variables to JavaScript code? Let’s

Resizing images in PHP

Publish Date:2025/04/13 Views:155 Category:PHP

In this tutorial article, we will discuss about resizing images in PHP. Load the image before resizing Before we can resize an image, we must first load it as an image resource in our script. This is file_get_contents() different from using

Creating a signature from Hash_hmac() and Sha256 in PHP

Publish Date:2025/04/13 Views:108 Category:PHP

PHP has one of the best encryption functions for data security. Hash_hmac() The encrypt function is one of the most famous encryptors. We'll show you how to use hash_hmac and sha256 encryptors to create 安全签名 one that you can store i

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial