JAVA-Arrays and Strings - Notes By ShariqSP

Arrays and Strings in Java

Arrays

In Java, Arrays are used to store multiple values of the same type.

Declaring Arrays: To declare an array in Java, you specify the type of elements it will hold and the array's name followed by square brackets ([]).


                  // Declaration of an array of integers
                  int[] numbers;
                

Initializing Arrays: Arrays can be initialized using the new keyword along with the length of the array, or by directly providing the elements.


                  // Initializing an array of integers with size 5
                  numbers = new int[5];
              
                  // Initializing an array with elements
                  int[] numbers = {1, 2, 3, 4, 5};
                

Accessing Array Elements: Elements in an array are accessed using their index, starting from 0.


                  int firstElement = numbers[0]; // Accessing the first element
                

Printing an array in Java can be done using either a for loop or a for-each loop.

Using a For Loop: In a for loop, you iterate over the array indices and access each element using the index.


                int[] numbers = {1, 2, 3, 4, 5};
                for (int i = 0; i < numbers.length; i++) {
                    System.out.print(numbers[i] + " ");
                }
                

Using a For-each Loop: In a for-each loop, you directly iterate over the elements of the array without needing to know the indices.


                int[] numbers = {1, 2, 3, 4, 5};
                for (int num : numbers) {
                    System.out.print(num + " ");
                }
                

Differences:

  • A for loop requires knowing the length of the array and using an index to access each element, while a for-each loop automatically handles this.
  • A for-each loop is more concise and readable when iterating over all elements of an array.
  • A for loop allows more control over the iteration process, such as iterating backwards or skipping elements.
quiz Long answers

Strings

In Java, Strings are sequences of characters and are treated as arrays of characters in Java.

Declaring Strings: Strings are declared similarly to other objects in Java, using the String class.


                  // Declaration of a String variable
                  String str;
                

Initializing Strings: Strings can be initialized using string literals or by creating a new instance of the String class.


                  // Initializing a String with a string literal
                  String greeting = "Hello";
              
                  // Initializing a String with a new instance
                  String name = new String("John");
                

Accessing String Characters: Characters in a string can be accessed using their index, similar to arrays.


                  char firstChar = greeting.charAt(0); // Accessing the first character
                

String Methods in Java

The String class in Java provides a wide range of methods to perform various operations on strings.

1. length()

Returns the length of the string.


                  String str = "Hello";
                  int length = str.length(); // length is 5
                

2. charAt(int index)

Returns the character at the specified index.


                  String str = "Java";
                  char ch = str.charAt(0); // ch is 'J'
                

3. concat(String str)

Concatenates the specified string to the end of this string.


                  String str1 = "Hello";
                  String str2 = "World";
                  String result = str1.concat(str2); // result is "HelloWorld"
                

4. indexOf(String str)

Returns the index within this string of the first occurrence of the specified substring.


                  String str = "Java is a programming language";
                  int index = str.indexOf("programming"); // index is 8
                

5. substring(int beginIndex)

Returns a new string that is a substring of this string, starting from the specified index.


                  String str = "Hello World";
                  String subStr = str.substring(6); // subStr is "World"
                

6. toLowerCase()

Converts all of the characters in this String to lower case.


                  String str = "HELLO";
                  String lowerCaseStr = str.toLowerCase(); // lowerCaseStr is "hello"
                

7. toUpperCase()

Converts all of the characters in this String to upper case.


                  String str = "hello";
                  String upperCaseStr = str.toUpperCase(); // upperCaseStr is "HELLO"
                

8. trim()

Returns a copy of the string with leading and trailing whitespace removed.


                  String str = "   Hello   ";
                  String trimmedStr = str.trim(); // trimmedStr is "Hello"
                

9. startsWith(String prefix)

Tests if this string starts with the specified prefix.


                  String str = "Hello World";
                  boolean startsWithHello = str.startsWith("Hello"); // true
                

10. endsWith(String suffix)

Tests if this string ends with the specified suffix.


                  String str = "Hello World";
                  boolean endsWithWorld = str.endsWith("World"); // true
                

11. contains(CharSequence s)

Returns true if and only if this string contains the specified sequence of char values.


                  String str = "Hello World";
                  boolean containsWorld = str.contains("World"); // true
                

12. replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.


                  String str = "Hello World";
                  String replacedStr = str.replace(' ', '-'); // "Hello-World"
                

13. replace(CharSequence target, CharSequence replacement)

Returns a new string resulting from replacing all occurrences of target in this string with replacement.


                  String str = "Hello World";
                  String replacedStr = str.replace("World", "Universe"); // "Hello Universe"
                

14. split(String regex)

Splits this string around matches of the given regular expression.


                  String str = "apple,banana,orange";
                  String[] fruits = str.split(","); // {"apple", "banana", "orange"}
                

15. trim()

Returns a copy of the string with leading and trailing whitespace removed.


                  String str = "   Hello   ";
                  String trimmedStr = str.trim(); // trimmedStr is "Hello"
                

16. valueOf(dataType data)

Returns the string representation of the specified data type.


                  int number = 123;
                  String str = String.valueOf(number); // "123"
                
quiz Long answers