w3resource

Java: Create a new string taking first three characters from a given string


First 3 Chars or #

Write a Java program to create a string taking the first three characters from a given string. If the string length is less than 3 use "#" as substitute characters.

Test Data: str1 = "Python"
str2 = " "

Sample Solution:

Java Code:

import java.lang.*;

public class Exercise72 {
    public static void main(String[] args) {
        // Define an empty string
        String str1 = "";

        // Get the length of the string
        int len = str1.length();

        // Check the length of the string and take different actions based on its length
        if (len >= 3) {
            // If the string has three or more characters, print the first three characters
            System.out.println(str1.substring(0, 3));
        } else if (len == 1) {
            // If the string has only one character, add "##" to it and print
            System.out.println(str1.charAt(0) + "##");
        } else {
            // If the string is empty or has two characters, print "###"
            System.out.println("###");
        }
    }
}

Sample Output:

###

Pictorial Presentation:

Java exercises: Create a new string taking first three characters from a given string


Java exercises: Create a new string taking first three characters from a given string


Flowchart:

Flowchart: Java exercises: Create a new string taking first three characters from a given string


For more Practice: Solve these Related Problems:

  • Modify the program to replace missing characters with "*".
  • Write a program to take the last 3 characters instead of the first.
  • Modify the program to repeat the extracted characters twice.
  • Write a program to handle empty strings without errors.

Go to:


PREV : Remove First Char and Concatenate.
NEXT : First and Last Char Combo.


Java Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.