Java Tutorial

Operators

Flow Control

String

Number and Date

Built-in Classes

Array

Class and Object

Inheritance and Polymorphism

Exception Handling

Collections, Generics and Enumerations

Reflection

Input/Output Stream

Annotation

Java String Query

In Java, querying a string refers to the process of searching, extracting, or manipulating data within a string. The String class provides several methods that can be used to perform various operations on strings. In this tutorial, we will cover some common string querying methods in Java.

  • Finding the length of a string:

You can find the length of a string using the length() method.

Example:

String str = "Hello, World!";
int length = str.length();
System.out.println("Length: " + length); // Output: Length: 13
  • Searching for a character or substring:

You can search for a character or a substring within a string using the indexOf() and lastIndexOf() methods.

Example:

String str = "Hello, World!";
int index = str.indexOf('o');
System.out.println("First index of 'o': " + index); // Output: First index of 'o': 4

index = str.lastIndexOf('o');
System.out.println("Last index of 'o': " + index); // Output: Last index of 'o': 8
  • Extracting a substring:

You can extract a substring from a string using the substring() method.

Example:

String str = "Hello, World!";
String sub = str.substring(7, 12);
System.out.println("Substring: " + sub); // Output: Substring: World
  • Comparing strings:

You can compare two strings using the equals() and equalsIgnoreCase() methods.

Example:

String str1 = "Hello";
String str2 = "hello";

boolean isEqual = str1.equals(str2);
System.out.println("Strings are equal: " + isEqual); // Output: Strings are equal: false

isEqual = str1.equalsIgnoreCase(str2);
System.out.println("Strings are equal (ignoring case): " + isEqual); // Output: Strings are equal (ignoring case): true
  • Replacing characters or substrings:

You can replace characters or substrings within a string using the replace(), replaceAll(), and replaceFirst() methods.

Example:

String str = "Hello, World!";
str = str.replace('o', 'O');
System.out.println("Replaced 'o' with 'O': " + str); // Output: Replaced 'o' with 'O': HellO, WOrld!
  • Splitting a string:

You can split a string into an array of substrings based on a delimiter using the split() method.

Example:

String str = "apple,banana,orange";
String[] fruits = str.split(",");

for (String fruit : fruits) {
    System.out.println(fruit);
}

Output:

apple
banana
orange
  • Converting case:

You can convert a string to uppercase or lowercase using the toUpperCase() and toLowerCase() methods.

Example:

String str = "Hello, World!";
str = str.toUpperCase();
System.out.println("Uppercase: " + str); // Output: Uppercase: HELLO, WORLD!

str = str.toLowerCase();
System.out.println("Lowercase: " + str); // Output: Lowercase: hello, world!

In this tutorial, we covered some common string querying methods in Java, including finding the length, searching for characters or substrings, extracting substrings, comparing strings, replacing characters or substrings, splitting a string, and converting the case. These methods provide a basic toolkit for working with strings in Java applications.

  1. String Handling in Java:

    • Strings in Java are objects of the String class. They are immutable, meaning their values cannot be changed after creation.
    String myString = "Hello, Java!";
    
  2. Java String Methods and Examples:

    • The String class provides various methods for string manipulation, such as length(), charAt(), toUpperCase(), toLowerCase(), etc.
    String myString = "Hello, Java!";
    int length = myString.length();
    char firstChar = myString.charAt(0);
    
  3. Substring in Java:

    • The substring() method is used to extract a portion of a string.
    String original = "Hello, Java!";
    String subString = original.substring(7); // "Java!"
    
  4. Concatenating Strings in Java:

    • Strings can be concatenated using the + operator or the concat() method.
    String str1 = "Hello";
    String str2 = "Java";
    String result = str1 + ", " + str2; // "Hello, Java"
    
  5. Parsing Strings in Java:

    • Parsing involves converting a string representation of data into its corresponding data type.
    String numStr = "123";
    int num = Integer.parseInt(numStr); // 123
    
  6. String Comparison in Java:

    • String comparison can be done using the equals() method for content equality or compareTo() method for lexicographical comparison.
    String str1 = "Hello";
    String str2 = "Hello";
    boolean isEqual = str1.equals(str2); // true
    
  7. Searching for a Substring in Java:

    • The indexOf() and lastIndexOf() methods are used to find the index of a substring within a string.
    String sentence = "Java is fun and Java is powerful";
    int firstIndex = sentence.indexOf("Java"); // 0
    
  8. Regular Expressions for String Matching in Java:

    • Regular expressions provide a powerful way to match patterns in strings.
    String text = "The price is $20";
    boolean hasPrice = text.matches(".*\\$\\d+.*"); // true
    
  9. Replacing Characters in a Java String:

    • The replace() method is used to replace characters or substrings in a string.
    String message = "Hello, World!";
    String updatedMessage = message.replace("World", "Java"); // "Hello, Java!"
    
  10. StringBuilder and StringBuffer in Java:

    • StringBuilder and StringBuffer are mutable alternatives to String when frequent modifications are required.
    StringBuilder sb = new StringBuilder("Hello");
    sb.append(", Java!"); // "Hello, Java!"
    
  11. StringTokenizer in Java:

    • StringTokenizer is used to break a string into tokens (words).
    String sentence = "Java is fun";
    StringTokenizer tokenizer = new StringTokenizer(sentence);
    while (tokenizer.hasMoreTokens()) {
        String word = tokenizer.nextToken();
        // Process each word
    }
    
  12. Java String Formatting:

    • String.format() and printf() methods allow formatting strings with placeholders.
    String formattedString = String.format("Name: %s, Age: %d", "John", 25);
    System.out.printf("Name: %s, Age: %d", "John", 25);