• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Files

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
can any one explain the output of this program...

import java.io.*;
public class Question12 {
public static void main(String[] args) throws IOException{
RandomAccessFile raf = new RandomAccessFile("test.dat","rw");
raf.writeInt(0x01);
raf.writeShort(0x23);
raf.writeByte(0x45);
raf.seek(3);
short a1 = raf.readShort();
short a2 = raf.readShort();
System.out.println("0x"+Integer.toHexString(a1)+", 0x"+Integer.toHexString(a2));
}
}

o/p:
0x100 0x2345
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Remember: int is 32 bits (= 4 bytes), short is 16 bits (= 2 bytes) and a byte is 8 bits.

You are writing the following bytes to the file (in hex):

00 00 00 01 (int)
00 23 (short)
45 (byte)

So the file now contains 7 bytes: 00 00 00 01 00 23 45

Then, by using seek(3), you set the file pointer to the 4th byte (the first byte in the file is position 0), and you read two shorts. So you read:

01 00 (short)
23 45 (short)

And then you print those two shorts as hexadecimal numbers: 0x100 0x2345
[ October 03, 2007: Message edited by: Jesper Young ]
 
swati cha
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for your reply
 
What's brown and sticky? ... a stick. Or a tiny ad.
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic