當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java print()和println()的區別用法及代碼示例


Java中的print():print()方法用於在控製台上顯示文本。此文本以字符串形式作為參數傳遞給此方法。此方法將在控製台上打印文本,光標停留在控製台上文本的結尾。下一個打印從這裏開始。

各種print()方法:

void print(boolean b) - Prints a boolean value.

void print(char c) - Prints a character.

void print(char[] s) - Prints an array of characters.



void print(double d) - Prints a double-precision floating-point number.

void print(float f) - Prints a floating-point number.

void print(int i) - Prints an integer.

void print(long l) - Prints a long integer.

void print(Object obj) - Prints an object.

void print(String s) - Prints a string.

例:

import java.io.*; 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        // The cursor will remain 
        // just after the 1 
        System.out.print("GfG1"); 
  
        // This will be printed 
        // just after the GfG2 
        System.out.print("GfG2"); 
    } 
}
輸出:

GfG1GfG2

Java中的println():println()方法也用於在控製台上顯示文本。此文本以字符串形式作為參數傳遞給此方法。此方法在控製台上打印文本,光標停留在控製台下一行的開頭。下一個打印從下一行開始。

各種println()方法:

void println() - Terminates the current line by writing the line separator string.

void println(boolean x) - Prints a boolean and then terminate the line.

void println(char x) - Prints a character and then terminate the line.

void println(char[] x) - Prints an array of characters and then terminate the line.

void println(double x) - Prints a double and then terminate the line.

void println(float x) - Prints a float and then terminate the line.

void println(int x) - Prints an integer and then terminate the line.

void println(long x) - Prints a long and then terminate the line.

void println(Object x) - Prints an Object and then terminate the line.

void println(String x) - Prints a String and then terminate the line.

例:

import java.io.*; 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        // The cursor will after GFG1 
        // will at the start 
        // of the next line 
        System.out.println("GfG1"); 
  
        // This will be printed at the 
        // start of the next line 
        System.out.println("GfG2"); 
    } 
}
輸出:
GfG1
GfG2

print()和println()之間的差異

println() print()
消息分發後,它將添加新行。 它不會添加任何新行。
它可以不帶參數地工作。 此方法僅適用於參數,否則為語法錯誤。

相關用法


注:本文由純淨天空篩選整理自AnshulVaidya大神的英文原創作品 Difference between print() and println() in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。