BSC MPCS Vth Sem Java Unit 2-signed
BSC MPCS Vth Sem Java Unit 2-signed
01
Packages–Creating and Using Packages, Access Protection, Wrapper Classes, String Class, StringBuffer
Class. Exception: Introduction, Types, Exception Handling Techniques, User-Defined Exception.
Multithreading: Introduction, Main Thread, Creation of New Threads – By Inheriting the Thread Class or
Implementing the Runnable Interface, Thread Lifecycle, Thread Priority, Synchronization.
Input/Output: Introduction, java.io Package, File Class, FileInputStream Class, FileOutputStream Class,
Scanner Class, BufferedInputStream Class, BufferedOutputStream Class, RandomAccessFile Class.
MS bhanu
Packages 02
A package is a container of classes and interfaces. A package represents a directory that contains related
group of classes and interfaces. For example, when we write statement like:
import java.io.*;
Here we are importing classes of java.io package. Here, java is a directory name and io is another sub
directory within it. The “*” represents all the classes and interfaces of that io sub directory. We can create
our own packages called user-defined packages or extend the available packages. User-defined packages can
also be imported into other classes and used exactly in the same way as the Built-in packages. Packages
provide reusability.
MS bhanu
Ex: package pack; 03
The first statement in the program must be package statement while creating a package. While
creating a package except instance variables, declare all the members and the class itself as public then only
the public members are available outside the package to other programs.
To compile the Java programs with package statements, you have to use -d option as shown below.
Then a folder with the given package name is created in the specified destination, and the compiled class
files will be placed in that folder.
Program 1: Write a program to create a package pack with Addition class.
//creating a package
package pack;
public class Addition
{
private double d1,d2;
public Addition(double a,double b)
{
d1 = a;
d2 = b;
}
public void sum()
{
System.out.println ("Sum of two given numbers is : " + (d1+d2) );
}
}
Compiling the above program:
C:\>javac – d . Addition.java
The – d option tells the Java compiler to create a separate directory and place the .class file in that
directory (package). The (.) dot after –d indicates that the package should be created in the current directory.
So, out package pack with Addition class is ready.
MS bhanu
{
04
public static void main(String args[])
{
Addition ob1 = new Addition(10,20);
ob1.sum();
}
}
Output:
//compiling program
C:\>javac use.java
//Running a program
C:\>java use
Sum of two given numbers: 30.00.
java.lang Language support classes. They include classes for primitive types, string, math
functions, thread and exceptions.
java.util Language utility classes such as vectors, hash tables, random numbers, data, etc.
java.io Input/output support classes. They provide facilities for the input and output of data.
java.net Classes for networking. They include classes for communicating with local computers
as well as with internet servers.
java.awt Set of classes for implementing graphical user interface. They include classes for
windows, buttons, lists, menus and so on.
MS bhanu
05
Access Protection in Packages
Access modifiers define the scope of the class and its members (data and methods). For example, private
members are accessible within the same class members (methods). Java provides many levels of security
that provides the visibility of members (variables and methods) within the classes, subclasses, and
packages.
Packages are meant for encapsulating, it works as containers for classes and other subpackages.
Class acts as containers for data and methods. There are four categories, provided by Java regarding the
visibility of the class members between classes and packages:
1. Subclasses in the same package
2. Non-subclasses in the same package
3. Subclasses in different packages
4. Classes that are neither in the same package nor subclasses
The three main access modifiers private, public and protected provides a range of ways to access required
by these categories.
Simply remember, private cannot be seen outside of its class, public can be access from anywhere, and
protected can be accessible in subclass only in the hierarchy.
A class can have only two access modifier, one is default and another is public. If the class has default
access then it can only be accessed within the same package by any other code. But if the class has public
access then it can be access from any where by any other code.
WRAPPER CLESS
A Wrapper class is a class whose object wraps or contains a primitive data types. When we create an object
to a wrapper class, it contains a field and in this field, we can store a primitive data types. In other words, we
can wrap a primitive value into a wrapper class object.
Need of Wrapper Classes
1. They convert primitive data types into objects. Objects are needed if we wish to modify the
arguments passed into a method (because primitive types are passed by value).
2. The classes in java.util package handles only objects and hence wrapper classes help in this case
also.
MS bhanu
3. Data structures in the Collection framework, such as ArrayList and Vector, store only objects
(reference types) and not primitive types. 06
4. An object is needed to support synchronization in multithreading.
The following two statements illustrate the difference between a primitive data type and an object of a
wrapper class:
int x = 25;
Integer y = new Integer(33);
The first statement declares an int variable named x and initializes it with the value 25. The second
statement instantiates an Integer object. The object is initialized with the value 33 and a reference to the
object is assigned to the object variable y. Below table lists wrapper classes in Java API with constructor
details.
As explain in above table all wrapper classes (except Character) take String as argument constructor. Please
note we might get NumberFormatException if we try to assign invalid argument in constructor. For example
to create Integer object we can have following syntax.
Integer intObj = new Integer (25);
Integer intObj2 = new Integer ("25");
Here in we can provide any number as string argument but not the words etc.
Below statement will throw run time exception (NumberFormatException)
MS bhanu
Integer intObj3 = new Integer ("Two"); 07
The following discussion focuses on the Integer wrapperclass, but applies in a general sense to all eight
wrapper classes.
Autoboxing:
Automatic conversion of primitive types to the object of their corresponding wrapper classes is
known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double etc.
Example:
// Java program to demonstrate Autoboxing
import java.util.ArrayList;
class Autoboxing
{
public static void main(String[] args)
{
char ch = 'a';;
// Autoboxing- primitive to Character object conversion
Character a = ch;
ArrayList<Integer> arrayList = new ArrayList<Integer>();
// Autoboxing because ArrayList stores only objects
arrayList.add(25);
// printing the values from object
System.out.println(arrayList.get(0));
}
}
Output:
25
Unboxing:
It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to
its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to
long, Double to double etc.
Example:
// Java program to demonstrate Unboxing
import java.util.ArrayList;
class Unboxing
{
public static void main(String[] args)
{
Character ch = 'a';
MS bhanu
// unboxing - Character object to primitive conversion
08
char a = ch;
ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(24);
// unboxing because get method returns an Integer object
int num = arrayList.get(0);
// printing the values from primitive data types
System.out.println(num);
}
}
Output:
24
The most common methods of the Integer wrapper class are summarized in below table. Similar methods
for the other wrapper classes are found in the Java API documentation.
MS bhanu
Ex:
Import java.io.*; 09
public class WrappingUnwrapping
{
public static void main(String args[])
{
byte grade = 2;
int marks = 50;
float price = 8.6f;
double rate = 50.5;
Byte g1 = new Byte(grade);
Integer m1 = new Integer(marks);
Float f1 = new Float(price);
Double r1 = new Double(rate);
System.out.println("Values of Wrapper objects (printing as objects)");
System.out.println("Byte object g1: " + g1);
System.out.println("Integer object m1: " + m1);
System.out.println("Float object f1: " + f1);
System.out.println("Double object r1: " + r1);
byte bv = g1.byteValue();
int iv = m1.intValue();
float fv = f1.floatValue();
double dv = r1.doubleValue();
System.out.println("Unwrapped values (printing as data types)");
System.out.println("byte value, bv: " + bv);
System.out.println("int value, iv: " + iv);
System.out.println("float value, fv: " + fv);
System.out.println("double value, dv: " + dv);
}
}
String Class
String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string is an immutable
object which means it is constant and can cannot be changed once it has been created. In java strings are
class objects and implemented using two classes those are
1) string
2) string buffer
A java is an instantiated object of the string class.
MS bhanu
When java strings compare to “c” strings are more reliable and predictable because in “c” the strings are
terminated by “null values” but where as in java string is not a character array and is not null terminated
Creating a String 10
Ex;
string y[];
Y=new string[3];
Ex:
String string name =(“GAYATHRI”);
MS bhanu
String str2 = new String(arrch);
11
//creating another java string str3 by using new keyword
String str3 = new String("Java String Example");
//Displaying all the three strings
System.out.println(str);
System.out.println(str2);
System.out.println(str3);
}
}
Output:
Beginnersbook
hello
Java String Example
String Methods
1. int length(): Returns the number of characters in the String.
Ex: "GeeksforGeeks".length(); // returns 13
3. String substring (int i): Return the substring from the ith index character to end.
Ex: "GeeksforGeeks".substring(3); // returns “ksforGeeks”
4. String substring (int i, int j): Returns the substring from i to j-1 index.
Ex: "GeeksforGeeks".substring(2, 5); // returns “eks”
5. String concat( String str): Concatenates specified string to the end of this string.
Ex: String s1 = ”Geeks”;
String s2 = ”forGeeks”;
6. int indexOf (String s): Returns the index within the string of the first occurrence of the specified
string.
Ex: String s = ”Learn Share Learn”;
7. int indexOf (String s, int i): Returns the index within the string of the first occurrence of the
specified string, starting at the specified index.
Ex: String s = ”Learn Share Learn”;
MS bhanu
int output = s.indexOf(„a‟,3);// returns 8 12
8. Int lastindexOf( int ch): Returns the index within the string of the last occurrence of the specified
string.
Ex: String s = ”Learn Share Learn”;
9. boolean equals( Object otherObj): Compares this string to the specified object.
Ex: Boolean out = “Geeks”.equals(“Geeks”); // returns true
10. boolean equalsIgnoreCase (String anotherString): Compares string to another string, ignoring
case considerations.
Ex: Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true
Note- In this case, it will not consider case of a letter (it will ignore whether it is uppercase or
lowercase).
13. String toLowerCase(): Converts all the characters in the String to lower case.
Ex: String word1 = “HeLLo”;
MS bhanu
String word3 = word1.toLowerCase(); // returns “hello"
13
14. String toUpperCase(): Converts all the characters in the String to upper case.
Ex: String word1 = “HeLLo”;
15. String trim(): Returns the copy of the String, by removing whitespaces at both ends. It does not
affect whitespaces in the middle.
Ex: String word1 = “ Learn Share Learn “;
16. String replace (char oldChar, char newChar): Returns new string by replacing all occurrences
of oldChar with newChar.
Ex: String s1 = “feeksforfeeks“;
Output :
MS bhanu
String length = 13
15
Character at 3rd position = k
Substring ksforGeeks
Substring = eks
Concatenated string = GeeksforGeeks
Index of Share 6
Index of a = 8
Checking Equality false
Checking Equality true
Checking Equalityfalse
If s1 = s2false
Changing to lower Case geekyme
Changing to UPPER Case GEEKYME
Trim the word Learn Share Learn
Original String feeksforfeeks
Replaced f with g -> geeksgorgeeks
StringBuffer Methods
Here is the list of important methods supported by StringBuffer class −
5 replace(int start, int end, String str) This method replaces the characters in a substring of this
StringBuffer with characters in the specified String.
Here is the list of other methods (except set methods) which are very similar to String class −
MS bhanu
Sr.No. Method & Description
1 int capacity() 16
Returns the current capacity of the String buffer.
9 int length()
Returns the length (character count) of this string buffer.
MS bhanu
StringBuffer.
15 String toString() 17
Converts to a string representing the data in this string buffer.
Ex:
Hello!
Hello
World Hello
Index of Hello: 6
Index of Hello: 10
BASIS FOR
STRING STRINGBUFFER
COMPARISON
MS bhanu
Basic The length of the String object is The length of the StringBuffer can be
19
fixed. increased.
Exceptional Handling
An exception is a problem that arises during the execution of a program. An exception can occur for many
different reasons, including the following: A user has entered invalid data. A file that needs to be opened
cannot be found. A network connection has been lost in the middle of communications, or the JVM has run
out of memory
Types of Exceptions
1. Checked Exception: A checked exception is an exception that is typically a user error or a problem that
cannot be foreseen by the programmer. Checked exception can also be defined as “The classes that extend
the Throwable class except RuntimeException and Error are known as Checked Exceptions”. For example,
if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions are checked at
compile-time and cannot simply be ignored at the time of compilation. Example of Checked Exception are
IOException, SQLException etc.
2. Unchecked Exception: Also known as Runtime Exceptions and they are ignored at the time of
compilation but checked during execution of the program. Unchecked Exceptions can also be defined as
“The Classes that extend the RuntimeException class are known as Unchecked Exceptions”. Examples are
ArithmeticException, NullPointerException etc.
3. Error: These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything about an error.
For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
Hierarchy of Exception
All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the
Throwable class. Other than the exception class there is another subclass called Error which is derived from
the Throwable class.
MS bhanu
20
MS bhanu
2. catch
3. finally
21
4. throw
5. throws
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in
protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that
occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed
into a method parameter.
Example of Program without Exceptional Handling
MS bhanu
22
MS bhanu
23
Finally Block
The finally keyword is used to create a block of code that follows a try block. A finally block of code always
executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-
type statements that you want to execute, no matter what happens in the protected code.
MS bhanu
Throw Keyword
The throw keyword is used to explicitly throw an exception. We can throw either checked or unchecked
exception. The throw keyword is normally used to throw custom exception. 24
Throws Keyword
The throws keyword is used to declare the exception, it provide information to the programmer that there
may occur an exception so during call of that method, and programmer must use exceptional handling
mechanism. Throws keyword is also used to propagate checked exception.
Example
In this example, exception is created by extending Exception class and the custom exception is declared in
the method validate (int i)
MS bhanu
If you want to write a checked exception that is automatically enforced by the Handle or Declare
Rule, you need to extend the Exception class.
25
If you want to write a runtime exception, you need to extend the RuntimeException class.
Example to create custom exception is shown in the section above.
Multithreading
Multithreading is a conceptual programming concept where a program (process) is divided into two or more
subprograms (process), which can be implemented at the same time in parallel. A multithreaded 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. A process consists of the memory space allocated by the
operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of
a process.
There are two distinct types of Multitasking i.e. Processor-Based and Thread-Based multitasking.
Q: What is the difference between thread-based and process-based multitasking?
Ans: As both are types of multitasking there is very basic difference between the two. Process-Based
multitasking is a feature that allows your computer to run two or more programs concurrently. For example
you can listen to music and at the same time chat with your friends on Facebook using browser. In Thread-
based multitasking, thread is the smallest unit of code, which means a single program can perform two or
more tasks simultaneously. For example a text editor can print and at the same time you can edit text
provided that those two tasks are perform by separate threads.
Benefits of Multithreading
1. Enables programmers to do multiple things at one time
2. Programmers can divide a long program into threads and execute them in parallel which eventually
increases the speed of the program execution
3. Improved performance and concurrency
4. Simultaneous access to multiple applications
Life Cycle of Thread
A thread can be in any of the five following states
1. Newborn State: When a thread object is created a new thread is born and said to be in Newborn state.
2. Runnable State: If a thread is in this state it means that the thread is ready for execution and waiting for
the availability of the processor. If all threads in queue are of same priority then they are given time slots for
execution in round robin fashion
3. Running State: It means that the processor has given its time to the thread for execution. A thread keeps
running until the following conditions occurs
a. Thread give up its control on its own and it can happen in the following situations
i. A thread gets suspended using suspend() method which can only be revived with resume()
method
MS bhanu
ii. A thread is made to sleep for a specified period of time using sleep(time) method, where
time in milliseconds
iii. A thread is made to wait for some event to occur using wait () method. In this case a
thread can be scheduled to run again using notify () method. 26
b. A thread is pre-empted by a higher priority thread
4. Blocked State: If a thread is prevented from entering into runnable state and subsequently running state,
then a thread is said to be in Blocked state.
5. Dead State: A runnable thread enters the Dead or terminated state when it completes its task or otherwise
terminates.
Main Thread
Every time a Java program starts up, one thread begins running which is called as the main thread of the
program because it is the one that is executed when your program begins.
Child threads are produced from main thread
Often it is the last thread to finish execution as it performs various shut down operations
Creating a Thread
Java defines two ways in which this can be accomplished:
1. You can implement the Runnable interface. You can extend the Thread class, itself.
2. Create Thread by Implementing Runnable
MS bhanu
The easiest way to create a thread is to create a class that implements the Runnable interface. To implement
Runnable, a class need only implement a single method called run( ), which is declared like this:
27
public void run( )
You will define the code that constitutes the new thread inside run( ) method. It is important to
understand that run( ) can call other methods, use other classes, and declare variables, just like the main
thread can.
After you create a class that implements Runnable, you will instantiate an object of type Thread from within
that class. Thread defines several constructors. The one that we will use is shown here:
Thread(Runnable threadOb, String threadName);
Here threadOb is an instance of a class that implements the Runnable interface and the name of the new
thread is specified by threadName. After the new thread is created, it will not start running until you call its
start( ) method, which is declared within Thread. The start( ) method is shown here:
void start( );
Example to Create a Thread using Runnable Interface
MS bhanu
Example to Create a Thread by Extending Thread Class
28
Thread Methods
MS bhanu
29
Example
MS bhanu
30
MS bhanu
As you can see in the output below, thread A gets started and when condition if(i==2) gets satisfied yield()
method gets evoked and the control is relinquished from thread A to thread B which run to its completion
and only after that thread a regain the control back.
31
Output
Output
MS bhanu
Use of sleep() Method
Causes the currently running thread to block for at least the specified number of milliseconds. You need to
handle exception while using sleep() method.
32
MS bhanu
Thread Priority 34
Every Java thread has a priority that helps the operating system determine the order in which threads
are scheduled.
Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY
(a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor time
before lower-priority threads. However, thread priorities cannot guarantee the order in which threads
execute and very much platform dependent
In the above code, you can see Priorities of Thread is set to maximum for Thread A which lets it to run to
completion ahead of C which is set to minimum priority.
Output:
MS bhanu
Synchronization 35
When two or more threads need access to a shared resource, they need some way to ensure that the
resource will be used by only one thread at a time. The process by which this synchronization is achieved is
called thread synchronization. The synchronized keyword in Java creates a block of code referred to as a
critical section. Every Java object with a critical section of code gets a lock associated with the object. To
enter a critical section, a thread needs to obtain the corresponding object's lock.
synchronized(object)
{
// statements to be synchronized
}
Problem without using Synchronization
In the following example method updatesum() is not synchronized and access by both the threads
simultaneously which results in inconsistent output. Making a method synchronized, Java creates a
“monitor” and hands it over to the thread that calls the method first time. As long as the thread holds the
monitor, no other thread can enter the synchronized section of the code. Writing the method as
synchronized will make one thread enter the method and till execution is not complete no other thread can
get access to the method.
Example
MS bhanu
36
MS bhanu
JAVA INPUT /OUTPUT 37
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of stream to make I/O operation fast. The java.io package contains all the classes
required for input and output operations.
We can perform file handling in java by Java I/O API.
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because it is like a
stream of water that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached with console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Let's see the code to print output and error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");
Let's see the code to get input from console.
1. int i=System.in.read();//returns ASCII code of 1st character
2. System.out.println((char)i);//will print the character
Java.io package
This package provides for system input and output through data streams, serialization and the file system.
Unless otherwise noted, passing a null argument to a constructor or method in any class or interface in this
package will cause a NullPointerException to be thrown.
The classes in the package are primarily abstract classes and stream-oriented that define methods and
subclasses which allow bytes to be read from and written to files or other input and output sources.
For reading the stream:
Open the stream
Read information
Close the stream
For writing in stream:
Open the stream
Write information
Close the stream
MS bhanu
Java.io.FileInputStream Class in Java 38
FileInputStream is useful to read data from a file in the form of sequence of bytes. FileInputStream is meant
for reading streams of raw bytes such as image data. For reading streams of characters, consider using
FileReader.
Constructor and Description
FileInputStream(File file) :Creates an input file stream to read from the specified File object.
FileInputStream(FileDescriptor fdobj) :Creates an input file stream to read from the specified file
descriptor.
FileInputStream(String name) :Creates an input file stream to read from a file with the specified
name.
Important Methods:
1. int read() : Reads a byte of data from this input stream.
Syntax: public int read( ) throws IOException
2. int read(byte[] b) :Reads up to b.length bytes of data from this input stream into an array of bytes.
3. int read(byte[] b, int off, int len) : Reads up to len bytes of data from this input stream into an array
of bytes.
4. long skip(long n) : Skips over and discards n bytes of data from the input stream.
5. int available() : Returns an estimate of the number of remaining bytes that can be read (or skipped
over) from this input stream .
6. void close() : Closes this file input stream and releases any system resources associated with the
stream.
7. FileDescriptor getFD() :Returns the FileDescriptor object that represents the connection to the actual
file in the file system being used by this FileInputStream.
8. FileChannel getChannel() :Returns the unique FileChannel object associated with this file input
stream.
MS bhanu
Syntax :public FileChannel getChannel() 39
9. void finalize() :Ensures that the close method of this file input stream is called when there are no
more references to it.
Here System.in represent the keyboard which is linked with DataInputStream object
2. Send data to OutputStream: Now , associate a file where the data is to be stored to some output
stream. For this , take the help of FileOutputStream which can send data to the file. Attaching the
file.txt to FileOutputStream can be done as:
MS bhanu
3. Reading data from DataInputStream: The next step is to read data from DataInputStream and
write it into FileOutputStream . It means read data from dis object and write it into fout object, as
shown here:
40
ch=(char)dis.read();
fout.write(ch);
4. Close the file: Finally, any file should be closed after performing input or output operations on it,
else the data of the may be corrupted. Closing the file is done by closing the associated streams. For
example, fout.close(): will close the FileOutputStream ,hence there is no way to write data into the file.
Implementation:
//Java program to demonstrate creating a text file using FileOutputStream
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
class Create_File
{
public static void main(String[] args) throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
FileOutputStream fout=new FileOutputStream("file.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout,1024);
System.out.println("Enter text (@ at the end):");
char ch;
while((ch=(char)dis.read())!='@')
{
bout.write(ch);
}
bout.close();
}
}
2. void close() : Closes this input stream and releases any system resources associated with the stream.
3. void mark(int readlimit) : Marks the current position in this input stream.
4. boolean markSupported() : Tests if this input stream supports the mark and reset methods.
5. int read() : Reads the next byte of data from the input stream.
6. int read(byte[] b, int off, int len) : Reads bytes from this byte-input stream into the specified byte
array, starting at the given offset.
7. void reset() : Repositions this stream to the position at the time the mark method was last called on
this input stream.
8. long skip(long n) :Skips over and discards n bytes of data from this input stream
Program:
// Java program to demonstrate working of BufferedInputStream
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
// Java program to demonstrate BufferedInputStream methods MS bhanu
class BufferedInputStreamDemo
42
{
public static void main(String args[]) throws IOException
{
FileInputStream fin = new FileInputStream("file1.txt");
BufferedInputStream bin = new BufferedInputStream(fin);
System.out.println("Number of remaining bytes:" +bin.available());
boolean b=bin.markSupported();
if (b)
bin.mark(bin.available());
bin.skip(4);
System.out.println("FileContents :");
int ch;
while ((ch=bin.read()) != -1)
System.out.print((char)ch);
bin.reset();
while ((ch=bin.read()) != -1)
System.out.print((char)ch);
fin.close();
}
}
Output:
void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array starting at offset
off to this buffered output stream.
Program:
//Java program demonstrating BufferedOutputStream
import java.io.*;
class BufferedOutputStreamDemo
{
public static void main(String args[])throws Exception
{
FileOutputStream fout = new FileOutputStream("f1.txt");
BufferedOutputStream bout = new BufferedOutputStream(fout);
for(int i = 65; i < 75; i++)
{
bout.write(i);
}
byte b[] = { 75, 76, 77, 78, 79, 80 };
bout.write(b);
bout.flush();
bout.close();
fout.close();
}
}
Output :
ABCDEFGHIJKLMNOP
Java.io.RandomAccessFile Class
The Java.io.RandomAccessFile class file behaves like a large array of bytes stored in the file
system.Instances of this class support both reading and writing to a random access file.
MS bhanu
Class declaration
44
Following is the declaration for Java.io.RandomAccessFile class −
8. readFloat() : java.io.RandomAccessFile.readFloat() reads a float value from the file, start reading
from the File Pointer.
MS bhanu
Syntax :public final void readFully(byte[] b) 45
10. readInt() : java.io.RandomAccessFile.readInt() reads a signed 4 bytes integer from the file, start
reading from the File Pointer.
11. readFully(byte[] b, int offset, int len) : java.io.RandomAccessFile.readFully(byte[] b, int offset,
int len) reads bytes initialising from offset positon upto b.length from the buffer, start reading from the
File Pointer.
12. readLong() : java.io.RandomAccessFile.readLong() reads a signed 64 bit integer from the file,
start reading from the File Pointer.
Java.util.Scanner Class
The java.util.Scanner class is a simple text scanner which can parse primitive types and strings using
regular expressions.Following are the important points about Scanner −
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches
whitespace.
A scanning operation may block waiting for input.
A Scanner is not safe for multithreaded use without external synchronization.
Class declaration
Following is the declaration for java.util.Scanner class −
Method Description
public String next() it returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and returns the value as a
string.
MS bhanu
public double it scans the next token as a double value. 46
nextDouble()
Example
import java.util.Scanner;
class ScannerTest
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();
}
}
Output:
MS bhanu