Java Program to Print a String


In this article, we will understand how to print a string in Java. A string is a pattern of characters and alphanumeric values. The easiest way to create a string is to write −

String str = "Welcome to the club!!!"

Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, " Welcome to the club!!!'.

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has 11 constructors that allow you to provide the initial value of the string using different sources, such as an array of characters.

In Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings. The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then use String Buffer & String Builder Classes.

Input

Suppose our input is −

Hello my name is John!

Output

The desired output would be −

The string is:
Hello my name is John!

Algorithm

Step 1- START
Step-2- Declare a string
Step 3- Prompt the user to enter a string/ define the string in a variable
Step 4- Read the value
Step 5- Display it on the console
Step 6- STOP

Example 1

Here, the input is being entered by the user based on a prompt. You can try this example live in our coding ground tool run button.

import java.util.Scanner;
public class PrintString {
   public static void main(String[] args){
      String my_str;
      System.out.println("The required packages have been imported ");
      Scanner my_scan = new Scanner(System.in);
      System.out.print("A scanner object has been defined \n");
      System.out.print("Enter a string:");
      my_str = my_scan.nextLine();
      System.out.print("The nextLine method is used to read the string");
      System.out.println("The string is: ");
      System.out.println(my_str);
   }
}

Output

Required packages have been imported
A scanner object has been defined
Enter a string: Hello my name is John!
The nextLine method is used to read the stringThe string is:
Hello my name is John!

Example 2

public class PrintString{
   public static void main(String[] args){
      String my_str;
      System.out.println("The required packages have been imported ");
      my_str = "Hello my name is John!";
      System.out.println("The string is: ");
      System.out.println(my_str);
   }
}

Output

The required packages have been imported
The string is:
Hello my name is John!

Updated on: 18-Feb-2022

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements