Home » Java programs » Java basic programs

Java program to read strings with different methods

In this article, we are going to read string with two different methods StringReader and Scanner class with example, output and explanation.
Submitted by IncludeHelp, on November 24, 2017

In this java program, we have to read strings using 'StringReader' and 'Scanner' class.

Read string using StringReader class

import java.io.IOException;
import java.io.StringReader;

public class ReadString1 
	public static void main(String[] args) 
	     String s = "Hello World";
	     // create a new StringReader
	     StringReader sr = new StringReader(s);
	         // read the first five chars
	         for (int i = 0; i < 5; i++)
	            char c = (char) sr.read();
	            System.out.print(" " + c);
	         // close the stream
         catch (IOException ex) 


H e l l o

Read String using Scanner class

import java.util.Scanner;

public class ReadString
	 public static void main(String args[])
		 // initialize and declare here.
		 int id;
		 String name;
		 // create scanner class object.
         Scanner scanner = new Scanner(System.in);
         // enter the detail.
         System.out.print("Enter Employeeid : ");
         System.out.print("Enter EmployeeName : ");
         System.out.print("Id : " +id+ "\nName : " +name);


Enter Employeeid : 101
Enter EmployeeName : Chandra Shekhar
Id : 101
Name : Chandra Shekhar

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.

Comments and Discussions

We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.