Penggunaan printf pada java

 


Penggunaan printf di java %format

  • s =   strings.
  • d =  decimal integers.
  • f  =  floating-point numbers.
  • =  date/time values.
  • n atau bisa juga dengan \n=  garis baru
  • b = boolean
  • c = Char

 

Cara Penggunaannya

%n (new line)
> System.out.printf("copas%ncoding%nmantab");
output

copas
coding
mantab


#String

%s (String)

> printf("%s %n", "copascoding");

> printf("%S %n", "CopasCodingan");

output

copascoding
CodingCodingan


#Jarak

mengatur jarak %s (String)

> System.out.printf("'%15s' %n", "copascoding");

> System.out.printf("'%-10S' %n", "CopasCodingan");

output

'  copascoding'
'CodingCodingan  '


#Desimal

%d (Desimal)

> System.out.printf("simple integer: %d%n", 10000L);

output

simple integer: 10000


#Char

%c (Char)

> System.out.printf("%c%n", 's');

> System.out.printf("%C%n", 'S');

output

s
S


#Gabungan

  (gabungan)

> System.out.printf("CopasCoding: %d%-2c%s", 100 ,'%' ,"instan");

output

CopasCoding: 100% instan


#Format Waktu

  • H, M, S characters are responsible for extracting the hours, minutes and seconds from the input Date.
  • L, N represent the time in milliseconds and nanoseconds accordingly.
  • p adds a.m./p.m. formatting.
  • z prints out the time-zone offset.
%t (time)
> Date date = new Date(); // memanggil waktu
> System.out.printf("%tT%n", date);
output

13:51:15 <-- waktu sekarang


> Date date = new Date(); // memanggil waktu

> System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date);

output

hours 13: minutes 51: seconds 15 <-- waktu sekarang


#Format Tanggal

  • A prints out the full day of the week.
  • d formats a two-digit day of the month.
  • B is for the full month name.
  • m formats a two-digit month.
  • Y outputs a year in four digits.
  • y outputs the last two digits of the year.
%t (time)

> Date date = new Date(); <-- memanggil waktu

> System.out.printf("%1$tA, %1$tB %1$tY %n", date);

output

Thursday, June 2021<-- tanggal sekarang


> Date date = new Date(); <-- memanggil waktu

> System.out.printf("%1$td.%1$tm.%1$ty %n", date);

output

17.06.21 <-- tanggal sekarang