Understanding Strings in Java

Jun 5, 2024

Understanding Strings in Java

Overview

  • Strings: Simple to use; complex to understand fully.
  • Strings store a sequence of characters.
  • Different from primitive types like int, float, double, and boolean.

Creating Strings

  1. Using Double Quotes
    • Syntax: String name = "Naveen";
    • String literals created using double quotes.
  2. Using Character Arrays
    • You can create character arrays to store sequences of characters but less common.
  3. Using new Keyword
    • Syntax: String name = new String("Naveen");
    • Creates a new String object explicitly.

Memory Allocation

  • Stack Memory: Holds reference variables like name.
  • Heap Memory: Holds the actual string objects.
  • Java Virtual Machine (JVM) manages memory allocation.

Behind the Scenes

  • String in Java is a class, not a primitive type.
    • Starts with a capital letter: String.
    • Contains methods to manipulate string data.
  • When creating strings, JVM handles object creation even if syntax looks different.
    • Both String name = "Naveen"; and String name = new String("Naveen"); are valid.

String Methods

  1. Concatenation: Using + Operator.
    • Example: String fullName = "Hello" + name; results in Hello Naveen.
  2. Getting Character by Index: charAt Method.
    • Example: name.charAt(1) returns a from Naveen.
  3. Checking Equality: equals Method.
    • Use name.equals(anotherName) to compare two strings.
  4. Hash Code: hashCode Method.
    • Generates a hash code based on the string content.

Practical Examples

  • Print Statements: Concatenation
    System.out.println("Hello " + name);
    
  • Character at Index
    System.out.println(name.charAt(1)); // prints 'a'
    
  • Concatenating Multiple Strings
    String fullName = name + " Reddy";
    System.out.println(fullName); // prints 'Naveen Reddy'
    

Key Takeaways

  • Strings are more than just character sequences; they are objects of the String class.
  • Memory management and object creation are handled by JVM.
  • Use provided methods to manage and manipulate string data efficiently.
  • Common to use syntax: String name = "value"; over new String("value");

Next Steps

  • Explore different types of strings in Java.