以上两步合并:int[] scores = new int[5];
3. 赋值 scores[0] = 76;
以上三步合并:int[] scores = {76, 80, 81, 82, 99};
等价于int[] scores = new int[]{76, 80, 81, 82, 99};
数组名.length:获取数组的长度
Arrays类是java提供的一个工具类,在java.util包中。
foreach 并不是java中的关键字,是for语句的特殊简化版本。
for (元素类型 元素变量:遍历对象) {
执行代码;
}
String[] subjects = new String[5]; subjects[0] = "Oricle"; subjects[1] = "PHP"; subjects[2] = "Linux"; subjects[3] = "Java"; subjects[4] = "Html"; //System.out.println("数组中第4个科目为:" + subjects[3]); Arrays.sort(subjects); for (int i = 0; i < subjects.length; i++) { System.out.println(subjects[i]); } System.out.println("输出数组中的元素:" + Arrays.toString(subjects)); for (String subject : subjects) { System.out.println(subject); }
在定义二维数组时,可以至指定行的个数,然后再为每一行分别指定列的个数,如果每行的列数不同,则创建的是不规则的二维数组。
String[][] names = {{"tom", "jack", "mike"}, {"zhangsan", "lisi", "wangwu"}}; for (int i= 0; i < names.length; i++) { for (int j = 0; j < names[i].length; j++) { System.out.println(names[i][j]); } }
定义方法:访问修饰符 返回值类型 方法名(参数列表) {
方法体
}
package com.test; public class Demo4 { public static void main(String[] args) { Demo4 demo = new Demo4(); demo.show(); double avg = demo.calcAvg(); System.out.println("平均成绩为:" + avg); } public void show() { System.out.println("Welcome to java!"); } public double calcAvg() { double java = 92.5; double php = 83.0; double avg = (java + php) / 2; return avg; } }
返回值为:
Welcome to java!
平均成绩为:87.75
把定义方法时的参数称为形参,目的是用来定义方法需要传入的参数的个数和类型;把调用方法时的参数称为实参,是传递给方法真正被处理的值。
public static void main(String[] args) { Demo4 demo= new Demo4(); demo.calcAvg(94, 81); } public void calcAvg(double score1, double score2) { double avg = (score1 + score2) / 2; System.out.println("平均分:"+avg); }
定义:如果同一个类中包含了两个或两个以上方法名相同、方法参数的个数、顺序或类型不同的方法,称为方法的重载,也可称为该方法被重载了。
方法的重载与方法的修饰符或返回值没有关系
public class HelloWorld { public static void main(String[] args) { HelloWorld hello = new HelloWorld(); // 调用无参的方法 hello.print(); // 调用带有一个字符串参数的方法 hello.print("java"); // 调用带有一个整型参数的方法 hello.print(18); } public void print() { System.out.println("无参的print方法"); } public void print(String name) { System.out.println("带有一个字符串参数的print方法,参数值为:" + name); } public void print(int age) { System.out.println("带有一个整型参数的print方法,参数值为:" + age); } }
返回值为:
无参的print方法 带有一个字符串参数的print方法,参数值为:java 带有一个整型参数的print方法,参数值为:18
原文:http://www.cnblogs.com/tianxintian22/p/6443004.html