Using underscores in literals to improve code readability - Java Language Basics

Java examples for Language Basics:Primitive Types

Introduction

Numerical literals can contain underscore characters (_) in Java.

Demo Code

public class Main {

    public static void main(String[] args) {
        long debitCard = 1234_5678_9876_5432L;
        System.out.println("The card number is: " + debitCard);
        System.out.print("The formatted card number is:");
        printFormatted(debitCard);//from  ww  w. j  a va  2  s  . c  o m

        float minAmount = 5_000F;
        float currentAmount = 5_250F;
        float withdrawalAmount = 500F;

        if ((currentAmount - withdrawalAmount) < minAmount) {
            System.out.println("Minimum amount limit exceeded " + minAmount);
        }
       
    }

    private static void printFormatted(long cardNumber) {
        String formattedNumber = Long.toString(cardNumber);
        for (int i = 0; i < formattedNumber.length(); i++) {
            if (i % 4 == 0) {
                System.out.print(" ");
            }
            System.out.print(formattedNumber.charAt(i));
        }
        System.out.println();
    }
}

Related Tutorials