String in Java

In Java, a string is a group of letters, numbers, or symbols put together. Once a string is created, it cannot be changed. There are two ways to create a string in Java:

  1. Using a string literal by putting the string in double quotes. For example: String s = “GeeksforGeeks”;

  2. Using the new keyword to create a string. For example: String s = new String (“GeeksforGeeks”);

There are many constructors that can be used to create a string. Here are some examples:

  1. String(byte[] byte_arr) - Creates a new string by decoding the byte array. It uses the platform's default character set for decoding.

  2. String(byte[] byte_arr, Charset char_set) - Creates a new string by decoding the byte array. It uses the char_set for decoding.

  3. String(byte[] byte_arr, String char_set_name) - Creates a new string by decoding the byte array. It uses the char_set_name for decoding.

  4. String(byte[] byte_arr, int start_index, int length) - Creates a new string from the byte array depending on the start_index (starting location) and length (number of characters from starting location).

  5. String(byte[] byte_arr, int start_index, int length, Charset char_set) - Creates a new string from the byte array depending on the start_index and length. It uses the char_set for decoding.

  6. String(byte[] byte_arr, int start_index, int length, String char_set_name) - Creates a new string from the byte array depending on the start_index and length. It uses the char_set_name for decoding.

  7. String(char[] char_arr) - Creates a new string from the given Character array.

  8. String(char[] char_array, int start_index, int count) - Creates a new string from a given character array but chooses count characters from the start_index.

  9. String(int[] uni_code_points, int offset, int count) - Creates a new string from a uni_code_array but chooses count characters from the start_index.

  10. String(StringBuffer s_buffer) - Creates a new string from the string in s_buffer.

  11. String(StringBuilder s_builder) - Creates a new string from the string in s_builder.

These constructors are used to create different types of strings from different sources. For example, you can create a string from a byte array, a character array, or a StringBuilder. By using these constructors, you can create strings that suit your needs.

Previous Post Next Post