Bytes Class | Guava | Java
Last Updated :
20 Nov, 2019
Bytes is a utility class for primitive type byte. It provides Static utility methods pertaining to byte primitives, that are not already found in either Byte or Arrays and interpret bytes as neither signed nor unsigned. The methods which specifically treat bytes as signed or unsigned are found in SignedBytes and UnsignedBytes.
Declaration :
@GwtCompatible(emulated=true)
public final class Bytes
extends Object
Below table shows the methods provided by Guava Bytes Class :
Exceptions :
- ensureCapacity : IllegalArgumentException if minLength or padding is negative.
- toArray : NullPointerException if collection or any of its elements is null.
Below given are some examples showing the implementation of Guava Bytes Class methods :
Example 1 :
import com.google.common.primitives.Bytes;
import java.util.*;
class GFG {
public static void main(String[] args)
{
byte arr[] = { 3 , 4 , 5 , 6 , 7 };
List<Byte> myList = Bytes.asList(arr);
System.out.println(myList);
}
}
|
Output :
[3, 4, 5, 6, 7]
Example 2 :
import com.google.common.primitives.Bytes;
import java.util.*;
class GFG {
public static void main(String[] args)
{
byte [] arr = { 3 , 4 , 5 , 6 , 7 };
System.out.println(Bytes.indexOf(arr, ( byte ) 5 ));
}
}
|
Output :
2
Example 3 :
import com.google.common.primitives.Bytes;
import java.util.*;
class GFG {
public static void main(String[] args)
{
byte [] arr1 = { 3 , 4 , 5 };
byte [] arr2 = { 6 , 7 };
byte [] arr = Bytes.concat(arr1, arr2);
System.out.println(Arrays.toString(arr));
}
}
|
Output :
[3, 4, 5, 6, 7]
Example 4 :
import com.google.common.primitives.Bytes;
class GFG {
public static void main(String[] args)
{
byte [] arr = { 3 , 4 , 5 , 6 , 7 };
System.out.println(Bytes.contains(arr, ( byte ) 8 ));
System.out.println(Bytes.contains(arr, ( byte ) 7 ));
}
}
|
output :
false
true
Example 5 :
import com.google.common.primitives.Bytes;
class GFG {
public static void main(String[] args)
{
byte [] arr = { 3 , 4 , 5 , 6 , 7 , 5 , 5 };
System.out.println(Bytes.lastIndexOf(arr, ( byte ) 5 ));
}
}
|
Output :
6
Example 6 :
import com.google.common.primitives.Bytes;
class GFG {
public static void main(String[] args)
{
byte [] arr = { 3 , 4 , 5 , 6 , 7 , 5 , 5 };
System.out.println(Bytes.lastIndexOf(arr, ( byte ) 9 ));
}
}
|
Output :
-1
Share your thoughts in the comments
Please Login to comment...