java tutorial - Java - Strings and methods of the String class - java programming - learn java - java basics - java for beginners



Strings - represent a sequence of characters. The strings in Java are widely used and are objects.

  • The Java platform provides a class string (class String) for creating and working with strings.

Creating Strings

The easiest way to create a string is:

String greeting = "Welcome to Wikitechy Tutorials!";
click below button to copy the code. By - java tutorial - team
  • After every time the compiler encounters a string literal in the code, it creates a string object (String) with a value, in this case "Hello world!".
  • As with other objects, you can create string objects using the new keyword and the constructor.
  • The row class has eleven constructors that allow you to provide the initial value of a string using various sources, such as an array of characters.

Sample Code

public class Test {

   public static void main(String args[]){
      char[] helloArray = { 'a', 'n', 'd', 'r', 'е', 'w', 's'};
      String helloString = new String(helloArray);  
      System.out.println(helloString);
   }
}
click below button to copy the code. By - java tutorial - team

Output :

andrеws
  • Note: The row class is immutable, so that once it is created; the string object cannot be changed. If you need to make many changes to the character string, you should use the String Buffer classes and the String Builder Classes.

Length of the string

  • The methods used to obtain information about an object are known as access methods. One of the access methods that you can use with strings is the length () method, it returns the number of characters contained in the string object.
  • Below is an example of the length () method, which will help determine the length of a string.

Sample Code

public class Test {

   public static void main(String args[]) {
      String s = "Hi.Welcome to wikitechy!!!!";
      int len = s.length();
      
      System.out.println("Line length:" + len + "character.");
   }
}
click below button to copy the code. By - java tutorial - team

Output :

Line length:27character.

Merge lines in Java

The row class includes a method for combining two strings:

string1.concat(string2);
click below button to copy the code. By - java tutorial - team
  • Returns a new string string1, with the string string added at the end. You can also use Method concat () with string literals:
"My name is" .concat("Wikitechy");
click below button to copy the code. By - java tutorial - team
  • More often, lines are joined by the + operator:
"Hi," + "Welcome to wikitechy" + "!"
click below button to copy the code. By - java tutorial - team

That leads to:

Hi,Welcome to wikitechy!
click below button to copy the code. By - java tutorial - team

Let's look at the following Example.

Sample Code

public class Test {

   public static void main(String args[]) {
      String string1 = "Wikitechy";
      System.out.println("Welcome to "+ string1 +" Website!");
   }
}
click below button to copy the code. By - java tutorial - team

Output :

Welcome to Wikitechy Website! 

Creating a string format

  • We have already studied the Printf () and format () methods for printing with formatted numbers.
  • The Java class has an equivalent Method format (), which returns a string object, not a stream object PrintStream).
  • Using the string static Methoda format () allows you to create a string of the desired format that you can reuse, unlike single-use print statements. OnExample instead of:
System.out.printf("Value of variable float = " +
                   "%f, while the value of integer " +
                   "variable = %d, and string " +
                   "= %s", floatVar, intVar, stringVar);
click below button to copy the code. By - java tutorial - team

You can also write:

String fs;
fs = String.format ("The value of the variable float =" +
                   "% f, as long as integer" +
                   "variable =% d, and string" +
                   "=% s", floatVar, intVar, stringVar);
System.out.println (fs);
click below button to copy the code. By - java tutorial - team

Row class methods

  • Below is a list of the methods supported by the row class.
NO Methods Description
1 char charAt (int index) Returns the character at the specified index.
2 int compareTo (Object o) Compares this string to another object.
3 int compareTo (String anotherString) Compares two lines lexically.
4 int compareToIgnoreCase (String str) Compares two lines lexically, ignoring the case of letters.
5 String concat (String str) Combines the specified string with this string by appending it at the end.
6 boolean contentEquals (StringBuffer sb) Returns true only if this string is the same string as the string buffer (StringBuffer).
7 static String copyValueOf (char [] data) Returns a string that represents a sequence of characters in the specified array.
8 static String copyValueOf (char [] data,
int offset, int count)
Returns a string that is a sequence of characters in the specified array.
9 boolean endsWith (String suffix) Checks if this string ends with the specified ending.
10 boolean equals (Object anObject) Compares this string to the specified object.
11 boolean equalsIgnoreCase (String anotherString) Compares this string to another string, ignoring the case of letters.
12 byte getBytes () It encodes the given string into a sequence of bytes by utilizing a charset platform, saving the outcome to a new byte array.
13 byte [] getBytes (String charsetName Encodes this string into a sequence of bytes by using the charset platform, saving the result to a new byte array.
14 void getChars (int srcBegin,
int srcEnd, char [] dst, int dstBegin)
Copy the characters from this string into an array of destination symbols.
15 int hashCode () It returns the hash code for this string.
16 int indexOf (int ch) It returns the index of the first occurrence of the specified character in this string.
17 int indexOf (int ch, int fromIndex) It returns the index of the first occurrence of the specified character in the given string, starts the search from the specified index.
18 int indexOf (String str) It returns index of the first occurrence of the specified substring in this string.
19 int indexOf (String str, int fromIndex) It returns the index of the first occurrence of the specified substring in this string, starts the search from the specified index.
20 String intern () It returns the canonical representation for the string object.
21 int lastIndexOf (int ch) Returns the index of the last occurrence of the specified character in this line.
22 int lastIndexOf (int ch, int fromIndex) Returns the index of the last occurrence of the specified character in this string, starting reverse search from the specified index.
23 int lastIndexOf (String str) Returns the index of the last occurrence of the specified substring in this string.
24 int lastIndexOf (String str, int fromIndex) Returns the index of the last occurrence of the specified substring in this string, starting reverse search from the specified index.
25 int length () Returns the length of the string.
26 boolean matches (String regex) Tells whether or not this string matches a given regular expression.
27 boolean regionMatches (boolean ignoreCase,
int toffset, String other,
int ooffset, int len)
Checks if two areas of a line are equal.
28 boolean regionMatches (int toffset,
String other, int ooffset, int len)
Checks if two areas of a line are equal.
29 String replace (char oldChar, char newChar) Returns a new string, replacing all occurrences of oldChar in this line with newChar.
30 String replaceAll (String regex,
String replacement)
Replaces every substring of a string that matches a given regular expression with a given substitution.
31 String replaceFirst (String regex,
String replacement)
Replaces the first substring of the given string that corresponds to the specified regular expression with this substitution.
32 String [] split (String regex) Splits this string around this regular expression.
33 String [] split (String regex, int limit) Separates this string surrounding this regular expression.
34 boolean startsWith (String prefix) Checks whether this string begins with the prefix specified.
35 boolean startsWith (String prefix, int toffset) Checks whether this string starts with the specified prefix starting at the specified index.
36 CharSequence subSequence (int beginIndex,
int endIndex)
Returns a new sequence of characters, which is a subsequence of this sequence.
37 String substring (int beginIndex) Returns a new string that is a substring of this string.
38 String substring (int beginIndex, int endIndex) Returns a new string that is a substring of this string.
39 char [] toCharArray () Converts this string into a new array of characters.
40 String toLowerCase () Converts all the characters in this string to lowercase using the rules of this locale.
41 String toLowerCase (Locale locale) Converts all the characters in a given string into lowercase using the rules of this locale.
42 String toString () This object (that is already a string!) return by itself.
43 String toUpperCase () Converts all characters in a string to upper case using the rules of this locale.
44 String toUpperCase (Locale locale) Converts all characters in a string to upper case using the rules of this locale.
45 String trim () Returns a copy of the string with missing leading and trailing spaces.
46 static String valueOf (primitive data type x) Returns the string representation of the passed data type of the argument.

Related Searches to Java - Strings and methods of the String class