C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

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

Liked this article? Do share with your friends :)