OOP(lesson1&2)

Cards (22)

  • Strings
    Used for storing text-based data in programming
  • String class
    Immutable and non-primitive data type used to store the characters of the sequence
  • Ways to compare strings in Java
    • Equality operator ==
    • equals() method
    • compareTo() method
  • Equality operator ==
    Compares two strings
  • The == operator does not work when comparing two string objects</b>
  • equals() method

    Compares the original content of the string
  • equalsIgnoreCase() method
    Compares two strings, ignoring case
  • compareTo() method
    Compares two strings lexicographically and returns an integer value
  • endsWith() method

    Checks whether the given string ends with the specified string suffix
  • startsWith() method

    Checks whether the given string starts with the specified string prefix
  • regionMatches() method

    Tests if two string regions are matching or equal
  • Immutability is the biggest problem of Java String if not used correctly
  • Mutable string
    A string that can be modified or changed
  • StringBuffer

    A mutable sequence of characters
  • StringBuffer
    • Mutable, initial capacity can be specified, append() method to add characters, insert() method to insert characters, delete() method to remove characters, reverse() method to reverse the order of characters
  • StringBuffer constructors

    StringBuffer(), StringBuffer(String str), StringBuffer(int capacity)
  • StringBuilder
    A mutable sequence of characters, differs from StringBuffer in terms of synchronization
  • Where possible, it is recommended to use StringBuilder in preference to StringBuffer as it will be faster under most implementations
  • Instances of StringBuilder are not safe for use by multiple threads
  • If synchronization is required, it is recommended to use StringBuffer
  • StringBuilder constructors
    StringBuilder(), StringBuilder(String str), StringBuilder(int length)
  • Differences between String, StringBuffer, and StringBuilder
    • String is immutable, StringBuffer is synchronized, StringBuilder is not synchronized
    • Concatenation operator "+" is internally implemented using either StringBuffer or StringBuilder
    • Use String if you require immutability, use StringBuffer if you need mutable + thread-safety, use StringBuilder if you require mutable + without thread-safety