print() vs. println() vs. printf()

G-NOTE·2021년 10월 18일
0

Spring

목록 보기
10/14

print()

  • 출력문 내부의 값을 그대로 출력한다. (자동 개행 없음)
System.out.print("Hello!");
System.out.print("Hello!");

result

Hello!Hello!

println()

  • 출력문 내부의 값을 그대로 출력한다. (자동 개행 있음)
System.out.println("Hello!");
System.out.println("Hello!");

result

Hello!
Hello!

printf()

  • 값을 다른 형식으로 출력할 수 없는 print(), println()에 반해 printf()는 지시자를 이용해 여러 형식으로 변환하여 출력할 수 있다. (자동 개행 없음)
  • println()은 값을 직접 바꾸지 않는 이상 같은 값을 다른 형식으로 출력할 수 없다.

printf()의 지시자

지시자설명
%c문자(character) 형식으로 출력
%s문자열(string) 형식으로 출력
%bboolean 형식으로 출력
%d10진수(decimal) 형식으로 출력
%o8진수(octal) 형식으로 출력
%x16진수(hexadecimal) 형식으로 출력
%f부동소수점(floating point) 형식으로 출력
%e지수(exponent) 표현식의 형식으로 출력
%n줄바꿈

주의사항

  • 지시자의 개수와 출력하려는 값의 수는 같아야 한다.
  • 출력하려는 값은 ,으로 구분한다.
  • 출력하려는 값은 지시자의 순서와 동일해야 한다. (틀리면 에러 발생)
System.out.printf("%d", 10); // 10
System.out.println();
System.out.printf("%o%n", 10); // 12
System.out.printf("%x", 10); // a

result

10
12
a
String name = "John";
int age = 30;
	
System.out.printf("My name is %s. I'm %d years old.%n", name, age);
System.out.printf("My name is %s. I'm %d years old.", "", age);

result

My name is John. I'm 30 years old.
My name is . I'm 30 years old.

참고

https://keep-cool.tistory.com/15
https://iinomad.com/3

profile
FE Developer

0개의 댓글