Exploring Strings in Java: Your Ultimate Core Java Interview Guide - Part 1

Exploring Strings in Java: Your Ultimate Core Java Interview Guide - Part 1

Creating Strings

Strings can be created using two methods

  • String literal: Simply enclosing text within double quotes, like?"Hello Dinuka".
  • Using the?new?keyword: Instantiating a new String object, like?new String("Hello Dinuka").

Difference Between String Literal and?new?Keyword

String literal

  • Utilizes a string pool in memory.
  • If the string already exists in the pool, the same reference is used.

new?keyword

  • Creates a new object in the heap memory every time, regardless of whether the string exists in the pool.
  • Consumes more memory compared to the string literal approach.

Immutability of Strings

  • Strings in Java are immutable, meaning they cannot be changed once created.

This is because:

  • It ensures thread safety.
  • Prevents unintended modifications by other parts of the program.

Overcoming Immutability

  • While strings are inherently immutable, you can change the reference to point to a different string.

To enforce immutability

  • Declare the string variable as?final.
  • Use string buffers or string builders for mutable string operations.
  • String buffers are thread-safe but slower due to synchronisation.
  • String builders are faster but not thread-safe.

Commonly Used String Methods

  • length(): Returns the length of the string.
  • charAt(int index): Returns the character at the specified index.
  • substring(int beginIndex): Returns a substring starting from the specified index.
  • substring(int beginIndex, int endIndex): Returns a substring between the specified begin and end indices.
  • toLowerCase(): Converts all characters in the string to lowercase.
  • toUpperCase(): Converts all characters in the string to uppercase.
  • indexOf(String str): Returns the index of the first occurrence of the specified substring.
  • lastIndexOf(String str): Returns the index of the last occurrence of the specified substring.
  • replace(char oldChar, char newChar): Replaces all occurrences of a specified character with another character.
  • startsWith(String prefix): Checks if the string starts with the specified prefix.
  • endsWith(String suffix): Checks if the string ends with the specified suffix.

Happy Coding!

要查看或添加评论,请登录

Dinuka Ekanayake的更多文章

社区洞察

其他会员也浏览了