Menu
Topics Index
...
`

Haphazard Access


If you need explanation Read this topic

If you need Answer Take test on this topic

Haphazard Access
What will be the output of the following program?
import java.io.*;

public class HaphazardAccess {

    public static void main(String[] args) throws IOException {
        File file = File.createTempFile("Alphabets", "txt");
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        raf.write("ABCDEFGHIJKLMNOP\nQRSTUVWXYZ\n".getBytes());
        System.out.print(raf.readLine() + "~");
        raf.seek(20);
        System.out.print(raf.readLine() + "~");
        raf.write("1234567890\n1234567890\n1234567890\n1234567890\n".getBytes());
        raf.setLength(40);
        System.out.print(raf.readLine() + "~");
        raf.seek(30);
        System.out.print(raf.readLine() + "~");
        raf.seek(0);
        System.out.print(raf.readLine() + "~");
        raf.close();
    }
}

A. ABCDEFGHIJKLMNOP~TUVWXYZ~null~34567890~ABCDEFGHIJKLMNOP~
B. null~TUVWXYZ~null~34567890~ABCDEFGHIJKLMNOP~
C. null~TUVWXYZ~null~null~ABCDEFGHIJKLMNOP~
D. Some other output or Compilation Error
E. Runtime Error
Topic: Java RandomAccessFile

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

ans :c
first file pointer in end of file...so null printed
next     ~tuvwxyz is printed....
after appending file pointer again goes to end so null printed...  next ~ printed...
next file poiter set to 30 the position... so 34567890 is printed...
next ~ printed...
file pointer set to 1 st position so first line ABCDEFGHIJKLMNOP is printed.....next ~

Posted by Ananda Kumar    2014-04-01 12:52:06


Answer is B...in the beginning the file pointer will be at the end..then raf.seek(20) will move it to the letter T...then TUVWXYZ gets printed..in case of numbers also ..the ile pointer will be at the end of file thus results null..then seek(30) moves it to the number 3 ..thus it is 34567890..Finallythe result would be B...

Posted by Sneha Rapool    2014-04-01 13:01:50


ans. B. First file pointer is at EOF and null is printed. Next file pointer is moved to position 20 from beginning and so TUVWXYZ is printed. Again 4 times 1 to 0 is appended to the file and the file pointer is pointing at last. so now null is printed. Then File pointer is pointed to location 30 from beginning after setting the length of the file as 40. so 3 to 0 is printed and again A to P is printed.

Posted by Nikhil Sulibhavi    2014-04-01 13:04:04


by mistake I typed c ....bt I explained for ans b....

Posted by Ananda Kumar    2014-04-01 13:20:58


Congratulations Sneha Rapool. You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-04-02 04:43:11


© meritcampus 2019

All Rights Reserved.

Open In App