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โ
- Array Methods Comparison
- String Methods Comparison
- Quick Reference Tables
- Common Patterns
- Performance Notes
Array Methods Comparisonโ
Creating and Initializing Arraysโ
- JavaScript
- Java
// 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]
// Array creation
int[] arr1 = new int[5]; // Array with length 5 (zeros)
int[] arr2 = {1, 2, 3, 4, 5}; // Array literal
int[] arr3 = new int[]{1, 2, 3, 4, 5}; // Explicit creation
List<Integer> list = new ArrayList<>(); // Dynamic array equivalent
// Fill array
int[] filled = new int[5];
Arrays.fill(filled, 0); // Fill with 0
// Or: Arrays.fill(filled, 2, 4, 99); // Fill index 2-3 with 99
Length/Sizeโ
- JavaScript
- Java
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]
int[] arr = {1, 2, 3, 4, 5};
System.out.println(arr.length); // 5 (property, not method)
// Arrays have fixed length, use ArrayList for dynamic sizing
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
System.out.println(list.size()); // 5
Adding Elementsโ
- JavaScript
- Java
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]
// Arrays have fixed size, use ArrayList
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));
// Add to end
list.add(4); // [1, 2, 3, 4] - returns boolean
Collections.addAll(list, 5, 6); // Add multiple: [1, 2, 3, 4, 5, 6]
// Add to beginning
list.add(0, 0); // [0, 1, 2, 3, 4, 5, 6]
// Add at specific index
list.add(2, 15); // [0, 1, 15, 2, 3, 4, 5, 6]
Removing Elementsโ
- JavaScript
- Java
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
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
// Remove from end
int last = list.remove(list.size() - 1); // Returns 5
// Remove from beginning
int first = list.remove(0); // Returns 1
// Remove at specific index
int removed = list.remove(1); // Removes index 1, returns element
// Remove by value
list.remove(Integer.valueOf(3)); // Remove first occurrence of 3
// Remove multiple (using iterator to avoid ConcurrentModificationException)
list.removeIf(x -> x > 3);
Searching Elementsโ
- JavaScript
- Java
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)
List<Integer> list = Arrays.asList(1, 2, 3, 4, 3, 5);
// Find index
int index = list.indexOf(3); // 2 (first occurrence)
int lastIndex = list.lastIndexOf(3); // 4 (last occurrence)
// Returns -1 if not found
// Check existence
boolean contains = list.contains(3); // true
// For arrays (must be sorted for binarySearch)
int[] sortedArr = {1, 2, 3, 4, 5};
int index = Arrays.binarySearch(sortedArr, 3); // 2
// Find with condition (Java 8+)
Optional<Integer> found = list.stream()
.filter(x -> x > 3)
.findFirst(); // Optional[4]
// Find index with condition
int foundIndex = IntStream.range(0, list.size())
.filter(i -> list.get(i) > 3)
.findFirst()
.orElse(-1); // 3
Iterating Arraysโ
- JavaScript
- Java
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);
});
int[] arr = {1, 2, 3, 4, 5};
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
// Traditional for loop
for (int i = 0; i < arr.length; i++) {
System.out.println(i + " " + arr[i]);
}
// Enhanced for loop (for-each)
for (int value : arr) {
System.out.println(value);
}
// List iteration
for (int i = 0; i < list.size(); i++) {
System.out.println(i + " " + list.get(i));
}
// forEach method (Java 8+)
list.forEach(System.out::println);
// Stream forEach with index
IntStream.range(0, list.size())
.forEach(i -> System.out.println(i + " " + list.get(i)));
Transforming Arraysโ
- JavaScript
- Java
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
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
// Map - transform each element
List<Integer> doubled = list.stream()
.map(x -> x * 2)
.collect(Collectors.toList()); // [2, 4, 6, 8, 10]
List<String> strings = list.stream()
.map(Object::toString)
.collect(Collectors.toList()); // ["1", "2", "3", "4", "5"]
// Filter - select elements
List<Integer> evens = list.stream()
.filter(x -> x % 2 == 0)
.collect(Collectors.toList()); // [2, 4]
// Reduce - aggregate
int sum = list.stream()
.reduce(0, Integer::sum); // 15
int product = list.stream()
.reduce(1, (a, b) -> a * b); // 120
Sorting Arraysโ
- JavaScript
- Java
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
// Arrays
int[] arr = {3, 1, 4, 1, 5, 9, 2, 6};
Arrays.sort(arr); // [1, 1, 2, 3, 4, 5, 6, 9] - ascending
// Reverse sort (need Integer[] for comparator)
Integer[] boxedArr = {3, 1, 4, 1, 5, 9, 2, 6};
Arrays.sort(boxedArr, Collections.reverseOrder());
// Lists
List<Integer> list = new ArrayList<>(Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6));
Collections.sort(list); // [1, 1, 2, 3, 4, 5, 6, 9]
list.sort(Collections.reverseOrder()); // [9, 6, 5, 4, 3, 2, 1, 1]
// Custom sort
List<Person> people = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 20)
);
people.sort(Comparator.comparing(Person::getAge));
// Stream sorting (returns new sorted stream)
List<Integer> sorted = list.stream()
.sorted()
.collect(Collectors.toList());
Copying Arraysโ
- JavaScript
- Java
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
int[] original = {1, 2, 3, 4, 5};
// Array copying
int[] copy1 = original.clone(); // Shallow copy
int[] copy2 = Arrays.copyOf(original, original.length);
int[] copy3 = new int[original.length];
System.arraycopy(original, 0, copy3, 0, original.length);
// Partial copy
int[] partial = Arrays.copyOfRange(original, 1, 4); // [2, 3, 4]
// List copying
List<Integer> originalList = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> copyList = new ArrayList<>(originalList);
// Deep copy for 2D arrays
int[][] nested = {{1, 2}, {3, 4}};
int[][] deepCopy = new int[nested.length][];
for (int i = 0; i < nested.length; i++) {
deepCopy[i] = nested[i].clone();
}
Joining Arraysโ
- JavaScript
- Java
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)
// Arrays
int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};
// Concatenate arrays (manual)
int[] combined = new int[arr1.length + arr2.length];
System.arraycopy(arr1, 0, combined, 0, arr1.length);
System.arraycopy(arr2, 0, combined, arr1.length, arr2.length);
// Using streams
int[] combined2 = IntStream.concat(
Arrays.stream(arr1),
Arrays.stream(arr2)
).toArray();
// Lists
List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(4, 5, 6);
List<Integer> combined3 = Stream.concat(list1.stream(), list2.stream())
.collect(Collectors.toList());
// Join to string
String str = list1.stream()
.map(String::valueOf)
.collect(Collectors.joining(", ")); // "1, 2, 3"
// Or using Arrays.toString() for simple cases
String str2 = Arrays.toString(arr1); // "[1, 2, 3]"
String Methods Comparisonโ
Creating Stringsโ
- JavaScript
- Java
// 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 creation
String str1 = "Hello"; // String literal (preferred)
String str2 = new String("Hello"); // Creates new object (avoid usually)
// String formatting
String name = "World";
String greeting = String.format("Hello, %s!", name); // "Hello, World!"
// Multi-line strings (Java 15+)
String multiline = """
Line 1
Line 2
Line 3
""";
// StringBuilder for building strings
StringBuilder sb = new StringBuilder();
sb.append("Hello, ").append(name).append("!");
String result = sb.toString();
String Length and Character Accessโ
- JavaScript
- Java
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 str = "Hello World";
// Length
System.out.println(str.length()); // 11
// Character access
System.out.println(str.charAt(0)); // 'H'
// No bracket notation or negative indexing
// Character codes
System.out.println((int) str.charAt(0)); // 72
System.out.println(str.codePointAt(0)); // 72
// Convert to char array for easier manipulation
char[] chars = str.toCharArray();
System.out.println(chars[0]); // 'H'
String Searchingโ
- JavaScript
- Java
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 str = "Hello World Hello";
// Find index
int index1 = str.indexOf("Hello"); // 0
int index2 = str.lastIndexOf("Hello"); // 12
int index3 = str.indexOf("Hello", 1); // 12
int notFound = str.indexOf("xyz"); // -1
// Check existence
boolean contains = str.contains("World"); // true
boolean starts = str.startsWith("Hello"); // true
boolean ends = str.endsWith("Hello"); // true
// Pattern matching
Pattern pattern = Pattern.compile("W\\w+");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
System.out.println(matcher.start()); // 6
}
// Find all matches
List<String> matches = new ArrayList<>();
Matcher allMatcher = Pattern.compile("Hello").matcher(str);
while (allMatcher.find()) {
matches.add(allMatcher.group());
}
String Modificationโ
- JavaScript
- Java
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 str = " Hello World ";
// Case conversion
str.toLowerCase(); // " hello world "
str.toUpperCase(); // " HELLO WORLD "
// Trimming
str.trim(); // "Hello World"
str.strip(); // "Hello World" (Java 11+, Unicode-aware)
str.stripLeading(); // "Hello World " (Java 11+)
str.stripTrailing(); // " Hello World" (Java 11+)
// No built-in padding, use String.format or Apache Commons
String padded = String.format("%03d", 5); // "005"
// Replacing
str.replace("World", "Java"); // Replace all occurrences
str.replaceFirst("l", "L"); // Replace first occurrence
str.replaceAll("l", "L"); // Replace all with regex
// Substrings
str.substring(2, 7); // "Hello" (start, end)
str.substring(2); // "Hello World " (from start to end)
// No negative indexing support
String Splitting and Joiningโ
- JavaScript
- Java
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 str = "apple,banana,cherry";
// Split
String[] parts = str.split(","); // ["apple", "banana", "cherry"]
String[] limited = str.split(",", 2); // ["apple", "banana,cherry"]
String[] chars = str.split(""); // ["a", "p", "p", "l", "e", ",", ...]
// Join arrays (Java 8+)
String[] fruits = {"apple", "banana", "cherry"};
String joined = String.join(", ", fruits); // "apple, banana, cherry"
// Join collections
List<String> fruitList = Arrays.asList(fruits);
String joined2 = String.join("", fruitList);
// Repeat (Java 11+)
String repeated = "ha".repeat(3); // "hahaha"
// For older Java versions
String repeated2 = String.join("", Collections.nCopies(3, "ha"));
String Comparisonโ
- JavaScript
- Java
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
String str1 = "hello";
String str2 = "Hello";
String str3 = "world";
// Equality
str1.equals("hello"); // true
str1.equalsIgnoreCase(str2); // true
str1 == "hello"; // true (string literals)
str1 == new String("hello"); // false (different objects)
// Comparison
str1.compareTo(str2); // positive (str1 > str2)
str1.compareTo(str3); // negative (str1 < str3)
str1.compareTo(str1); // 0 (equal)
str1.compareToIgnoreCase(str2); // 0 (equal ignoring case)
// Null-safe comparison
Objects.equals(str1, str2); // false
Quick Reference Tablesโ
Array Methods Quick Referenceโ
| Operation | JavaScript | Java (Arrays) | Java (Collections) |
|---|---|---|---|
| Create | [1,2,3] | {1,2,3} | Arrays.asList(1,2,3) |
| Length | arr.length | arr.length | list.size() |
| Add End | arr.push(x) | N/A (fixed size) | list.add(x) |
| Add Start | arr.unshift(x) | N/A | list.add(0, x) |
| Remove End | arr.pop() | N/A | list.remove(list.size()-1) |
| Remove Start | arr.shift() | N/A | list.remove(0) |
| Find Index | arr.indexOf(x) | Arrays.binarySearch() | list.indexOf(x) |
| Contains | arr.includes(x) | N/A | list.contains(x) |
| Sort | arr.sort() | Arrays.sort(arr) | Collections.sort(list) |
| Copy | [...arr] | arr.clone() | new ArrayList<>(list) |
| Join | arr.join(',') | Arrays.toString() | String.join(',', list) |
| Map | arr.map(f) | N/A | list.stream().map(f) |
| Filter | arr.filter(f) | N/A | list.stream().filter(f) |
| Reduce | arr.reduce(f) | N/A | list.stream().reduce(f) |
String Methods Quick Referenceโ
| Operation | JavaScript | Java |
|---|---|---|
| Length | str.length | str.length() |
| Char At | str[i] or str.charAt(i) | str.charAt(i) |
| Substring | str.slice(i,j) | str.substring(i,j) |
| Index Of | str.indexOf(s) | str.indexOf(s) |
| Contains | str.includes(s) | str.contains(s) |
| Starts With | str.startsWith(s) | str.startsWith(s) |
| Ends With | str.endsWith(s) | str.endsWith(s) |
| Upper Case | str.toUpperCase() | str.toUpperCase() |
| Lower Case | str.toLowerCase() | str.toLowerCase() |
| Trim | str.trim() | str.trim() |
| Replace | str.replace(a,b) | str.replace(a,b) |
| Replace All | str.replaceAll(a,b) | str.replaceAll(a,b) |
| Split | str.split(sep) | str.split(sep) |
| Join | arr.join(sep) | String.join(sep, arr) |
| Repeat | str.repeat(n) | str.repeat(n) (Java 11+) |
Common Patternsโ
Array Processing Patternsโ
- JavaScript
- Java
// 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
// Find max/min
List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6);
int max = Collections.max(numbers); // 9
int min = Collections.min(numbers); // 1
// Or with streams:
int maxStream = numbers.stream().mapToInt(Integer::intValue).max().orElse(0);
// Sum array
int sum = numbers.stream().mapToInt(Integer::intValue).sum(); // 31
// Remove duplicates
List<Integer> unique = numbers.stream()
.distinct()
.collect(Collectors.toList()); // [3, 1, 4, 5, 9, 2, 6]
// Flatten array
List<List<Integer>> nested = Arrays.asList(
Arrays.asList(1, 2),
Arrays.asList(3, 4),
Arrays.asList(5)
);
List<Integer> flat = nested.stream()
.flatMap(List::stream)
.collect(Collectors.toList()); // [1, 2, 3, 4, 5]
// Group by property
List<Person> people = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 25)
);
Map<Integer, List<Person>> grouped = people.stream()
.collect(Collectors.groupingBy(Person::getAge));
// Check if all/any elements match condition
boolean allPositive = numbers.stream().allMatch(x -> x > 0); // false
boolean hasEven = numbers.stream().anyMatch(x -> x % 2 == 0); // true
String Processing Patternsโ
- JavaScript
- Java
// 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, ' ');
}
// Reverse string
String str = "hello";
String reversed = new StringBuilder(str).reverse().toString(); // "olleh"
// Check palindrome
public static boolean isPalindrome(String s) {
String clean = s.toLowerCase().replaceAll("[^a-z0-9]", "");
return clean.equals(new StringBuilder(clean).reverse().toString());
}
// Count characters
public static Map<Character, Integer> charCount(String str) {
Map<Character, Integer> count = new HashMap<>();
for (char c : str.toCharArray()) {
count.put(c, count.getOrDefault(c, 0) + 1);
}
return count;
}
// Title case
public static String titleCase(String str) {
return Arrays.stream(str.split(" "))
.map(word -> word.substring(0, 1).toUpperCase() +
word.substring(1).toLowerCase())
.collect(Collectors.joining(" "));
}
// Remove extra spaces
public static String cleanSpaces(String str) {
return str.trim().replaceAll("\\s+", " ");
}
Performance Notesโ
Array Performanceโ
JavaScript:
push()/pop()are O(1) - efficientunshift()/shift()are O(n) - less efficientsplice()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
StringBuilderfor multiple operations StringBuilderis not thread-safe,StringBufferis 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 +
ArrayListfor dynamic behavior + Streams API for functional operations
Stringsโ
- JavaScript: Immutable with extensive built-in methods and template literals
- Java: Immutable with similar methods +
StringBuilderfor efficient building
Migration Tipsโ
- JS โ Java: Learn
ArrayListand Streams API for array operations - Java โ JS: Embrace functional array methods and template literals
- 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!