Q:

Java program to read strings with different methods

belongs to collection: Java String Programs

0

Java program to read strings with different methods

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to get length of the string in java?... >>