編寫方法名時,應遵循駝峰命名法,即第一個單詞的首字母應小寫,其餘單詞的首字母應大寫。示例 public class Test { public void sampleMethod() { System.out.println("This is sample method"); } public void demoMethod() { System.out.println("This is demo method"); } public static void main(String args[]) { Test obj = new Test(); obj.sample(); obj.demo(); } } 輸出 This is sample method This is demo method
關鍵字 Java 中的關鍵字對編譯器具有特殊含義,因此不能用作識別符號。Java 提供了一組 50 個關鍵字。abstract continue for new switch assert default goto package synchronized boolean do if private this break double implements protected throw byte else import public throws case enum instanceof return transient catch extends int short try char final long strictfp volatile const float native super while 保留字 在上面提到的關鍵字列表中,關鍵字 goto 和 const 目前未使用。它們是保留字(供將來使用)。
Java 中的有效識別符號 – 必須以字母(A 到 Z 或 a 到 z)、貨幣字元 ($) 或下劃線 (_) 開頭。第一個字元之後可以是任何字元組合。不能是關鍵字。示例 下面的示例顯示了在 Java 中宣告變數時使用的各種可能的識別符號。即時演示 public class VariableTest { public static void main(String args[]) { // 宣告名為 num 的變數 int num = 1; ... 閱讀更多
多行註釋 (/* */) 用於註釋原始碼中的多行。示例 即時演示 public class CommentsExample { /* 下面是這裡的主要方法,我們建立一個名為 num 的變數。並列印其值 * */ public static void main(String args[]) { // 宣告名為 num 的變數 int num = 1; ... 閱讀更多
要註釋特定行,只需在該行之前放置“雙反斜槓 (//)”即可,如下所示。 // Hello this line is commented 示例 下面的示例演示了在 Java 中使用單行註釋。即時演示 public class CommentsExample { public static void main(String args[]) { // 宣告名為 num 的變數 int num = 1; // 列印變數 num 的值 System.out.println("value if the variable num: "+num); } } 輸出 value if the variable num: 1
java.lang 包是 Java 中的預設包,預設情況下會匯入它。因此,無需顯式匯入此包。即,無需匯入即可訪問此包的類。示例 如果您觀察下面的示例,我們沒有顯式匯入 lang 包,但我們仍然能夠使用 java.lang.Math 類的 sqrt() 方法計算數字的平方根。即時演示 public class LangTest { public static void main(String args[]) { int num = 100; ... 閱讀更多