【部分内容来自网络,侵删】
数组
一维数组
在java中有三种方式定义数组:
public class Calc {
public static void main(String[] args) {
// 1
int[] arr1 = new int[3];
arr1[0]=12;
arr1[1]=14;
arr1[2]=17;
// 2
int[] arr2 = new int[]{1,4,8,0};
// 3
int[] arr3 = {1,3,7,11,9};
}
}
可以通过length获取数组的长度。
二维数组
二维数组就是数组的数组
public class Calc {
public static void main(String[] args) {
// 1
int[][] arr1 = new int[3][4];
// 2
int[][] arr2 = new int[3][];//第二个维度是不确定的
// 3
int[][] arr3 = {{1,2},{2,3},{3,4}};
}
}
函数(方法)
在Java中,声明一个方法的具体语法格式如下:
修饰符 返回值类型 方法名(参数类型 参数名1,参数类型 参数名2,...){
执行语句
………
return 返回值;
}
对于上面的语法格式中具体说明如下:
-
修饰符:方法的修饰符比较多,有对访问权限进行限定的,有静态修饰符static,还有最终修饰符final等,这些修饰符在后面的学习过程中会逐步介绍
-
返回值类型:用于限定方法返回值的数据类型,void表示没有返回值
-
参数类型:用于限定调用方法时传入参数的数据类型
-
参数名:是一个变量,用于接收调用方法时传入的数据
-
return关键字:用于结束方法以及返回方法指定类型的值
-
返回值:被return语句返回的值,该值会返回给调用者
方法重载
如果有两个方法的方法名相同,但参数不一致,那么可以说一个方法是另一个方法的重载。
- 方法名称必须相同。
- 参数列表必须不同。
- 方法的返回类型可以相同也可以不相同。
- 仅仅返回类型不同不足以称为方法的重载。
public class Calc {
public static void main(String[] args) {
}
public static int add(int a, int b){
return a + b;
}
public static double add(double a, double b){
return a + b;
}
public static String add(String a, String b){
return a + b;
}
}
方法中的参数传递
java中参数传递按照值传递,这里要特别注意字符串类型,字符串会按照基本数据类型那样处理。、
public class Calc {
public static void main(String[] args) {
int a = 10, b = 20;
m1(a, b);
System.out.println(a);//10
System.out.println(b);//20
MyClass obj = new MyClass();
obj.name = "hi";
m2(obj);
System.out.println(obj.name);
String s1 = "hi";
m3(s1);
System.out.println(s1);//hi
String s2 = new String("new string");
m4(s2);
System.out.println(s2);//new string
}
public static void m1(int a, int b){
a = 100;
b = 200;
System.out.println(a);//100
System.out.println(b);//200
}
public static void m2(MyClass obj){
obj.name = "haha";
System.out.println(obj.name);
}
public static void m3(String a){
a = "hello";
}
public static void m4(String a){
a = new String("change");
}
}
class MyClass {
String name;
}
网友评论