Java程序中方法名首字母大写会产生什么影响?
Java方法名首字母大写为何仍能正常运行?
Java语法没有强制要求方法名首字母小写,只要方法名是合法标识符(由字母、数字、下划线、$组成,不以数字开头,不是关键字),就能通过编译并正常运行。你测试的代码里,
Accept()、ReplaceVowel()这类首字母大写的方法完全符合语法规则,所以程序运行无异常。方法名首字母小写是Java编码规范里的约定(比如Oracle官方的Java代码规范),核心目的是提升代码可读性:类名首字母大写,方法和变量名首字母小写,能快速区分类与方法/变量,让团队协作的代码风格统一,降低理解成本。
你提到的
Main()方法能运行,是BlueJ环境的特殊处理。标准Java中程序入口必须是public static void main(String[] args),但BlueJ为了简化教学,允许省略参数直接运行类中的main(或Main)方法。
以下是你的测试代码:
import java.util.Scanner; class Replace3meth { String str, newstr; int len, vcount; public void Accept() { // obtaining input System.out.println("\f");//clearing the screen Scanner sc = new Scanner(System.in); System.out.println("Enter a sentence"); str = sc.nextLine(); str = str.toLowerCase(); } // accept() method ends public void ReplaceVowel() { len = str.length(); newstr = ""; vcount = 0; char c; for (int i = 0; i < len; i++) { // finding no. of vowels c = str.charAt(i); if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { c = Character.toUpperCase(c); vcount++; } // if function ends newstr = newstr + c; } // for loop ends } // replaceVowel() method ends public void Display() { // printing output System.out.println("Original sentence:" +str); System.out.println("New sentence: "+newstr); System.out.println("No. of vowels: "+vcount); } // display() method ends public static void Main() { // calling all methods Replace3meth obj = new Replace3meth(); obj.Accept(); obj.ReplaceVowel(); obj.Display(); } // main() method ends } // class ends
内容的提问来源于stack exchange,提问作者Mr Gubbo
相关产品推荐
相关产品推荐

