Contents
Wrapper Classes
Wrapper Classes in Java
The first question that typically comes to mind is, “When we already have primitive data types, why do we need wrapper classes in Java?” The reason lies in the additional functionality provided by wrapper classes that primitive data types lack. These features primarily include useful methods like valueOf()
, parseInt()
, toString()
, and more.
A wrapper class “wraps” around a primitive data type, giving it an object representation. These classes are final and immutable. Two key concepts related to wrapper classes are autoboxing and unboxing.
1. Autoboxing is the automatic conversion of a primitive value into an instance of its corresponding wrapper class (e.g., converting an int
to an Integer
). The Java compiler applies autoboxing when:
- A primitive value is passed as an argument to a method that expects an object of the corresponding wrapper class.
- A primitive value is assigned to a variable of the corresponding wrapper class.
2. Unboxing is the automatic conversion of an instance of a wrapper class to its corresponding primitive value (e.g., converting an Integer
to an int
). The Java compiler applies unboxing when:
- An object of a wrapper class is passed as an argument to a method that expects a primitive type.
- An object of a wrapper class is assigned to a variable of the corresponding primitive type.
Features of Wrapper Classes
Some of the notable benefits of wrapper classes include:
1. They allow conversion between primitive data types and objects. This is useful in cases where arguments passed to methods need to be modified, as primitives are passed by value.
2. Java classes, such as those in the java.util package, deal with objects rather than primitive types, making wrapper classes essential.
3. Data structures in the Collection Framework (e.g., ArrayList, Vector) store only objects, not primitives.
4. Wrapper classes enable object creation for synchronization in multithreading.
They provide numerous utility methods. For instance, a float value can be converted to its integer equivalent using the provided method.
Example 1: Autoboxing in Java
The following code demonstrates autoboxing, where primitive types are automatically converted to their corresponding wrapper classes:
import java.util.*;
class WrapperDemo {
public static void main(String[] args) {
int x = 10;
double y = 7.25;
long z = 12345;
// Autoboxing: converting primitives to objects
Integer intObj = x;
Double doubleObj = y;
Long longObj = z;
// Output the wrapped values
System.out.println(intObj);
System.out.println(doubleObj);
System.out.println(longObj);
}
}
Output:
10
7.25
12345
Example 2: Wrapper Class Utility Methods
Here’s another example that illustrates the utility methods provided by wrapper classes:
import java.io.*;
class WrapperUtility {
public static void main(String[] args) {
// Converting a float to int using a wrapper class method
Float floatValue = Float.valueOf(28.97f);
int convertedValue = floatValue.intValue();
// Output the converted value
System.out.println(convertedValue);
// Converting a binary string to an integer
Integer binaryValue = Integer.valueOf("1101", 2);
// Output the converted integer from binary
System.out.println(binaryValue);
}
}
Output:
28
13
Character Class in Java
Java provides the Character
class within the java.lang
package as a wrapper for the primitive char
data type. This class encapsulates a single char
value and offers numerous useful methods to manipulate characters. The Character
class also supports Autoboxing, where a primitive char
is automatically converted to a Character
object when necessary.
Creating a Character
Object:
Character myChar = new Character('b');
This statement creates a Character
object containing the character 'b'
. The Character
class constructor takes a single argument of type char
.
Autoboxing allows Java to automatically convert a char
to a Character
object if a method expects an object. Conversely, unboxing converts the object back to a primitive char
.
/** This is a documentation comment */
Methods of the Character
Class
Here are some important methods provided by the Character
class:
1. boolean isLetter(char ch)
This method checks whether a given character is a letter (A-Z or a-z).
Syntax:
boolean isLetter(char ch)
Example:
public class Demo {
public static void main(String[] args) {
System.out.println(Character.isWhitespace(' '));
System.out.println(Character.isWhitespace('\t'));
System.out.println(Character.isWhitespace('X'));
}
}
Output:
true
true
false
2. boolean isUpperCase(char ch)
This method checks whether the given character is uppercase.
Syntax:
boolean isUpperCase(char ch)
Example:
public class Demo {
public static void main(String[] args) {
System.out.println(Character.isUpperCase('K'));
System.out.println(Character.isUpperCase('k'));
}
}
Output:
true
false
3. char toUpperCase(char ch)
This method converts a lowercase character to its uppercase equivalent.
Syntax:
char toUpperCase(char ch)
Example:
public class Demo {
public static void main(String[] args) {
System.out.println(Character.toUpperCase('m'));
System.out.println(Character.toUpperCase('M'));
}
}
Output:
M
M
4. char toLowerCase(char ch)
This method converts an uppercase character to its lowercase equivalent.
Syntax:
char toLowerCase(char ch)
Examples:
public class Demo {
public static void main(String[] args) {
System.out.println(Character.toLowerCase('N'));
System.out.println(Character.toLowerCase('n'));
}
}
Output:
n
n
Escape Sequences
Java allows the use of escape sequences to represent special characters in strings. Here are some common escape sequences:
Escape Sequence | Description |
---|---|
\t | Inserts a tab |
\b | Inserts a backspace |
\n | Inserts a newline |
\r | Inserts a carriage return |
\f | Inserts a formfeed |
\' | Inserts a single quote |
\" | Inserts a double quote |
\\ | Inserts a backslash |
Example:
public class EscapeDemo {
public static void main(String[] args) {
System.out.println("He said, \"Java is fun!\"");
System.out.println("Line1\nLine2");
}
}
Output:
He said, "Java is fun!"
Line1
Line2
Java.Lang.Byte class in Java
The Byte
class in Java is a wrapper class for the primitive byte
type, which provides methods for dealing with byte values, such as converting them to string representations and vice versa. A Byte
object can hold a single byte
value.
Constructors of Byte Class
There are two primary constructors used to initialize a Byte
object:
1. Byte(byte b)
Initializes a Byte
object with the given byte value.
public Byte(byte b)
Parameters:b
: The byte value to initialize the Byte
object with.
2. Byte(String s)
Initializes a Byte
object using the byte value from the provided string representation. The string is parsed as a decimal value by default.
Syntax:
public Byte(String s) throws NumberFormatException
Parameter:value
: string representing a byte value.
Fields in Byte Class
static int BYTES : The number of bytes used to represent a byte value in two’s complement binary form.
static byte MAX_VALUE : The maximum value a byte can have, which is 2⁷ – 1 (i.e., 127).
static byte MIN_VALUE : The minimum value a byte can have, which is -2⁷ (i.e., -128).
static int SIZE : The number of bits used to represent a byte value (8 bits).
static Class<Byte> TYPE : The
Class
instance representing the primitive typebyte
.
Methods in Byte Class
1. toString()
Returns the string representation of the byte value.
Syntax:
public String toString(byte value)
2. valueOf()
Returns a Byte
object initialized with the provided byte value.
Syntax:
public static Byte valueOf(byte value)
3. valueOf(String value, int radix)
Parses the string into a byte value based on the given radix and returns a Byte
object.
Syntax:
public static Byte valueOf(String value, int radix) throws NumberFormatException
4. parseByte()
Converts a string into a primitive byte value, with or without a specified radix.
Syntax:
public static byte parseByte(String value, int radix) throws NumberFormatException
5. decode()
Decodes a string into a Byte
object. The string can be in decimal, hexadecimal, or octal format.
Syntax:
public static Byte decode(String value) throws NumberFormatException
6. byteValue(), shortValue(), intValue(), longValue(), floatValue(), doubleValue()
These methods return the respective primitive values corresponding to the Byte
object.
7. hashCode()
Returns the hash code for the Byte
object.
8. equals()
Compares two Byte
objects for equality.
9. compareTo()
Compares two Byte
objects numerically.
10. compare()
Compares two primitive byte values.
Java Program to Illustrate Byte Class Methods
public class ByteExample {
public static void main(String[] args) {
byte num = 42;
String numStr = "36";
// Constructing two Byte objects
Byte byteObj1 = new Byte(num);
Byte byteObj2 = new Byte(numStr);
// toString()
System.out.println("toString(num) = " + Byte.toString(num));
// valueOf()
Byte byteVal1 = Byte.valueOf(num);
System.out.println("valueOf(num) = " + byteVal1);
byteVal1 = Byte.valueOf(numStr);
System.out.println("valueOf(numStr) = " + byteVal1);
byteVal1 = Byte.valueOf(numStr, 8);
System.out.println("valueOf(numStr, 8) = " + byteVal1);
// parseByte()
byte primitiveByte = Byte.parseByte(numStr);
System.out.println("parseByte(numStr) = " + primitiveByte);
primitiveByte = Byte.parseByte(numStr, 8);
System.out.println("parseByte(numStr, 8) = " + primitiveByte);
// decode()
String decString = "50";
String octString = "040";
String hexString = "0x2A";
Byte decodedByte = Byte.decode(decString);
System.out.println("decode(50) = " + decodedByte);
decodedByte = Byte.decode(octString);
System.out.println("decode(040) = " + decodedByte);
decodedByte = Byte.decode(hexString);
System.out.println("decode(0x2A) = " + decodedByte);
// Various primitive type conversions
System.out.println("byteValue() = " + byteObj1.byteValue());
System.out.println("shortValue() = " + byteObj1.shortValue());
System.out.println("intValue() = " + byteObj1.intValue());
System.out.println("longValue() = " + byteObj1.longValue());
System.out.println("floatValue() = " + byteObj1.floatValue());
System.out.println("doubleValue() = " + byteObj1.doubleValue());
// hashCode()
int hash = byteObj1.hashCode();
System.out.println("hashCode() = " + hash);
// equals()
boolean isEqual = byteObj1.equals(byteObj2);
System.out.println("equals() = " + isEqual);
// compare()
int compareResult = Byte.compare(byteObj1, byteObj2);
System.out.println("compare() = " + compareResult);
// compareTo()
int compareToResult = byteObj1.compareTo(byteObj2);
System.out.println("compareTo() = " + compareToResult);
}
}
Output:
toString(num) = 42
valueOf(num) = 42
valueOf(numStr) = 36
valueOf(numStr, 8) = 30
parseByte(numStr) = 36
parseByte(numStr, 8) = 30
decode(50) = 50
decode(040) = 32
decode(0x2A) = 42
byteValue() = 42
shortValue() = 42
intValue() = 42
longValue() = 42
floatValue() = 42.0
doubleValue() = 42.0
hashCode() = 42
equals() = false
compare() = 6
compareTo() = 6
Java.Lang.Short class in Java
Short Class in Java
The Short
class is a wrapper for the primitive short
data type. It provides various methods for handling short values, such as converting them to and from string representations. An instance of the Short
class can store a single short value.
Constructors in the Short Class
The Short
class has two main constructors:
1. Short(short value)
This constructor creates a Short
object initialized with the provided short value.
Syntax:
public Short(short value)
Parameters:value
: The short value used for initialization.
2. Short(String s)
This constructor creates a Short
object from a string representing a short value, with the default base (radix) of 10.
Syntax:
public Short(String s) throws NumberFormatException
Parameters:s
: A string representing the short value.
Throws:NumberFormatException
if the string does not represent a valid short value.
Methods in the Short Class
1. toString()
This method converts a short value to its string representation.
Syntax:
public static String toString(short value)
2. valueOf()
This method returns a Short
object initialized with the given short value.
Syntax:
public static Short valueOf(short value)
3. parseShort()
This method parses the string argument to return a primitive short value.
Syntax:
public static short parseShort(String s, int radix) throws NumberFormatException
4. decode()
This method decodes a string to return a Short
object. It supports decimal, hexadecimal, and octal representations.
Syntax:
public static Short decode(String s) throws NumberFormatException
5. byteValue(), shortValue(), intValue(), longValue(), floatValue(), doubleValue()
These methods return the corresponding primitive value from the Short
object.
6. hashCode()
Returns the hash code for this Short
object.
Syntax:
public int hashCode()
7. equals()
Checks if two Short
objects are equal.
Syntax:
public boolean equals(Object obj)
8. compareTo()
Compares two Short
objects.
Syntax:
public int compareTo(Short anotherShort)
9. compare()
Compares two primitive short values.
Syntax:
public static int compare(short x, short y)
10. reverseBytes()
This method reverses the order of the bytes in the given short value.
Syntax:
public static short reverseBytes(short value)
Example:
public class ShortExample {
public static void main(String[] args) {
// Short value and string representation
short sValue = 90;
String sString = "50";
// Creating two Short objects
Short first = new Short(sValue);
Short second = new Short(sString);
// toString()
System.out.println("toString(sValue) = " + Short.toString(sValue));
// valueOf()
Short obj1 = Short.valueOf(sValue);
System.out.println("valueOf(sValue) = " + obj1);
obj1 = Short.valueOf(sString);
System.out.println("valueOf(sString) = " + obj1);
obj1 = Short.valueOf(sString, 7);
System.out.println("valueOf(sString, 7) = " + obj1);
// parseShort()
short parsedValue = Short.parseShort(sString);
System.out.println("parseShort(sString) = " + parsedValue);
parsedValue = Short.parseShort(sString, 7);
System.out.println("parseShort(sString, 7) = " + parsedValue);
// decode()
String decimalString = "40";
String octalString = "006";
String hexString = "0x10";
Short decoded = Short.decode(decimalString);
System.out.println("decode(40) = " + decoded);
decoded = Short.decode(octalString);
System.out.println("decode(006) = " + decoded);
decoded = Short.decode(hexString);
System.out.println("decode(0x10) = " + decoded);
// Primitive value methods
System.out.println("byteValue(first) = " + first.byteValue());
System.out.println("shortValue(first) = " + first.shortValue());
System.out.println("intValue(first) = " + first.intValue());
System.out.println("longValue(first) = " + first.longValue());
System.out.println("floatValue(first) = " + first.floatValue());
System.out.println("doubleValue(first) = " + first.doubleValue());
// Hash code
int hash = first.hashCode();
System.out.println("hashCode(first) = " + hash);
// Equality check
boolean isEqual = first.equals(second);
System.out.println("first.equals(second) = " + isEqual);
// Comparison
int comparison = Short.compare(first, second);
System.out.println("compare(first, second) = " + comparison);
int compareTo = first.compareTo(second);
System.out.println("first.compareTo(second) = " + compareTo);
// Reverse bytes
short toReverse = 60;
System.out.println("Short.reverseBytes(toReverse) = " + Short.reverseBytes(toReverse));
}
}
Output:
toString(sValue) = 90
valueOf(sValue) = 90
valueOf(sString) = 50
valueOf(sString, 7) = 35
parseShort(sString) = 50
parseShort(sString, 7) = 35
decode(40) = 40
decode(006) = 6
decode(0x10) = 16
byteValue(first) = 90
shortValue(first) = 90
intValue(first) = 90
longValue(first) = 90
floatValue(first) = 90.0
doubleValue(first) = 90.0
hashCode(first) = 90
first.equals(second) = false
compare(first, second) = 40
first.compareTo(second) = 40
Short.reverseBytes(toReverse) = 15360
Java.Lang.Long class in Java
Long Class in Java
The Long
class is a wrapper for the primitive type long
that provides methods to handle long
values more effectively. It can convert a long
to a String
representation and vice versa. A Long
object holds a single long
value, and there are two primary constructors to initialize this object:
Long(long b): Initializes a Long
object with the specified long
value.
public Long(long b)
Parameter:s
: String representation of the long
value.
Key Methods
1. toString(): Converts a long
value to a string representation.
public String toString(long b)
2. toHexString(): Converts a long
value to its hexadecimal string representation.
public String toHexString(long b)
3. toOctalString(): Converts a long
value to its octal string representation.
public String toOctalString(long b)
4. toBinaryString(): Converts a long
value to its binary string representation.
public String toBinaryString(long b)
5. valueOf(): Converts a long
or string to a Long
object.
public static Long valueOf(long b)
public static Long valueOf(String val, long radix) throws NumberFormatException
public static Long valueOf(String s) throws NumberFormatException
6. parseLong(): Converts a string to a primitive long
value.
public static long parseLong(String val, int radix) throws NumberFormatException
public static long parseLong(String val) throws NumberFormatException
7. getLong(): Retrieves the Long
object associated with a system property or returns null
if it doesn’t exist. An overloaded method allows for a default value.
public static Long getLong(String prop)
public static Long getLong(String prop, long val)
8. decode(): Decodes a string into a Long
object (handles decimal, hex, and octal formats).
public static Long decode(String s) throws NumberFormatException
9. rotateLeft(): Rotates the bits of the given long
value to the left by the specified distance.
public static long rotateLeft(long val, int dist)
Example:
public class LongExample {
public static void main(String[] args) {
long num = 30;
String strNum = "25";
// Creating two Long objects
Long obj1 = new Long(num);
Long obj2 = new Long(strNum);
// String conversion
System.out.println("String representation: " + Long.toString(num));
// Hexadecimal, Octal, and Binary conversion
System.out.println("Hexadecimal: " + Long.toHexString(num));
System.out.println("Octal: " + Long.toOctalString(num));
System.out.println("Binary: " + Long.toBinaryString(num));
// Using valueOf()
Long val1 = Long.valueOf(num);
System.out.println("valueOf(num): " + val1);
Long val2 = Long.valueOf(strNum);
System.out.println("valueOf(strNum): " + val2);
Long val3 = Long.valueOf(strNum, 8);
System.out.println("valueOf(strNum, 8): " + val3);
// Using parseLong()
long parsedValue1 = Long.parseLong(strNum);
System.out.println("parseLong(strNum): " + parsedValue1);
long parsedValue2 = Long.parseLong(strNum, 8);
System.out.println("parseLong(strNum, 8): " + parsedValue2);
// getLong() method examples
Long propValue = Long.getLong("java.specification.version");
System.out.println("System property value: " + propValue);
System.out.println("Default value: " + Long.getLong("nonexistent", 5));
// Decode
System.out.println("Decoded (hex): " + Long.decode("0x1f"));
System.out.println("Decoded (octal): " + Long.decode("007"));
// Bit rotation
System.out.println("rotateLeft(30, 2): " + Long.rotateLeft(num, 2));
System.out.println("rotateRight(30, 2): " + Long.rotateRight(num, 2));
}
}
Output:
String representation: 30
Hexadecimal: 1e
Octal: 36
Binary: 11110
valueOf(num): 30
valueOf(strNum): 25
valueOf(strNum, 8): 21
parseLong(strNum): 25
parseLong(strNum, 8): 21
System property value: 19
Default value: 5
Decoded (hex): 31
Decoded (octal): 7
rotateLeft(30, 2): 120
rotateRight(30, 2): 7
Java.Lang.Float class in Java
The Float
class in Java is a wrapper class for the primitive type float
, and it provides several methods to work with float values, such as converting them to string representations and vice-versa. A Float
object can hold a single float value. There are primarily two constructors to initialize a Float
object:
Float(float f)
: This creates a Float
object initialized with the specified float value.
Syntax:
public Float(float f)
Parameters:s
: The string representation of a float value.
Throws:NumberFormatException
: If the provided string cannot be parsed as a float.
Methods of the Float
Class
1. toString(): Returns the string representation of the float value.
Synta
public String toString(float f)
Parameters: f: The float value for which the string representation is required.
2. valueOf():Returns a Float
object initialized with the given float value.
Syntax:
public static Float valueOf(String s) throws NumberFormatException
3. parseFloat():Parses the string as a float and returns the primitive float value.
Syntax:
public static float parseFloat(String s) throws NumberFormatException
4. byteValue():Returns the byte value of the Float
object.
Syntax:
public byte byteValue()
5. shortValue(): Returns the short value of the Float
object.
Syntax:
public short shortValue()
6. intValue(): Returns the int value of the Float
object.
Syntax:
public int intValue()
7. doubleValue():Returns the double value of the Float
object.
Syntax:
Error: variable 'a' is already defined
8. longValue(): Returns the long value of the Float
object.
Syntax:
public double doubleValue()
9. floatValue():Returns the float value of the Float
object.
Syntax:
public float floatValue()
10. floatValue(): Returns the float value of the Float
object.
Syntax:
public float floatValue()
11. isNaN(): Checks whether the float value is NaN
(Not-a-Number).
Syntax:
public boolean isNaN()
12. isInfinite(): Checks whether the float value is infinite.
Syntax:
public boolean isInfinite()
13. toHexString():Returns the hexadecimal representation of the given float value.
Syntax:
public static String toHexString(float val)