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

This an example of Java string programs, 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);
         try 
         {
	         // read the first five chars
	         for (int i = 0; i < 5; i++)
	         {
	            char c = (char) sr.read();
	            System.out.print(" " + c);
	         }
	         // close the stream
	         sr.close();
	     }
         catch (IOException ex) 
         {
	         ex.printStackTrace();
	     }
	}
}

Output

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 : ");
              id=(scanner.nextInt());
         System.out.print("Enter EmployeeName : ");
              name=(scanner.next());    
         System.out.print("Id : " +id+ "\nName : " +name);
     }
}

Output

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

Java String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.