Skip to main content

JavaScript vs Java: Arrays & Strings Method Comparison

A comprehensive guide comparing JavaScript and Java methods for Arrays and Strings operations. Perfect for developers transitioning between languages or working in full-stack environments.


๐Ÿ“‹ Table of Contentsโ€‹

  1. Array Methods Comparison
  2. String Methods Comparison
  3. Quick Reference Tables
  4. Common Patterns
  5. Performance Notes

Array Methods Comparisonโ€‹

Creating and Initializing Arraysโ€‹

// Array creation
let arr1 = []; // Empty array
let arr2 = [1, 2, 3, 4, 5]; // Array literal
let arr3 = new Array(5); // Array with length 5 (empty slots)
let arr4 = new Array(1, 2, 3); // Array with elements
let arr5 = Array.of(1, 2, 3); // Preferred way
let arr6 = Array.from({length: 5}, (_, i) => i); // [0,1,2,3,4]

// Fill array
let filled = new Array(5).fill(0); // [0,0,0,0,0]

Length/Sizeโ€‹

let arr = [1, 2, 3, 4, 5];
console.log(arr.length); // 5

// Modify length
arr.length = 3; // Truncates to [1, 2, 3]
arr.length = 5; // Extends to [1, 2, 3, undefined, undefined]

Adding Elementsโ€‹

let arr = [1, 2, 3];

// Add to end
arr.push(4); // [1, 2, 3, 4] - returns new length
arr.push(5, 6); // [1, 2, 3, 4, 5, 6] - multiple elements

// Add to beginning
arr.unshift(0); // [0, 1, 2, 3, 4, 5, 6] - returns new length

// Add at specific index
arr.splice(2, 0, 1.5); // [0, 1, 1.5, 2, 3, 4, 5, 6]

Removing Elementsโ€‹

let arr = [1, 2, 3, 4, 5];

// Remove from end
let last = arr.pop(); // Returns 5, arr = [1, 2, 3, 4]

// Remove from beginning
let first = arr.shift(); // Returns 1, arr = [2, 3, 4]

// Remove at specific index
let removed = arr.splice(1, 1); // Removes index 1, returns [3]
// arr = [2, 4]

// Remove multiple elements
arr.splice(0, 2); // Remove 2 elements from index 0

Searching Elementsโ€‹

let arr = [1, 2, 3, 4, 3, 5];

// Find index
arr.indexOf(3); // 2 (first occurrence)
arr.lastIndexOf(3); // 4 (last occurrence)
arr.indexOf(6); // -1 (not found)

// Check existence
arr.includes(3); // true
arr.includes(6); // false

// Find element/index with condition
arr.find(x => x > 3); // 4 (first element > 3)
arr.findIndex(x => x > 3); // 3 (index of first element > 3)

Iterating Arraysโ€‹

let arr = [1, 2, 3, 4, 5];

// Traditional for loop
for (let i = 0; i < arr.length; i++) {
console.log(i, arr[i]);
}

// For...of loop (values)
for (let value of arr) {
console.log(value);
}

// For...in loop (indices)
for (let index in arr) {
console.log(index, arr[index]);
}

// forEach method
arr.forEach((value, index) => {
console.log(index, value);
});

Transforming Arraysโ€‹

let arr = [1, 2, 3, 4, 5];

// Map - transform each element
let doubled = arr.map(x => x * 2); // [2, 4, 6, 8, 10]
let strings = arr.map(x => x.toString()); // ['1', '2', '3', '4', '5']

// Filter - select elements
let evens = arr.filter(x => x % 2 === 0); // [2, 4]
let greaterThan2 = arr.filter(x => x > 2); // [3, 4, 5]

// Reduce - aggregate
let sum = arr.reduce((acc, x) => acc + x, 0); // 15
let product = arr.reduce((acc, x) => acc * x, 1); // 120

Sorting Arraysโ€‹

let arr = [3, 1, 4, 1, 5, 9, 2, 6];

// Sort in place (lexicographic by default)
arr.sort(); // [1, 1, 2, 3, 4, 5, 6, 9] - converts to strings first!

// Numeric sort
arr.sort((a, b) => a - b); // [1, 1, 2, 3, 4, 5, 6, 9] - ascending
arr.sort((a, b) => b - a); // [9, 6, 5, 4, 3, 2, 1, 1] - descending

// Sort strings
let words = ['banana', 'apple', 'cherry'];
words.sort(); // ['apple', 'banana', 'cherry']

// Custom sort
let people = [{name: 'Alice', age: 25}, {name: 'Bob', age: 20}];
people.sort((a, b) => a.age - b.age); // Sort by age

Copying Arraysโ€‹

let original = [1, 2, 3, 4, 5];

// Shallow copy methods
let copy1 = [...original]; // Spread operator
let copy2 = Array.from(original); // Array.from()
let copy3 = original.slice(); // slice() without parameters
let copy4 = original.concat(); // concat() without parameters

// Partial copy
let partial = original.slice(1, 4); // [2, 3, 4] - index 1 to 3

// Deep copy (for nested arrays/objects)
let nested = [[1, 2], [3, 4]];
let deepCopy = JSON.parse(JSON.stringify(nested)); // Simple deep copy

Joining Arraysโ€‹

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];

// Concatenate arrays
let combined1 = arr1.concat(arr2); // [1, 2, 3, 4, 5, 6]
let combined2 = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]

// Join to string
let str = arr1.join(', '); // "1, 2, 3"
let str2 = arr1.join(''); // "123"
let str3 = arr1.join(); // "1,2,3" (default comma)

String Methods Comparisonโ€‹

Creating Stringsโ€‹

// String creation
let str1 = "Hello"; // String literal
let str2 = 'Hello'; // Single quotes
let str3 = `Hello`; // Template literal
let str4 = new String("Hello"); // String object (avoid)

// Template literals
let name = "World";
let greeting = `Hello, ${name}!`; // "Hello, World!"

// Multi-line strings
let multiline = `Line 1
Line 2
Line 3`;

String Length and Character Accessโ€‹

let str = "Hello World";

// Length
console.log(str.length); // 11

// Character access
console.log(str[0]); // 'H' - bracket notation
console.log(str.charAt(0)); // 'H' - method
console.log(str.at(-1)); // 'd' - negative index (ES2022)

// Character codes
console.log(str.charCodeAt(0)); // 72 (UTF-16 code)
console.log(str.codePointAt(0)); // 72 (Unicode code point)

String Searchingโ€‹

let str = "Hello World Hello";

// Find index
str.indexOf("Hello"); // 0 (first occurrence)
str.lastIndexOf("Hello"); // 12 (last occurrence)
str.indexOf("Hello", 1); // 12 (search from index 1)
str.indexOf("xyz"); // -1 (not found)

// Check existence
str.includes("World"); // true
str.startsWith("Hello"); // true
str.endsWith("Hello"); // true

// Search with regex
str.search(/W\w+/); // 6 (index of "World")
str.match(/Hello/g); // ["Hello", "Hello"] (all matches)

String Modificationโ€‹

let str = "  Hello World  ";

// Case conversion
str.toLowerCase(); // " hello world "
str.toUpperCase(); // " HELLO WORLD "

// Trimming
str.trim(); // "Hello World"
str.trimStart(); // "Hello World " (ES2019)
str.trimEnd(); // " Hello World" (ES2019)

// Padding
"5".padStart(3, "0"); // "005"
"5".padEnd(3, "0"); // "500"

// Replacing
str.replace("World", "JavaScript"); // Replace first occurrence
str.replaceAll("l", "L"); // Replace all (ES2021)
str.replace(/l/g, "L"); // Replace all with regex

// Substrings
str.substring(2, 7); // "Hello" (start, end)
str.substr(2, 5); // "Hello" (start, length) - deprecated
str.slice(2, 7); // "Hello" (start, end, supports negative)
str.slice(-7, -2); // "World"

String Splitting and Joiningโ€‹

let str = "apple,banana,cherry";

// Split
str.split(","); // ["apple", "banana", "cherry"]
str.split(",", 2); // ["apple", "banana"] (limit)
str.split(""); // ["a", "p", "p", "l", "e", ",", ...]

// Join arrays
let fruits = ["apple", "banana", "cherry"];
fruits.join(", "); // "apple, banana, cherry"
fruits.join(""); // "applebananacherry"

// Repeat
"ha".repeat(3); // "hahaha"

String Comparisonโ€‹

let str1 = "hello";
let str2 = "Hello";
let str3 = "world";

// Equality
str1 === "hello"; // true (strict equality)
str1 == "hello"; // true (loose equality)

// Comparison
str1.localeCompare(str2); // 1 (str1 > str2)
str1.localeCompare(str3); // -1 (str1 < str3)
str1.localeCompare(str1); // 0 (equal)

// Case-insensitive comparison
str1.toLowerCase() === str2.toLowerCase(); // true

Quick Reference Tablesโ€‹

Array Methods Quick Referenceโ€‹

OperationJavaScriptJava (Arrays)Java (Collections)
Create[1,2,3]{1,2,3}Arrays.asList(1,2,3)
Lengtharr.lengtharr.lengthlist.size()
Add Endarr.push(x)N/A (fixed size)list.add(x)
Add Startarr.unshift(x)N/Alist.add(0, x)
Remove Endarr.pop()N/Alist.remove(list.size()-1)
Remove Startarr.shift()N/Alist.remove(0)
Find Indexarr.indexOf(x)Arrays.binarySearch()list.indexOf(x)
Containsarr.includes(x)N/Alist.contains(x)
Sortarr.sort()Arrays.sort(arr)Collections.sort(list)
Copy[...arr]arr.clone()new ArrayList<>(list)
Joinarr.join(',')Arrays.toString()String.join(',', list)
Maparr.map(f)N/Alist.stream().map(f)
Filterarr.filter(f)N/Alist.stream().filter(f)
Reducearr.reduce(f)N/Alist.stream().reduce(f)

String Methods Quick Referenceโ€‹

OperationJavaScriptJava
Lengthstr.lengthstr.length()
Char Atstr[i] or str.charAt(i)str.charAt(i)
Substringstr.slice(i,j)str.substring(i,j)
Index Ofstr.indexOf(s)str.indexOf(s)
Containsstr.includes(s)str.contains(s)
Starts Withstr.startsWith(s)str.startsWith(s)
Ends Withstr.endsWith(s)str.endsWith(s)
Upper Casestr.toUpperCase()str.toUpperCase()
Lower Casestr.toLowerCase()str.toLowerCase()
Trimstr.trim()str.trim()
Replacestr.replace(a,b)str.replace(a,b)
Replace Allstr.replaceAll(a,b)str.replaceAll(a,b)
Splitstr.split(sep)str.split(sep)
Joinarr.join(sep)String.join(sep, arr)
Repeatstr.repeat(n)str.repeat(n) (Java 11+)

Common Patternsโ€‹

Array Processing Patternsโ€‹

// Find max/min
let numbers = [3, 1, 4, 1, 5, 9, 2, 6];
let max = Math.max(...numbers); // 9
let min = Math.min(...numbers); // 1

// Sum array
let sum = numbers.reduce((a, b) => a + b, 0); // 31

// Remove duplicates
let unique = [...new Set(numbers)]; // [3, 1, 4, 5, 9, 2, 6]

// Flatten array
let nested = [[1, 2], [3, 4], [5]];
let flat = nested.flat(); // [1, 2, 3, 4, 5]
let deepFlat = nested.flat(Infinity); // For deeply nested

// Group by property
let people = [{name: 'Alice', age: 25}, {name: 'Bob', age: 25}];
let grouped = people.reduce((acc, person) => {
(acc[person.age] = acc[person.age] || []).push(person);
return acc;
}, {});

// Check if all/any elements match condition
let allPositive = numbers.every(x => x > 0); // false
let hasEven = numbers.some(x => x % 2 === 0); // true

String Processing Patternsโ€‹

// Reverse string
let str = "hello";
let reversed = str.split('').reverse().join(''); // "olleh"

// Check palindrome
function isPalindrome(s) {
let clean = s.toLowerCase().replace(/[^a-z0-9]/g, '');
return clean === clean.split('').reverse().join('');
}

// Count characters
function charCount(str) {
return str.split('').reduce((acc, char) => {
acc[char] = (acc[char] || 0) + 1;
return acc;
}, {});
}

// Title case
function titleCase(str) {
return str.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(' ');
}

// Remove extra spaces
function cleanSpaces(str) {
return str.trim().replace(/\s+/g, ' ');
}

Performance Notesโ€‹

Array Performanceโ€‹

JavaScript:

  • push()/pop() are O(1) - efficient
  • unshift()/shift() are O(n) - less efficient
  • splice() is O(n) for insertion/deletion
  • Spread operator [...arr] creates shallow copy - O(n)

Java:

  • Array access is O(1)
  • ArrayList.add() is amortized O(1)
  • ArrayList.add(0, x) is O(n)
  • System.arraycopy() is faster than loops for copying

String Performanceโ€‹

JavaScript:

  • Strings are immutable - each operation creates new string
  • Template literals are generally efficient
  • For many concatenations, use array join: arr.join('')

Java:

  • Strings are immutable - use StringBuilder for multiple operations
  • StringBuilder is not thread-safe, StringBuffer is thread-safe
  • String concatenation with + in loops is inefficient

Best Practicesโ€‹

JavaScript:

// โŒ Inefficient
let result = "";
for (let i = 0; i < 1000; i++) {
result += "item " + i;
}

// โœ… Efficient
let parts = [];
for (let i = 0; i < 1000; i++) {
parts.push("item " + i);
}
let result = parts.join("");

Java:

// โŒ Inefficient
String result = "";
for (int i = 0; i < 1000; i++) {
result += "item " + i;
}

// โœ… Efficient
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append("item ").append(i);
}
String result = sb.toString();

Summaryโ€‹

This guide provides a comprehensive comparison between JavaScript and Java for array and string operations. Key takeaways:

Arraysโ€‹

  • JavaScript: Dynamic arrays with rich built-in methods (map, filter, reduce)
  • Java: Fixed-size arrays + ArrayList for dynamic behavior + Streams API for functional operations

Stringsโ€‹

  • JavaScript: Immutable with extensive built-in methods and template literals
  • Java: Immutable with similar methods + StringBuilder for efficient building

Migration Tipsโ€‹

  1. JS โ†’ Java: Learn ArrayList and Streams API for array operations
  2. Java โ†’ JS: Embrace functional array methods and template literals
  3. Both: Understand immutability and performance implications

The syntax may differ, but the concepts are remarkably similar, making it easier to work across both languages in full-stack development!