Java Tutorial : Java Integer Literals Explained: Decimal, Binary, Octal & Hex | S7


Test Your Knowledge

Take this quiz to test your understanding of Java Integer Literals.


Introduction:

In Session 7, we dive into Java Integer Literals, exploring the various ways to represent integer values using Decimal, Binary, Octal, and Hexadecimal formats. Understanding these literals is crucial for dealing with different data representations in Java.

Decimal Literals

Decimal literals are the most common and use base 10. For example:

int decimal = 100;
int negativeDecimal = -50;

Here, 100 and -50 are decimal literals representing positive and negative integer values respectively.

Binary Literals

Binary literals use base 2 and are prefixed with 0b or 0B. For example:

int binary = 0b1100100;
int negativeBinary = -0b1100100;

The binary literal 0b1100100 equals 100 in decimal, and -0b1100100 represents a negative binary literal.

Octal Literals

Octal literals use base 8 and are prefixed with 0. For example:

int octal = 0144;
int negativeOctal = -0144;

The octal literal 0144 equals 100 in decimal, and -0144 is the negative equivalent.

Hexadecimal Literals

Hexadecimal literals use base 16 and are prefixed with 0x or 0X. For example:

int hex = 0x64;
int negativeHex = -0x64;

The hexadecimal literal 0x64 equals 100 in decimal, and -0x64 represents the negative hexadecimal literal.

Code Examples

Here are some additional examples to illustrate how different literals can be used in Java:

 




public class IntegerLiteralsExample {
    public static void main(String[] args) {
        // Decimal Literals
        int decimal1 = 123;
        int decimal2 = -456;

        // Binary Literals
        int binary1 = 0b101010;
        int binary2 = -0b110110;

        // Octal Literals
        int octal1 = 0754;
        int octal2 = -0342;

        // Hexadecimal Literals
        int hex1 = 0x1F;
        int hex2 = -0xA5;

        // Print all values
        System.out.println("Decimal 1: " + decimal1);
        System.out.println("Decimal 2: " + decimal2);
        System.out.println("Binary 1: " + binary1);
        System.out.println("Binary 2: " + binary2);
        System.out.println("Octal 1: " + octal1);
        System.out.println("Octal 2: " + octal2);
        System.out.println("Hexadecimal 1: " + hex1);
        System.out.println("Hexadecimal 2: " + hex2);
    }
}(code-box)

This code demonstrates how different types of integer literals are declared and printed in Java.

Conclusion

Understanding the different integer literals in Java is essential for working with various numeric systems. Whether you need to use decimal, binary, octal, or hexadecimal, Java provides straightforward syntax to represent these values.

Call to Action

Experiment with different integer literals in your code. Try converting between decimal, binary, octal, and hexadecimal to deepen your understanding!

Post a Comment

0 Comments