ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.