0% found this document useful (0 votes)
3 views

java unit3

The document explains Java's wrapper classes, including autoboxing and unboxing, which facilitate the conversion between primitive data types and their corresponding wrapper classes. It also covers the String and StringBuffer classes, highlighting their differences in mutability and methods for string manipulation. Additionally, the document discusses exception handling in Java, detailing the types of exceptions, the try-catch mechanism, and the importance of maintaining the normal flow of an application.

Uploaded by

sirisha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

java unit3

The document explains Java's wrapper classes, including autoboxing and unboxing, which facilitate the conversion between primitive data types and their corresponding wrapper classes. It also covers the String and StringBuffer classes, highlighting their differences in mutability and methods for string manipulation. Additionally, the document discusses exception handling in Java, detailing the types of exceptions, the try-catch mechanism, and the importance of maintaining the normal flow of an application.

Uploaded by

sirisha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

1

Wrapper classes
Parser methods
Converting Back from String object to Primitives:
The six parser methods are
parseInt
parseFloat
parseDouble
parseShort
parseByte
parselong
They take String as an argument convert it to the corresponding primitive.
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper
class is known as autoboxing, for example, byte to Byte, char to Character, int to
Integer, long to Long, float to Float, boolean to Boolean, double to Double, and
short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to
convert the primitive into objects.
Wrapper class Example: Primitive to Wrapper
1. //Java program to convert primitive into objects
2. //Autoboxing example of int to Integer
3. public class WrapperExample1{
4. public static void main(String args[]){
5. //Converting int into Integer
6. int a=20;
7. Integer i=Integer.valueOf(a);//converting int into Integer explicitly
8. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
2

9.
10. System.out.println(a+" "+i+" "+j);
11. }}
Output:
20 20 20
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is
known as unboxing. It is the reverse process of autoboxing. Since Java 5, we do
not need to use the intValue() method of wrapper classes to convert the wrapper
type into primitives.
Wrapper class Example: Wrapper to Primitive
1. //Java program to convert object into primitives
2. //Unboxing example of Integer to int
3. public class WrapperExample2{
4. public static void main(String args[]){
5. //Converting Integer to int
6. Integer a=new Integer(3);
7. int i=a.intValue();//converting Integer to int explicitly
8. int j=a;//unboxing, now compiler will write a.intValue() internally
9.
10. System.out.println(a+" "+i+" "+j);
11. }}
Output:
333
Java Wrapper classes Example
1. //Java Program to convert all primitives into its corresponding
2. //wrapper objects and vice-versa
3. public class WrapperExample3{
4. public static void main(String args[]){
5. byte b=10;
6. short s=20;
7. int i=30;
8. long l=40;
3

9. float f=50.0F;
10. double d=60.0D;
11. char c='a';
12. boolean b2=true;
13.
14. //Autoboxing: Converting primitives into objects
15. Byte byteobj=b;
16. Short shortobj=s;
17. Integer intobj=i;
18. Long longobj=l;
19. Float floatobj=f;
20. Double doubleobj=d;
21. Character charobj=c;
22. Boolean boolobj=b2;
23.
24. //Printing objects
25. System.out.println("---Printing object values---");
26. System.out.println("Byte object: "+byteobj);
27. System.out.println("Short object: "+shortobj);
28. System.out.println("Integer object: "+intobj);
29. System.out.println("Long object: "+longobj);
30. System.out.println("Float object: "+floatobj);
31. System.out.println("Double object: "+doubleobj);
32. System.out.println("Character object: "+charobj);
33. System.out.println("Boolean object: "+boolobj);
34.
35. //Unboxing: Converting Objects to Primitives
36. byte bytevalue=byteobj;
37. short shortvalue=shortobj;
38. int intvalue=intobj;
39. long longvalue=longobj;
40. float floatvalue=floatobj;
41. double doublevalue=doubleobj;
42. char charvalue=charobj;
43. boolean boolvalue=boolobj;
4

44.
45. //Printing primitives
46. System.out.println("---Printing primitive values---");
47. System.out.println("byte value: "+bytevalue);
48. System.out.println("short value: "+shortvalue);
49. System.out.println("int value: "+intvalue);
50. System.out.println("long value: "+longvalue);
51. System.out.println("float value: "+floatvalue);
52. System.out.println("double value: "+doublevalue);
53. System.out.println("char value: "+charvalue);
54. System.out.println("boolean value: "+boolvalue);
55. }}
Output:
---Printing object values---
Byte object: 10
Short object: 20
Integer object: 30
Long object: 40
Float object: 50.0
Double object: 60.0
Character object: a
Boolean object: true
---Printing primitive values---
byte value: 10
short value: 20
int value: 30
long value: 40
float value: 50.0
double value: 60.0
char value: a
boolean value: true

String class
5

String is a sequence of characters. In java, objects of String are immutable which


means a constant and cannot be changed once created.
Creating a String
There are two ways to create string in Java:
 String literal
String s = “SAPCOLLEGE”;
Using new keyword
String s = new String (“SAPCOLLEGE”);

public class Example{


public static void main(String args[]){
//creating a string by java string literal
String str = "Beginnersbook";
String str1 = new String("Java String Example");
//Displaying all the three strings
System.out.println(str);
System.out.println(str1);
}
}
Output:

All String Methods


The String class has a set of built-in methods that you can use on strings.
Method Description Return Type

charAt() Returns the character at the specified char


6

index (position)

codePointAt() Returns the Unicode of the character at int


the specified index

codePointBefore() Returns the Unicode of the character int


before the specified index

codePointCount() Returns the Unicode in the specified int


text range of this String

compareTo() Compares two strings lexicographically int

compareToIgnoreCase() Compares two strings int


lexicographically, ignoring case
differences

concat() Appends a string to the end of another String


string

contains() Checks whether a string contains a boolean


sequence of characters

contentEquals() Checks whether a string contains the boolean


exact same sequence of characters of
the specified CharSequence or
StringBuffer

copyValueOf() Returns a String that represents the String


characters of the character array
7

endsWith() Checks whether a string ends with the boolean


specified character(s)

equals() Compares two strings. Returns true if boolean


the strings are equal, and false if not

equalsIgnoreCase() Compares two strings, ignoring case boolean


considerations

format() Returns a formatted string using the String


specified locale, format string, and
arguments

getBytes() Encodes this String into a sequence of byte[]


bytes using the named charset, storing
the result into a new byte array

getChars() Copies characters from a string to an void


array of chars

hashCode() Returns the hash code of a string int

indexOf() Returns the position of the first found int


occurrence of specified characters in a
string

intern() Returns the index within this string of String


the first occurrence of the specified
character, starting the search at the
specified index
8

isEmpty() Checks whether a string is empty or not boolean

lastIndexOf() Returns the position of the last found int


occurrence of specified characters in a
string

length() Returns the length of a specified string int

matches() Searches a string for a match against a boolean


regular expression, and returns the
matches

offsetByCodePoints() Returns the index within this String that int


is offset from the given index by
codePointOffset code points

regionMatches() Tests if two string regions are equal boolean

replace() Searches a string for a specified value, String


and returns a new string where the
specified values are replaced

replaceFirst() Replaces the first occurrence of a String


substring that matches the given regular
expression with the given replacement

replaceAll() Replaces each substring of this string String


that matches the given regular
expression with the given replacement

split() Splits a string into an array of String[]


9

substrings

startsWith() Checks whether a string starts with boolean


specified characters

subSequence() Returns a new character sequence that CharSequence


is a subsequence of this sequence

substring() Extracts the characters from a string, String


beginning at a specified start position,
and through the specified number of
character

toCharArray() Converts this string to a new character char[]


array

toLowerCase() Converts a string to lower case letters String

toString() Returns the value of a String object String

toUpperCase() Converts a string to upper case letters String

trim() Removes whitespace from both ends of String


a string

valueOf() Returns the primitive value of a String


object
10

StringBuffer class
StringBuffer class is used to create a mutable string object i.e its state can be
changed after it is created. It represents growable and writable character sequence.
As we know that String objects are immutable, so if we do a lot of changes
with String objects, we will end up with a lot of memory leak.
So StringBuffer class is used when we have to make lot of modifications to our
string. It is also thread safe i.e multiple threads cannot access it simultaneously.
StringBuffer defines 4 constructors. They are,
1. StringBuffer ( )
2. StringBuffer ( int size )
3. StringBuffer ( String str )
4. StringBuffer ( charSequence [ ]ch )

 StringBuffer() creates an empty string buffer and reserves room for 16


characters.
 stringBuffer(int size) creates an empty string and takes an integer argument to
set capacity of the buffer.

Example showing difference between String and StringBuffer


class Test {
public static void main(String args[])
{
String str = "study";
str.concat("tonight");
System.out.println(str); // Output: study

StringBuffer strB = new StringBuffer("study");


11

strB.append("tonight");
System.out.println(strB); // Output: studytonight
}
}
Reason:
Output is such because String objects are immutable objects. Hence, if we
concatenate on the same String object, it won't be altered(Output: study). But
StringBuffer creates mutable objects. Hence, it can be altered(Output:
studytonight)

Important methods of StringBuffer class


The following methods are some most commonly used methods of StringBuffer
class.
append()
This method will concatenate the string representation of any type of data to the
end of the invoking StringBuffer object. append() method has several overloaded
forms.
StringBuffer append(String str)

StringBuffer append(int n)

StringBuffer append(Object obj)


The string representation of each parameter is appended to StringBuffer object.
StringBuffer str = new StringBuffer("test");
str.append(123);
System.out.println(str);
12

test123

insert()
This method inserts one string into another. Here are few forms of insert() method.
StringBuffer insert(int index, String str)

StringBuffer insert(int index, int num)

StringBuffer insert(int index, Object obj)


Here the first parameter gives the index at which position the string will be inserted
and string representation of second parameter is inserted into StringBuffer object.
StringBuffer str = new StringBuffer("test");
str.insert(4, 123);
System.out.println(str);

test123

reverse()
This method reverses the characters within a StringBuffer object.
StringBuffer str = new StringBuffer("Hello");
str.reverse();
System.out.println(str);

olleH
13

replace()
This method replaces the string from specified start index to the end index.
<
StringBuffer str = new StringBuffer("Hello World");
str.replace( 6, 11, "java");
System.out.println(str);

Hello java

capacity()
This method returns the current capacity of StringBuffer object.
StringBuffer str = new StringBuffer();
System.out.println( str.capacity() );

16

Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
In Java, an exception is an event that disrupts the normal flow of the program. It is
an object which is thrown at runtime.
What is Exception Handling
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
14

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application
that is why we use exception handling. Let's take a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in your program and there occurs an exception at
statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not
be executed. If we perform exception handling, the rest of the statement will be
executed. That is why we use exception handling in Java.

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy which
is inherited by two subclasses: Exception and Error. A hierarchy of Java Exception
classes are given below:
15

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. Here, an error
is considered as the unchecked exception. According to Oracle, there are three
types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked Exceptions


1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and
Error are known as checked exceptions e.g. IOException, SQLException etc.
Checked exceptions are checked at compile-time.
16

2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions
e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Java try and catch
The try statement allows you to define a block of code to be tested for errors while
it is being executed.
The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.
The try and catch keywords come in pairs:
Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Consider the following example:
This will generate an error, because myNumbers[10] does not exist.
public class MyClass {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}
17

The output will be something like this:


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at MyClass.main(MyClass.java:4)

If an error occurs, we can use try...catch to catch the error and execute some code
to handle it:
Example
public class MyClass {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

The output will be:


Something went wrong.

Finally
The finally statement lets you execute code, after try...catch, regardless of the
result:
Example
public class MyClass {
public static void main(String[] args) {
18

try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}

The output will be:


Something went wrong.
The 'try catch' is finished.
The throw keyword
The throw statement allows you to create a custom error.
The throw statement is used together with an exception type. There are many
exception types available in
Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsEx
ception, SecurityException, etc.
The exception type is often used together with a custom method. Don't worry if
you don't understand the example below, you will learn more about methods in the
next chapter:
Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or
older, print "Access granted":
public class MyClass {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18
19

years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}

public static void main(String[] args) {


checkAge(15); // Set age to 15 (which is below 18...)
}
}

The output will be:


Exception in thread "main" java.lang.ArithmeticException: Access denied - You
must be at least 18 years old.
at MyClass.checkAge(MyClass.java:4)
at MyClass.main(MyClass.java:12)
If age was 20, you would not get an exception:
Example
checkAge(20);

The output will be:


Access granted - You are old enough!

User Defined Exception in Java


User Defined Exception or custom exception is creating your own exception class
and throws that exception using ‘throw’ keyword. This can be done by extending
the class Exception.
20

There is no need to override any of the above methods available in the Exception
class, in your derived class. But practically, you will require some amount of
customizing as per your programming needs.

Example: To created a User-Defined Exception Class

Step 1) Copy the following code into the editor


class JavaException{
public static void main(String args[]){
try{
throw new MyException(2);
// throw is used to create a new exception and throw it.
}
catch(MyException e){
System.out.println(e) ;
}
}
}
class MyException extends Exception{
int a;
MyException(int b) {
a=b;
}
public String toString(){
return ("Exception Number = "+a) ;
}
}
21

Step 2) Save , Compile & Run the code. Excepted output -

NOTE:
The keyword “throw” is used to create a new Exception and throw it to the catch
block.

What are Java Threads?


A thread is a:

Facility to allow multiple activities within a single process


 Referred as lightweight process
 A thread is a series of executed statements
 Each thread has its own program counter, stack and local variables
 A thread is a nested sequence of method calls
 Its shares memory, files and per-process state

Whats the need of a thread or why we use Threads?


To perform asynchronous or background processing
 Increases the responsiveness of GUI applications
 Take advantage of multiprocessor systems
 Simplify program logic when there are multiple independent entities

What happens when a thread is invoked?


When a thread is invoked, there will be two paths of execution. One path will
execute the thread and the other path will follow the statement after the thread
invocation. There will be a separate stack and memory space for each thread.
22

Risk Factor
 Proper co-ordination is required between threads accessing common variables
[use of synchronized and volatile] for consistence view of data
 overuse of java threads can be hazardous to program’s performance and its
maintainability.
Threads in Java
Java threads facility and API is deceptively simple:
Every java program creates at least one thread [ main() thread ]. Additional threads
are created through the Thread constructor or by instantiating classes that extend
the Thread class.

Thread creation in Java


Thread implementation in java can be achieved in two ways:

1. Extending the java.lang.Thread class


2. Implementing the java.lang.Runnable Interface
Note: The Thread and Runnable are available in the java.lang.* package

1) By extending thread class


 The class should extend Java Thread class.
 The class should override the run() method.
 The functionality that is expected by the Thread to be executed is written in the
run() method.
void start(): Creates a new thread and makes it runnable.
void run(): The new thread begins its life inside this method.

Example:

public class MyThread extends Thread {


public void run(){
System.out.println("thread is running...");
}
23

public static void main(String[] args) {


MyThread obj = new MyThread();
obj.start();
}
2) By Implementing Runnable interface
 The class should implement the Runnable interface
 The class should implement the run() method in the Runnable interface
 The functionality that is expected by the Thread to be executed is put in the
run() method
Example:

public class MyThread implements Runnable {


public void run(){
System.out.println("thread is running..");
}
public static void main(String[] args) {
Thread t = new Thread(new MyThread());
t.start();
}
Extends Thread class vs Implements Runnable Interface?
 Extending the Thread class will make your class unable to extend other classes,
because of the single inheritance feature in JAVA. However, this will give you
a simpler code structure. If you implement Runnable, you can gain better
object-oriented design and consistency and also avoid the single inheritance
problems.
 If you just want to achieve basic functionality of a thread you can simply
implement Runnable interface and override run() method. But if you want to do
something serious with thread object as it has other methods like suspend(),
resume(), ..etc which are not available in Runnable interface then you may
prefer to extend the Thread class.
Thread life cycle in java
24

A thread goes through various stages in its life cycle. For example, a thread is born,
started, runs, and then dies. The following diagram shows the complete life cycle
of a thread.

Following are the stages of the life cycle −


 New − A new thread begins its life cycle in the new state. It remains in this
state until the program starts the thread. It is also referred to as a born
thread.
 Runnable − After a newly born thread is started, the thread becomes
runnable. A thread in this state is considered to be executing its task.
 Waiting − Sometimes, a thread transitions to the waiting state while the
thread waits for another thread to perform a task. A thread transitions back to
the runnable state only when another thread signals the waiting thread to
continue executing.
 Timed Waiting − A runnable thread can enter the timed waiting state for a
specified interval of time. A thread in this state transitions back to the
runnable state when that time interval expires or when the event it is waiting
for occurs.
 Terminated (Dead) − A runnable thread enters the terminated state when it
completes its task or otherwise terminates.
Main thread in Java
Java provides built-in support for multithreaded programming. A multi-threaded
program contains two or more parts that can run concurrently. Each part of such a
program is called a thread, and each thread defines a separate path of execution.
Main Thread
When a Java program starts up, one thread begins running immediately. This is
usually called the main thread of our program, because it is the one that is executed
when our program begins.
25

Properties :
 It is the thread from which other “child” threads will be spawned.
 Often, it must be the last thread to finish execution because it performs various
shutdown actions
Flow diagram :

How to control Main thread


The main thread is created automatically when our program is started. To control it
we must obtain a reference to it. This can be done by calling the
method currentThread( ) which is present in Thread class. This method returns a
reference to the thread on which it is called. The default priority of Main thread is 5
and for all remaining user threads priority will be inherited from parent to child.
filter_none
edit
play_arrow
brightness_4
// Java program to control the Main Thread
26

public class Test extends Thread


{
public static void main(String[] args)
{
// getting reference to Main thread
Thread t = Thread.currentThread();

// getting name of Main thread


System.out.println("Current thread: " + t.getName());

// changing the name of Main thread


t.setName("Geeks");
System.out.println("After name change: " + t.getName());

// getting priority of Main thread


System.out.println("Main thread priority: "+ t.getPriority());

// setting priority of Main thread to MAX(10)


t.setPriority(MAX_PRIORITY);
27

System.out.println("Main thread new priority: "+


t.getPriority());

for (int i = 0; i < 5; i++)


{
System.out.println("Main thread");
}

// Main thread creating a child thread


ChildThread ct = new ChildThread();

// getting priority of child thread


// which will be inherited from Main thread
// as it is created by Main thread
System.out.println("Child thread priority: "+ ct.getPriority());

// setting priority of Main thread to MIN(1)


ct.setPriority(MIN_PRIORITY);

System.out.println("Child thread new priority: "+


28

ct.getPriority());

// starting child thread


ct.start();
}
}

// Child Thread class


class ChildThread extends Thread
{
@Override
public void run()
{
for (int i = 0; i < 5; i++)
{
System.out.println("Child thread");
}
}
}
Output:
Current thread: main
29

After name change: Geeks


Main thread priority: 5
Main thread new priority: 10
Main thread
Main thread
Main thread
Main thread
Main thread
Child thread priority: 10
Child thread new priority: 1
Child thread
Child thread
Child thread
Child thread
Child thread
Relation between the main() method and main thread in Java
For each program, a Main thread is created by JVM(Java Virtual Machine). The
“Main” thread first verifies the existence of the main() method, and then it
initializes the class. Note that from JDK 6, main() method is mandatory in a
standalone java application.

Thread Priority
 When a Java thread is created, it inherits its priority from the thread that created
it.
 You can modify a thread’s priority at any time after its creation using
the setPriority method.
30

 Thread priorities are integers ranging between MIN_PRIORITY (1)


and MAX_PRIORITY (10) . The higher the integer, the higher the
priority.Normally the thread priority will be 5.
Synchronization of Threads
 In many cases concurrently running threads share data and two threads try to do
operations on the same variables at the same time. This often results in corrupt
data as two threads try to operate on the same data.
 A popular solution is to provide some kind of lock primitive. Only one thread
can acquire a particular lock at any particular time. This can be achieved by
using a keyword “synchronized” .
 By using the synchronize only one thread can access the method at a time and a
second call will be blocked until the first call returns or wait() is called inside
the synchronized method.
31

Java FileInputStream Class


Java FileInputStream class obtains input bytes from a file. It is
used for reading byte-oriented data (streams of raw bytes) such
as image data, audio, video etc. You can also read character-
stream data. But, for reading streams of characters, it is
recommended to use FileReader class.
Java FileInputStream class declaration
Ddeclaration for java.io.FileInputStream class:
1. public class FileInputStream extends InputStream

Java FileInputStream class methods


Method Description

int available() It is used to return the estimated number of


bytes that can be read from the input
stream.

int read() It is used to read the byte of data from the


input stream.

int read(byte[] It is used to read up to b.length bytes of


b) data from the input stream.

int read(byte[] It is used to read up to len bytes of data from


b, int off, int
32

len) the input stream.

long skip(long It is used to skip over and discards x bytes of


x) data from the input stream.

FileChannel It is used to return the unique FileChannel


getChannel() object associated with the file input stream.

FileDescriptor It is used to return the FileDescriptor object.


getFD()

protected void It is used to ensure that the close method is


finalize() call when there is no more reference to the
file input stream.

void close() It is used to closes the stream.

Java FileInputStream example 1: read single character


1. import java.io.FileInputStream;
2. public class DataStreamExample {
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("D:\\
testout.txt");
6. int i=fin.read();
7. System.out.print((char)i);
8.
9. fin.close();
10. }catch(Exception e){System.out.println(e);}
11. }
12. }
33

Note: Before running the code, a text file named


as "testout.txt" is required to be created. In this file, we are
having following content:
Welcome to javatpoint.
After executing the above program, you will get a single character
from the file which is 87 (in byte form). To see the text, you need
to convert it into character.
Output:
W
Java FileInputStream example 2: read all characters
1. package com.javatpoint;
2.
3. import java.io.FileInputStream;
4. public class DataStreamExample {
5. public static void main(String args[]){
6. try{
7. FileInputStream fin=new FileInputStream("D:\\
testout.txt");
8. int i=0;
9. while((i=fin.read())!=-1){
10. System.out.print((char)i);
11. }
12. fin.close();
13. }catch(Exception e){System.out.println(e);}
14. }
15. }
Output:
Welcome to javaTpoint
34

Java FileOutputStream Class


Java FileOutputStream is an output stream used for writing data
to a file.
If you have to write primitive values into a file, use
FileOutputStream class. You can write byte-oriented as well as
character-oriented data through FileOutputStream class. But, for
character-oriented data, it is preferred to use FileWriter than
FileOutputStream.

FileOutputStream class declaration


Let's see the declaration for Java.io.FileOutputStream class:
1. public class FileOutputStream extends OutputStream

FileOutputStream class methods


Method Description

protected void It is used to clean up the connection with


finalize() output stream.

void write(byte[] ary) It is used to write ary.length bytes from


byte array to the file output stream.

void write(byte[] ary, It is used to write len bytes from the byt
int off, int len) starting at offset off to the file output str

void write(int b) It is used to write the specified byte to th


output stream.

FileChannel It is used to return the file channel objec


35

getChannel() associated with the file output stream.

FileDescriptor getFD() It is used to return the file descriptor ass


with the stream.

void close() It is used to closes the file output stream

Java FileOutputStream Example 1: write byte


1. import java.io.FileOutputStream;
2. public class FileOutputStreamExample {
3. public static void main(String args[]){
4. try{
5. FileOutputStream fout=new FileOutputStream("D:\\
testout.txt");
6. fout.write(65);
7. fout.close();
8. System.out.println("success...");
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
Output:
Success...
The content of a text file testout.txt is set with the data A.
testout.txt
A
Java FileOutputStream example 2: write string
1. import java.io.FileOutputStream;
2. public class FileOutputStreamExample {
3. public static void main(String args[]){
4. try{
5. FileOutputStream fout=new FileOutputStream("D:\\
testout.txt");
36

6. String s="Welcome to javaTpoint.";


7. byte b[]=s.getBytes();//converting string into byte array

8. fout.write(b);
9. fout.close();
10. System.out.println("success...");
11. }catch(Exception e){System.out.println(e);}
12. }
13. }
Output:
Success...
The content of a text file testout.txt is set with the
data Welcome to javaTpoint.
testout.txt
Welcome to javaTpoint.

Java Scanner
Scanner class in Java is found in the java.util package. Java
provides various ways to read input from the keyboard, the
java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a
delimiter which is whitespace by default. It provides many
methods to read and parse various primitive values.
The Java Scanner class is widely used to parse text for strings and
primitive types using a regular expression. It is the simplest way
to get input in Java. By the help of Scanner in Java, we can get
input from the user in primitive types such as int, long, double,
byte, float, short, etc.
The Java Scanner class extends Object class and implements
Iterator and Closeable interfaces.
37

The Java Scanner class provides nextXXX() methods to return the


type of value such as nextInt(), nextByte(), nextShort(), next(),
nextLine(), nextDouble(), nextFloat(), nextBoolean(), etc. To get a
single character from the scanner, you can call next().charAt(0)
method which returns a single character.
Java Scanner Class Declaration
1. public final class Scanner
2. extends Object
3. implements Iterator<String>
How to get Java Scanner
To get the instance of Java Scanner which reads input from the
user, we need to pass the input stream (System.in) in the
constructor of Scanner class. For Example:
1. Scanner in = new Scanner(System.in);
To get the instance of Java Scanner which parses the strings, we
need to pass the strings in the constructor of Scanner class. For
Example:
1. Scanner in = new Scanner("Hello Javatpoint");

Java Scanner Class Methods


The following are the list of Scanner methods:
SN Modifier & Method Description
Type

1 void close() It is used to close this


) scanner.

2 pattern delimiter It is used to get the Pattern


) () which the Scanner class is
currently using to match
38

delimiters.

3 Stream<Ma findAll() It is used to find a stream of


) tchResult> match results that match
the provided pattern string.

4 String findInLin It is used to find the next


) e() occurrence of a pattern
constructed from the
specified string, ignoring
delimiters.

5 string findWithi It is used to find the next


) nHorizon occurrence of a pattern
() constructed from the
specified string, ignoring
delimiters.

6 boolean hasNext( It returns true if this


) ) scanner has another token
in its input.

7 boolean hasNext It is used to check if the


) BigDeci next token in this scanner's
mal() input can be interpreted as
a BigDecimal using the
nextBigDecimal() method or
not.

8 boolean hasNext It is used to check if the


) BigInteg next token in this scanner's
er() input can be interpreted as
a BigDecimal using the
39

nextBigDecimal() method or
not.

9 boolean hasNext It is used to check if the


) Boolean( next token in this scanner's
) input can be interpreted as
a Boolean using the
nextBoolean() method or
not.

1 boolean hasNext It is used to check if the


0 Byte() next token in this scanner's
) input can be interpreted as
a Byte using the
nextBigDecimal() method or
not.

1 boolean hasNext It is used to check if the


1 Double() next token in this scanner's
) input can be interpreted as
a BigDecimal using the
nextByte() method or not.

1 boolean hasNext It is used to check if the


2 Float() next token in this scanner's
) input can be interpreted as
a Float using the nextFloat()
method or not.

1 boolean hasNextI It is used to check if the


3 nt() next token in this scanner's
) input can be interpreted as
an int using the nextInt()
40

method or not.

1 boolean hasNext It is used to check if there is


4 Line() another line in the input of
) this scanner or not.

1 boolean hasNext It is used to check if the


5 Long() next token in this scanner's
) input can be interpreted as
a Long using the nextLong()
method or not.

1 boolean hasNext It is used to check if the


6 Short() next token in this scanner's
) input can be interpreted as
a Short using the
nextShort() method or not.

1 IOException ioExcept It is used to get the


7 ion() IOException last thrown by
) this Scanner's readable.

1 Locale locale() It is used to get a Locale of


8 the Scanner class.
)

1 MatchResult match() It is used to get the match


9 result of the last scanning
) operation performed by this
scanner.

2 String next() It is used to get the next


0 complete token from the
41

) scanner which is in use.

2 BigDecimal nextBig It scans the next token of


1 Decimal( the input as a BigDecimal.
) )

2 BigInteger nextBigI It scans the next token of


2 nteger() the input as a BigInteger.
)

2 boolean nextBool It scans the next token of


3 ean() the input into a boolean
) value and returns that
value.

2 byte nextByte It scans the next token of


4 () the input as a byte.
)

2 double nextDou It scans the next token of


5 ble() the input as a double.
)

2 float nextFloa It scans the next token of


6 t() the input as a float.
)

2 int nextInt() It scans the next token of


7 the input as an Int.
)

2 String nextLine It is used to get the input


8 string that was skipped of
42

) () the Scanner object.

2 long nextLon It scans the next token of


9 g() the input as a long.
)

3 short nextShor It scans the next token of


0 t() the input as a short.
)

3 int radix() It is used to get the default


1 radix of the Scanner use.
)

3 void remove( It is used when remove


2 ) operation is not supported
) by this implementation of
Iterator.

3 Scanner reset() It is used to reset the


3 Scanner which is in use.
)

3 Scanner skip() It skips input that matches


4 the specified pattern,
) ignoring delimiters

3 Stream<Stri tokens() It is used to get a stream of


5 ng> delimiter-separated tokens
) from the Scanner object
which is in use.

3 String toString( It is used to get the string


43

6 ) representation of Scanner
) using.

3 Scanner useDeli It is used to set the


7 miter() delimiting pattern of the
) Scanner which is in use to
the specified pattern.

Example 1
Let's see a simple example of Java Scanner where we are getting
a single input from the user. Here, we are asking for a string
through in.nextLine() method.
1. import java.util.*;
2. public class ScannerExample {
3. public static void main(String args[]){
4. Scanner in = new Scanner(System.in);
5. System.out.print("Enter your name: ");
6. String name = in.nextLine();
7. System.out.println("Name is: " + name);
8. in.close();
9. }
10. }
Output:
Enter your name: sonoo jaiswal
Name is: sonoo jaiswal
Example 2
1. import java.util.*;
2. public class ScannerClassExample1 {
3. public static void main(String args[]){
4. String s = "Hello, This is JavaTpoint.";
5. //Create scanner Object and pass string in it
44

6. Scanner scan = new Scanner(s);


7. //Check if the scanner has a token
8. System.out.println("Boolean Result: " + scan.hasNext());
9. //Print the string
10. System.out.println("String: " +scan.nextLine());
11. scan.close();
12. System.out.println("--------Enter Your Details-------- ");
13. Scanner in = new Scanner(System.in);
14. System.out.print("Enter your name: ");
15. String name = in.next();
16. System.out.println("Name: " + name);
17. System.out.print("Enter your age: ");
18. int i = in.nextInt();
19. System.out.println("Age: " + i);
20. System.out.print("Enter your salary: ");
21. double d = in.nextDouble();
22. System.out.println("Salary: " + d);
23. in.close();
24. }
25. }
Output:
Boolean Result: true
String: Hello, This is JavaTpoint.
-------Enter Your Details---------
Enter your name: Abhishek
Name: Abhishek
Enter your age: 23
Age: 23
Enter your salary: 25000
Salary: 25000.0
Example 3
1. import java.util.*;
2. public class ScannerClassExample2 {
3. public static void main(String args[]){
45

4. String str = "Hello/This is JavaTpoint/My name is Abhishek.";

5. //Create scanner with the specified String Object


6. Scanner scanner = new Scanner(str);
7. System.out.println("Boolean Result: "+scanner.hasNextBool
ean());
8. //Change the delimiter of this scanner
9. scanner.useDelimiter("/");
10. //Printing the tokenized Strings
11. System.out.println("---Tokenizes String---");
12. while(scanner.hasNext()){
13. System.out.println(scanner.next());
14. }
15. //Display the new delimiter
16. System.out.println("Delimiter used: " +scanner.delimit
er());
17. scanner.close();
18. }
19. }
Output:
Boolean Result: false
---Tokenizes String---
Hello
This is JavaTpoint
My name is Abhishek.
Delimiter used: /

Java Console Class


The Java Console class is be used to get input from console. It
provides methods to read texts and passwords.
If you read password using Console class, it will not be displayed
to the user.
46

The java.io.Console class is attached with system console


internally. The Console class is introduced since 1.5.
Let's see a simple example to read text from console.
1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);

Java Console class declaration


Let's see the declaration for Java.io.Console class:
1. public final class Console extends Object implements Flushabl
e

Java Console class methods


Method Description

Reader reader() It is used to retrieve the


reader object associated with the
console

String readLine() It is used to read a single line of text


from the console.

String It provides a formatted prompt then


readLine(String fmt, reads the single line of text from the
Object... args) console.

char[] It is used to read password that is not


readPassword() being displayed on the console.

char[] It provides a formatted prompt then


readPassword(String reads the password that is not being
fmt, Object... args) displayed on the console.
47

Console It is used to write a formatted string to


format(String fmt, the console output stream.
Object... args)

Console printf(String It is used to write a string to the console


format, Object... output stream.
args)

PrintWriter writer() It is used to retrieve


the PrintWriter object associated with
the console.

void flush() It is used to flushes the console.

How to get the object of Console


System class provides a static method console() that returns
the singleton instance of Console class.
1. public static Console console(){}
Let's see the code to get the instance of Console class.
1. Console c=System.console();

Java Console Example


1. import java.io.Console;
2. class ReadStringTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter your name: ");
6. String n=c.readLine();
7. System.out.println("Welcome "+n);
8. }
9. }
Output
48

Enter your name: Nakul Jain


Welcome Nakul Jain

Java Console Example to read password


1. import java.io.Console;
2. class ReadPasswordTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter password: ");
6. char[] ch=c.readPassword();
7. String pass=String.valueOf(ch);//converting char array into string

8. System.out.println("Password is: "+pass);


9. }
10. }
Output
Enter password:
Password is: 123
Java - RandomAccessFile
This class is used for reading and writing to random access file. A
random access file behaves like a large array of bytes. There is a
cursor implied to the array called file pointer, by moving the
cursor we do the read write operations. If end-of-file is reached
before the desired number of byte has been read than
EOFException is thrown. It is a type of IOException.
Constructor
Constructor Description

RandomAccessFile(File Creates a random access file


file, String mode) stream to read from, and optionally
to write to, the file specified by the
49

File argument.

RandomAccessFile(Strin Creates a random access file


g name, String mode) stream to read from, and optionally
to write to, a file with the specified
name.

Method
Modifier and Method Method
Type

void close() It closes this random


access file stream and
releases any system
resources associated with
the stream.

FileChanne getChannel() It returns the


l unique FileChannel object
associated with this file.

int readInt() It reads a signed 32-bit


integer from this file.

String readUTF() It reads in a string from


this file.
50

void seek(long pos) It sets the file-pointer


offset, measured from the
beginning of this file, at
which the next read or
write occurs.

void writeDouble(doubl It converts the double


e v) argument to a long using
the doubleToLongBits
method in class Double,
and then writes that long
value to the file as an
eight-byte quantity, high
byte first.

void writeFloat(float v) It converts the float


argument to an int using
the floatToIntBits method
in class Float, and then
writes that int value to the
file as a four-byte quantity,
high byte first.

void write(int b) It writes the specified byte


to this file.

int read() It reads a byte of data


from this file.

long length() It returns the length of this


file.

void seek(long pos) It sets the file-pointer


51

offset, measured from the


beginning of this file, at
which the next read or
write occurs.

Example
1. import java.io.IOException;
import java.io.RandomAccessFile;
2.
3. public class RandomAccessFileExample {
4. static final String FILEPATH ="myFile.TXT";
5. public static void main(String[] args) {
6. try {
7. System.out.println(new String(readFromFile(FILEPATH, 0,
18)));
8. writeToFile(FILEPATH, "I love my country and my people",
31);
9. } catch (IOException e) {
10. e.printStackTrace();
11. }
12. }
13. private static byte[] readFromFile(String filePath, int positi
on, int size)
14. throws IOException {
15. RandomAccessFile file = new RandomAccessFile(filePath,
"r");
16. file.seek(position);
17. byte[] bytes = new byte[size];
18. file.read(bytes);
19. file.close();
20. return bytes;
21. }
52

22. private static void writeToFile(String filePath, String data, i


nt position)
23. throws IOException {
24. RandomAccessFile file = new RandomAccessFile(filePath,
"rw");
25. file.seek(position);
26. file.write(data.getBytes());
27. file.close();
28. }
29. }
The myFile.TXT contains text "This class is used for reading and
writing to random access file."
after running the program it will contains
This class is used for reading I love my country and my peoplele.

You might also like