In this lesson, you will learn
In Java, strings are objects that represent sequences of characters. The String class provides several constructors for creating strings.
Here are the primary constructors used to create strings in Java, along with examples.
Creates an empty string. This constructor is not often used since strings are immutable, and you can’t change an empty string afterward.
String str = new String();
// Creates an empty string
To create a String initialized by an array of characters, use the following constructor
Constructor: public String(char chars[ ])
char[] charArray = {'H', 'e', 'l', 'l', 'o'};
String str = new String(charArray);
/* Creates a string "Hello" from an
array of characters */
You can specify a subrange of a character array as an initializer using the following constructor:
Constructor: public String(char chars[ ], int startIndex, int numChars)
Here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of characters to use.
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
//This initializes s with the characters cde.
You can construct a String object that contains the same character sequence as another String object using this constructor.
Constructor: public String(String strObj)
Here, strObj is a String object.
package ch11.l2;
public class CreateString {
public static void main(String[] args) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
System.out.println("s1==s2: "+(s1==s2));
//check equality of objects
}
}
Java
Java
s1==s2: false
Constructs a new String by decoding an array of bytes using the platform’s default charset.
public String(byte chrs[ ])
public String(byte chrs[ ], int startIndex, int numChars)
Here, chrs specifies the array of bytes. The second form allows you to specify a subrange.
Example
package ch11.l2;
public class MakeStringFromByteArray {
public static void main(String[] args) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
ABCDEF
CDE
String that contains characters from a substring(int beginIndex) and substring(int beginIndex, int endIndex) of an existing String.beginIndex and extends to the character at index endIndex - 1.
String original = "Hello, World!";
String str = new String(original.substring(0, 5));
/* Creates a string "Hello" from a
substring of "Hello, World!" */
String that represents the same sequence of characters as the content of the StringBuilder or StringBuffer.Constructors
public String(StringBuffer strBufObj)
public String(StringBuilder strBuildObj)
StringBuilder sb = new StringBuilder("Hello");
String str = new String(sb);
// Creates a string "Hello" from a StringBuilder
String myage = "21";
String s1 = "He is " + myage + " years old.";
System.out.println(s1); //"He is 21 years old."
int myage = 21;
String s1 = "He is " + myage + " years old.";
System.out.println(s1); //"He is 21 years old."
String s = "four: " + 2 + 2;
System.out.println(s); //four: 22
String s = "four: " + (2 + 2); //four: 4
toString() method is a public method provided by the Object class, which is the superclass of all classes in Java.toString() method from the Object class.
package ch11.l2;
class Person{
public String name;
public int age;
public String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
}
public class ToStringExample {
public static void main(String[] args) {
Person p1=new Person("Amit", 27, "Male");
Person p2=new Person("Riya", 23, "Female");
System.out.println(p1);//compiler writes here p1.toString()
System.out.println(p2);//compiler writes here p1.toString()
}
}
ch11.l2.Person@7cc355be
ch11.l2.Person@6e8cf4c6
package ch11.l2;
class Person{
public String name;
public int age;
public String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", "
+ "gender=" + gender + "]";
}
}
public class ToStringExample {
public static void main(String[] args) {
Person p1=new Person("Amit", 27, "Male");
Person p2=new Person("Riya", 23, "Female");
System.out.println(p1);//compiler writes here p1.toString()
System.out.println(p2);//compiler writes here p1.toString()
}
}
Person [name=Amit, age=27, gender=Male]
Person [name=Riya, age=23, gender=Female]
Below is a summarized table of some commonly used String methods, categorized by their purpose with examples.
| Method | Description | Example |
|---|---|---|
charAt(int index) |
Returns the character at the specified index. | String s = "example"; char c = s.charAt(2); // 'a' |
compareTo(String anotherString) |
Compares two strings lexicographically. | String s1 = "hello"; String s2 = "world"; int result = s1.compareTo(s2); // Negative value |
concat(String str) |
Concatenates the specified string to the end of this string. | String s1 = "hello "; String s2 = s1.concat("world"); // "hello world" |
contains(CharSequence s) |
Returns true if and only if this string contains the specified sequence of char values. | String s = "example"; boolean contains = s.contains("amp"); // true |
endsWith(String suffix) |
Tests if this string ends with the specified suffix. | String s = "example"; boolean endsWith = s.endsWith("ple"); // true |
equals(Object anObject) |
Compares this string to the specified object. | String s1 = "hello"; String s2 = "hello"; boolean equals = s1.equals(s2); // true |
equalsIgnoreCase(String anotherString) |
Compares this String to another String, ignoring case considerations. | String s1 = "Hello"; String s2 = "hello"; boolean equalsIgnoreCase = s1.equalsIgnoreCase(s2); // true |
indexOf(int ch) |
Returns the index within this string of the first occurrence of the specified character. | String s = "example"; int index = s.indexOf('a'); // 2 |
isEmpty() |
Returns true if, and only if, length() is 0. | String s = ""; boolean isEmpty = s.isEmpty(); // true |
length() |
Returns the length of this string. | String s = "example"; int length = s.length(); // 7 |
replace(char oldChar, char newChar) |
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. | String s = "example"; String replaced = s.replace('e', 'a'); // "axampla" |
split(String regex) |
Splits this string around matches of the given regular expression. | String s = "one,two,three"; String[] parts = s.split(","); // ["one", "two", "three"] |
startsWith(String prefix) |
Tests if this string starts with the specified prefix. | String s = "example"; boolean startsWith = s.startsWith("ex"); // true |
substring(int beginIndex) |
Returns a new string that is a substring of this string. | String s = "example"; String sub = s.substring(3); // "mple" |
toCharArray() |
Converts this string to a new character array. | String s = "example"; char[] chars = s.toCharArray(); // ['e', 'x', 'a', 'm', 'p', 'l', 'e'] |
toLowerCase() |
Converts all of the characters in this String to lower case. | String s = "Example"; String lower = s.toLowerCase(); // "example" |
toUpperCase() |
Converts all of the characters in this String to upper case. | String s = "example"; String upper = s.toUpperCase(); // "EXAMPLE" |
trim() |
Returns a string whose value is this string, with any leading and trailing whitespace removed. | String s = " example "; String trimmed = s.trim(); // "example" |
Very well made pdf, easy to understand, got the concept in one reading
You must be logged in to submit a review.