Last modified: January 07, 2023
Strings are used for storing text data.
In JavaScript, strings are created by either using the ""
double quote or '
single quote.
In Java, only "
double quote is accepted for creating string, but not the single quote.
When creating a String variable, use the following syntax:
String greeting = "Hello World";
To combine different strings together, use the plus sign:
String anotherGreeting = greeting + " hello again";
In Java, You cannot compare different strings by using ==
You must use the .equals()
method like this:
"abc" == "abc" // DON'T. This would be evaluated as false
"abc".equals("abc"); // true
"abc".equals("ABC"); // false
"abc".equals("edf"); // false
Unlike int, double, boolean, and other primitive data types, String is a non-primitive data type.
Everytime you create String something = "something"
,
behind the scene, Java is treating it as String something = new String()
and then append each character from "something" to the newly created String object.
Simply put, every Java string is a different object. Although two strings may look the same, they are created at different times in different places, and == will treat them as different strings.
To correctly compare two strings in Java, use the .equals()
method.
Behind the scene of this method, Java is comparing every character one by one and determines if every character matches.
To get the length of a string, use the .length()
method on a string:
System.out.println(greeting.length()); // this works
System.out.println(greeting.length); // this does NOT work. You need the parenthesis.
To convert a string to upper case or lower case, you can:
System.out.println(greeting.toUpperCase()); // prints out HELLO WORLD!
System.out.println(greeting.toLowerCase); // prints out hello world!
To determine if a string contains a particular string you are looking for, you can:
greeting.contains("whatsup"); // returns false
greeting.contains("Hello"); // returns true
greeting.contains("hello"); // returns false because case doesn't match
To determine the starting index of a particular substring in Java, you can:
System.out.println(greeting.indexOf("Hello")); // prints out 0
System.out.println(greeting.indexOf("World")); // prints out 6
System.out.println(greeting.indexOf("whatsup")); // prints out -1 because it doesn't exist
System.out.println(greeting.indexOf("hello")); // prints out -1 because case doesn't match
In Java, String has many more built-in methods than the ones listed above.
To see the complete list of Java String methods, you can visit its official documentation here.