JAVA IO - JAVA: Learn JAVA Quickly (2017)

JAVA: Learn JAVA Quickly (2017)

CHAPTER 4. JAVA IO

Buffered Reader

As we saw, System.out is output stream. Opposite of that is System.in,input stream. In new class JavaIO inside main method add following lines:

BufferedReader in = newBufferedReader(new InputStreamReader(System.in));

System.out.print("Type your name: ");

String name = in.readLine();

System.out.println("Your name is: " + name);

System.out.print("Type your height: ");

intheight = Integer.parseInt(in.readLine());

System.out.println("Your height is: " + height);

There will be some errors. It says: “Unhandled exception type IOException”

Note: To fix this problem click on red alert and Add throws declaration. Now main method will throw exception if it occurs.

Run program.

expected: Type your name: will be printed to console

Type your height:

Also, we can see import section between package and class name. Java packages are used for better organization of java libraries and classes. In this case we can see that java.io package is imported from whose are derived methods inside our current class.

WRAPPER CLASSES

Wrapper classes are used when something is typed that is nota String. Every primitive type has his own Wrapper class.

· int -> Integer

· long -> Long

· boolean -> Boolean

Wrapper classes are doing automatic boxing and unboxing (conversion primitive types to objects and vice versa) using XXXparseXXX method. For example:

inti = Integer.parseInt("10");

longl = Long.parseLong("10");

SCANNER

Alternative for this is class Scanner, which can read both primitive types and Strings. Scanner is using delimiter to break input into tokens. Delimiter is whitespace by default. Try to run this code:

StringyourName;

intyourHeight;

Scanner sc = newScanner(System.in);

System.out.print("Enter your name: ");

yourName = sc.nextLine();

System.out.println("Your name is: " + yourName);

System.out.print("Enter your height: ");

yourHeight = sc.nextInt();

System.out.println("Your height is: " + yourHeight);

expected: Enter your name will be printed to console

Enter your height

Good practice is to close operations at the end of program using:

sc.close();

Try to make something different on your own. Use other primitive types, first for Buffered Reader and then for Scanner. Which method will be for float?

Did you figured out that Buffered Reader and Scanner have different methods,

readLine() and nextLine()?