java

Arrays Strings


1. Arrays in Java

Definition

  • An array is a collection of elements of the same type stored in a contiguous memory location.
  • Arrays are objects in Java and can store both primitive data types and objects.

Declaration and Initialization

Key Features

  • Indexing: Array indices start at 0 and go up to n-1, where n is the array’s length.
  • Length: The size of the array is fixed and accessible using the .length property.
  • Default Values:
    • Numeric types (int, float, etc.): 0
    • Boolean: false
    • Objects: null

Types of Arrays

  1. Single-dimensional Array: int[] arr = new int[3]; // Example: [0, 0, 0]
  2. Multi-dimensional Array: int[][] matrix = { {1, 2}, {3, 4}, {5, 6} }; // 2D array (matrix)

Accessing Array Elements

Iterating Through an Array

Key Limitations

  • Arrays have a fixed size once created.
  • Do not support dynamic resizing. For dynamic collections, use ArrayList or other collections.

2. Strings in Java

Definition

  • A String is a sequence of characters. In Java, String is an immutable class in the java.lang package.

Declaration and Initialization

Key Features

  • Strings are immutable, meaning once created, their content cannot be changed.
  • Stored in the String pool for memory optimization.

String Methods

MethodDescriptionExample
length()Returns the length of the string."Java".length()4
charAt(index)Returns the character at the specified index."Java".charAt(2)'v'
substring(start, end)Returns a substring from start to end-1."Java".substring(1, 3)"av"
toUpperCase()Converts all characters to uppercase."java".toUpperCase()"JAVA"
toLowerCase()Converts all characters to lowercase."JAVA".toLowerCase()"java"
equals(otherString)Compares two strings for equality (case-sensitive)."java".equals("Java")false
equalsIgnoreCase(otherString)Compares two strings for equality (case-insensitive)."java".equalsIgnoreCase("Java")true
contains(sequence)Checks if the string contains the specified character sequence."Java".contains("av")true
replace(oldChar, newChar)Replaces all occurrences of oldChar with newChar."Java".replace('a', 'o')"Jovo"
split(regex)Splits the string based on the provided regex and returns an array."a,b,c".split(",")["a", "b", "c"]
trim()Removes leading and trailing whitespace." Hello ".trim()"Hello"

String Concatenation

  1. Using the + operator: String greeting = "Hello" + " " + "World!"; System.out.println(greeting); // Output: Hello World!
  2. Using concat() method: String str1 = "Java"; String str2 = "Programming"; String result = str1.concat(" ").concat(str2); System.out.println(result); // Output: Java Programming

Immutability

  • Any operation on a String creates a new string object instead of modifying the original.

StringBuilder and StringBuffer

  • For mutable strings (modifiable):
    • StringBuilder: Faster and not thread-safe.
    • StringBuffer: Thread-safe (synchronized) but slower.

Comparison: Arrays vs Strings

FeatureArraysStrings
TypeFixed-size collection of same-type elements.Sequence of characters (immutable).
FlexibilitySize is fixed. Cannot resize dynamically.Content is immutable.
UsageSuitable for numeric or grouped data.Suitable for text and character sequences.
EfficiencyFaster for bulk data operations.Optimized for text operations.

Leave a Reply

Your email address will not be published. Required fields are marked *