sodcalculator

10 Tech How-To

Print Array Length in JS, Java & C++

Guide 10-50916 · Updated · Step by step

This guide shows you how to get and print the number of elements in an array using three popular languages: JavaScript, Java, and C++. You’ll learn the exact syntax for each language, along with common pitfalls and how to avoid them. No prior knowledge beyond basic array creation is needed.

What You’ll Need

  • A code editor or IDE (e.g., VS Code, IntelliJ, Eclipse, or even a simple text editor)
  • For JavaScript: Node.js installed, or just use your browser’s developer console
  • For Java: JDK (Java Development Kit) installed
  • For C++: A C++ compiler like g++ (often comes with MinGW on Windows, Xcode on Mac, or gcc on Linux)

Step-by-Step

JavaScript

  1. Create an array. For example: let fruits = ['apple', 'banana', 'orange'];
  2. Access the length property. In JavaScript, arrays have a built-in length property that returns the number of elements. It’s a property, not a method, so no parentheses are needed.
  3. Print it. Use console.log(fruits.length); to output the number to the console. You can also combine it with a string: console.log('Number of fruits: ' + fruits.length);
  4. Run the code. If using Node.js, save the file as script.js and run node script.js in your terminal. In a browser, paste the code into the console and press Enter.

Java

  1. Create an array. For example: int[] numbers = {10, 20, 30, 40}; or String[] names = new String[3];
  2. Access the length field. In Java, arrays have a public final field called length. It’s a field, not a method, so no parentheses.
  3. Print it. Use System.out.println(numbers.length); or with a message: System.out.println("Array length: " + numbers.length);
  4. Run the code. Save the file as Main.java (class name must match), compile with javac Main.java, and run with java Main.

C++

  1. Include the necessary header. Add #include <iostream> at the top of your file for input/output.
  2. Create an array. For example: int numbers[] = {5, 10, 15, 20, 25};
  3. Calculate the length. Unlike JavaScript and Java, C++ arrays do not have a built-in length property. You must compute it using the sizeof operator: int length = sizeof(numbers) / sizeof(numbers[0]);
  4. Print it. Use std::cout << length << std::endl; or with a message: std::cout << "Array length: " << length << std::endl;
  5. Run the code. Save the file as main.cpp, compile with g++ main.cpp -o program, and run with ./program (on Windows, program.exe).

Common Mistakes

  • Using parentheses after length in JavaScript or Java. It’s a property/field, not a method. fruits.length() will cause an error.
  • Forgetting the sizeof division in C++. Using just sizeof(numbers) gives the total bytes, not the number of elements. Always divide by the size of one element.
  • Using length() for strings vs. arrays in Java. Strings have a length() method, but arrays have a length field. Mixing them up is a common compile error.
  • Modifying the array after creation. In JavaScript, the length updates automatically. In Java and C++ (static arrays), the length is fixed at creation and cannot change.

Tips

  • Use a loop to iterate. Knowing the length is essential for looping through an array. For example, in JavaScript: for (let i = 0; i < fruits.length; i++).
  • In C++, prefer std::array or std::vector for modern code. These have a .size() method, which is safer and more readable. For example: std::vector<int> v = {1,2,3}; std::cout << v.size();
  • In JavaScript, use Array.isArray() to check if a variable is an array before accessing length. This avoids errors when the variable might be undefined or not an array.
  • In Java, use the enhanced for-loop when you don’t need the index. It’s cleaner: for (int num : numbers) { ... }

Troubleshooting

  • Compile error: ‘length’ cannot be resolved (Java) or ‘length’ is not a member (C++). Double-check that you are using an array, not a collection like ArrayList (which uses .size()) or a string (which uses .length() in Java).
  • Output is 0 or a huge number in C++. This usually means you are using sizeof on a pointer, not the array itself. When you pass an array to a function, it decays to a pointer, so you lose the size. Pass the size as a separate parameter, or use std::vector.
  • JavaScript says ‘length’ is undefined. This happens when the variable is not an array. Check if it’s null or undefined. Use console.log(Array.isArray(myVar)) to verify.
  • Java prints a memory address instead of a number. That’s because you used System.out.println(numbers) without .length. Add .length to get the count.

Frequently Asked Questions

1. Can I change the length of an array in JavaScript?

Yes, you can assign a new value to length to truncate or extend the array. For example, arr.length = 10 adds empty slots if it was shorter, or removes elements if it was longer.

2. Why does C++ not have a built-in length property?

C++ arrays are low-level constructs inherited from C. They are just contiguous memory blocks, and the size is not stored alongside the data. The sizeof trick works only when the array is in scope, not when passed to a function.

3. How do I print the length of a 2D array?

In JavaScript: arr.length gives the number of rows, and arr[0].length gives the number of columns (if rectangular). In Java: arr.length for rows, arr[0].length for columns. In C++: use sizeof(arr)/sizeof(arr[0]) for rows and sizeof(arr[0])/sizeof(arr[0][0]) for columns.

4. What is the difference between size() and length?

length is a property/field for arrays in JavaScript and Java. size() is a method for collections like ArrayList, Vector, and std::vector in C++. They serve the same purpose but on different data structures.

5. Can I print the length without a semicolon in JavaScript?

Yes, JavaScript has automatic semicolon insertion, but it’s best practice to include semicolons to avoid unexpected behavior. In Java and C++, semicolons are mandatory.

6. What happens if I try to print the length of an empty array?

It prints 0. An empty array has no elements, so the length is zero. This is valid in all three languages.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →