getFloat(): This method is available in java.nio.ByteBuffer class of Java.
Approach 1: When the method does not take any argument.
Syntax:
float java.nio.ByteBuffer.getFloat()
This method reads the next four bytes at this buffer's current position,composing them into a float value according to the current byte order,and then increments the position by four.
Parameters: NA
Returns: The float value at the buffer's current position.
Throws:
BufferUnderflowException - If there are fewer than four bytes remaining in this buffer
Java
import java.nio.ByteBuffer;public class ByteBuffergetFloat {public static void main(String[] args) {byte array[] = { 1, 2, 3, 4, 5 };ByteBuffer bb = ByteBuffer.wrap(array);System.out.println(bb.getFloat());}}
Output:
2.3879393E-38
Approach 1.1: BufferUnderflowException
Java
import java.nio.ByteBuffer;public class ByteBuffergetFloat {public static void main(String[] args) {byte array[] = { 1, 2, 3 };ByteBuffer bb = ByteBuffer.wrap(array);System.out.println(bb.getFloat());}}
Output:
Exception in thread "main" java.nio.BufferUnderflowException at java.base/java.nio.Buffer.nextGetIndex(Buffer.java:702) at java.base/java.nio.HeapByteBuffer.getFloat(HeapByteBuffer.java:545)
Approach 2: When the method takes one argument of type int.
Syntax:
float java.nio.ByteBuffer.getFloat(int index)
This method takes one argument of type int as its parameter. This method reads four bytes at the given index, composing them into afloat value according to the current byte order.
Parameters: One parameter is required for this method.
index: The index from which the bytes will be read.
Returns: The float value at the given index.
Throws:
IndexOutOfBoundsException - If index is negative or not smaller than the buffer's limit,minus three
Java
import java.nio.ByteBuffer;public class ByteBuffergetFloatint {public static void main(String[] args) {byte array[] = { 1, 2, 3, 4 };ByteBuffer bb = ByteBuffer.wrap(array);int index = 0;System.out.println(bb.getFloat(index));}}
Output:
2.3879393E-38
Approach 2.1: IndexOutOfBoundsException
Java
import java.nio.ByteBuffer;public class ByteBuffergetFloatint {public static void main(String[] args) {byte array[] = { 1, 2, 3, 4 };ByteBuffer bb = ByteBuffer.wrap(array);int index = -1;System.out.println(bb.getFloat(index));}}
Output:
Exception in thread "main" java.lang.IndexOutOfBoundsException at java.base/java.nio.Buffer.checkIndex(Buffer.java:744) at java.base/java.nio.HeapByteBuffer.getFloat(HeapByteBuffer.java:551)
No comments:
Post a Comment