Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use printf() method with long values in Java?

I remember that I did this in C but I couldn’t get it work in Java.

How to print long values with printf() method in Java?

I tried with below code what I actually need is to print the long value in hexadecimal way like below

long l = 32L -----> 0000000000000022

If I use %d then it prints integer value which I don’t want...

class TestPrintf() 
{
    public static void main(String[] args)
    {

    long l = 100L;

    System.out.printf(“%l”+l); // Error unknown format exception
    System.out.printf(“%d”+l); // Prints 100
    System.out.printf(“%f”+l); // Unknown illegal format conversion float != java.lang.long
    }
}
like image 731
Karthik Cherukuri Avatar asked Feb 16 '15 09:02

Karthik Cherukuri


People also ask

How do you print a long in Java?

The println(long) method of PrintStream Class in Java is used to print the specified long value on the stream and then break the line. This long value is taken as a parameter. Parameters: This method accepts a mandatory parameter longValue which is the long value to be written on the stream.

What is %N in Java printf?

By using %n in your format string, you tell Java to use the value returned by System. getProperty("line. separator") , which is the line separator for the current system.

Can we use printf () apart from just printing values if yes then where in Java?

The printf function of C can do a lot more than just printing the values of variables. We can also format our printing with the printf function. We will first see some of the format specifiers and special characters and then start the examples of formatted printing.


Video Answer


2 Answers

You need to put the actual argument to print as the next argument of a printf() methods. Concatenating will not work.

System.out.printf("%d%n", 123);             // for ints and longs
System.out.printf("%d%n", 12345L);          // for ints and longs
System.out.printf("%f%n", (double) 12345L); // for floating point numbers

Full documentation in java.util.Formatter

like image 189
Crazyjavahacking Avatar answered Sep 30 '22 03:09

Crazyjavahacking


If you want a 16-character zero-padded string, with A-F in uppercase, prefixed by 0x, you should use:

System.out.printf("0x%016X", l);
like image 32
Andy Turner Avatar answered Sep 30 '22 02:09

Andy Turner