1. University MCA (AI/ML) Semester 2
  2. CAP477
  3. Unit 1

CAP477 · Unit 1: Java fundamentals

Arrays and Strings

9 practice questions

Key points

  • Arrays: fixed size, default values, length field
  • Strings are immutable; methods return new Strings
  • == compares references, equals compares content
  • Use StringBuilder for repeated modification

Arrays are fixed-size objects. int[] a = new int[3]; gives default values: 0 for numbers, false for boolean, null for objects (0 null false 0.0 for int, String, boolean, double). Length is the field a.length (not a method). Out-of-range access throws ArrayIndexOutOfBoundsException ("Index 3 out of bounds for length 3"). Assigning int[] b = a; copies the reference; a.clone() makes a shallow copy. 2D arrays are arrays of arrays and can be jagged. java.util.Arrays offers sort, toString, binarySearch (sorted input only), fill, equals.

Strings are immutable: methods such as toUpperCase() return a new String and leave the original unchanged. Common methods: length(), charAt(i), substring(begin, end) (end exclusive), indexOf, contains, replace, trim, split, compareTo, equals, repeat, isBlank, String.join.

== versus equals(): == compares references; equals() compares content. String literals are pooled, so "hi" == "hi" is true, but new String("hi") == "hi" is false while equals is true. intern() returns the pooled instance.

compareTo returns the lexicographic difference: "apple".compareTo("banana") is -1 and "b".compareTo("a") is 1. "a,b,,c".split(",") gives [a, b, , c].

StringBuilder is a mutable buffer for repeated edits (not synchronized; StringBuffer is the synchronized version): new StringBuilder("abc").append("de").reverse().insert(0, "X") yields Xedcba.

Calling a method on null throws NullPointerException.

Exam pitfall: array length is length, String length is length().

Try two questions

Question 1 · Tier 2, Understand

What is the default value of an element in new String[2]?

  1. false
  2. 0
  3. ""
  4. null
Show the answer

D. Object arrays default to null: 0 null false 0.0 3.

Question 2 · Tier 3, Apply

int[] a = {5, 2, 9, 1}; Arrays.sort(a); int[] b = a; b[0] = 99; System.out.println(a[0]); prints:

  1. 99
  2. 5
  3. 1
  4. 2
Show the answer

A. b and a are the same array object: 99.