1. 认识java的main方法
![image.png](https://img-blog.csdnimg.cn/img_convert/627116b588a26335345a50b5457bbdaf.png#clientId=u648916cb-64cf-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=216&id=u4443ffb4&margin=[object Object]&name=image.png&originHeight=239&originWidth=738&originalType=binary&ratio=1&rotation=0&showTitle=false&size=15253&status=done&style=none&taskId=u7ecd1ee9-6613-4c22-a989-b5833c5979c&title=&width=666.9957885742188)
- 一个java文件当中只能有一个public的类。
- 且 类名 需要和 文件名 是相同的。
比如,文件名为HelloWorld.java,所以此处的类名为HelloWorld
- 编程规范建议:左括号 是紧跟着当前行的。
- 类名 一定要采用大驼峰的形式(单词紧跟着,每个单词的首字母大写)
- 注意:字节码文件 .class文件,一个类对应一个字节码文件
如,一个.java文件里面有两个类,则有两个字节码文件。
![image.png](https://img-blog.csdnimg.cn/img_convert/7338a30a17b68e7aa33ab826adf6d8b3.png#clientId=u641a9f64-56b3-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=259&id=u0dcaaa79&margin=[object Object]&name=image.png&originHeight=273&originWidth=566&originalType=binary&ratio=1&rotation=0&showTitle=false&size=13502&status=done&style=none&taskId=u98cbba34-0af7-4291-9f68-c780935ac90&title=&width=535.9873657226562)
![image.png](https://img-blog.csdnimg.cn/img_convert/2476df7d87c9bdfafebb49a01183b2b2.png#clientId=u641a9f64-56b3-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=171&id=u5cf11b2d&margin=[object Object]&name=image.png&originHeight=255&originWidth=732&originalType=binary&ratio=1&rotation=0&showTitle=false&size=18793&status=done&style=none&taskId=uf2103d29-a0e0-4843-897c-67724b1575a&title=&width=490.9999694824219)
那为什么要这样设置呢?
为了方便使用,Java当中,用到哪个类就加载哪个类。
![image.png](https://img-blog.csdnimg.cn/img_convert/99167181347efe6e95eb9aac5369ffa1.png#clientId=u648916cb-64cf-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=202&id=u831f614f&margin=[object Object]&name=image.png&originHeight=245&originWidth=723&originalType=binary&ratio=1&rotation=0&showTitle=false&size=17402&status=done&style=none&taskId=u7112a6d4-2814-4cd3-8fb6-13d31e2adab&title=&width=595.4999694824219)
运行时命令行参数
public static void main (String[] args) {
}
上述main函数的形参String[] args
是运行时命令行参数。我们下面做个测试:
public static void main (String[] args) {
int i = 0;
for (i = 0; i < args.length; ++i)
{
System.out.println(args[i]);
}
System.out.println("kaixin");
}
可以看到只输出了“kaixn”,没有输出for循环里面的值。
![image.png](https://img-blog.csdnimg.cn/img_convert/88c1348d6197a3351f3ff284c22af9ce.png#clientId=u76f3e23f-5532-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=70&id=u294098f0&margin=[object Object]&name=image.png&originHeight=91&originWidth=848&originalType=binary&ratio=1&rotation=0&showTitle=false&size=18405&status=done&style=none&taskId=u36c5c544-8c09-4e83-bdd2-ec47c898f93&title=&width=653.9957885742188)
当我们在java 文件名
后输入一些字符串,字符串就被存储到args
里面了,就可以打印出for循环里面的内容了。
![image.png](https://img-blog.csdnimg.cn/img_convert/4b4c3d5ba76c0504a2cadb80359103db.png#clientId=u76f3e23f-5532-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=130&id=u1877d366&margin=[object Object]&name=image.png&originHeight=183&originWidth=975&originalType=binary&ratio=1&rotation=0&showTitle=false&size=18179&status=done&style=none&taskId=u643479db-b022-4919-855c-6cbb639bad5&title=&width=691.4999694824219)
2. 如何运行一个java程序
![image.png](https://img-blog.csdnimg.cn/img_convert/2dcde5a3c747d7f7d0031fd9abc055be.png#clientId=u641a9f64-56b3-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=132&id=ucd0136fe&margin=[object Object]&name=image.png&originHeight=183&originWidth=798&originalType=binary&ratio=1&rotation=0&showTitle=false&size=54123&status=done&style=none&taskId=ucfb3dc55-ab44-404b-9a4c-5c4c79ff779&title=&width=576.9999694824219)
- 首先,比如文件HelloWorld.java是存放在磁盘上的。
- 编译该文件,使用
javac 文件名.java
,形成 .class文件。
注意:
- 在cmd上编译文件,需要将当前目录改为文件所在目录,使用命令
cd /d 文件路径
![image.png](https://img-blog.csdnimg.cn/img_convert/0ef287100fabaab231999c76c626fa5d.png#clientId=u641a9f64-56b3-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=86&id=u5415634c&margin=[object Object]&name=image.png&originHeight=102&originWidth=735&originalType=binary&ratio=1&rotation=0&showTitle=false&size=11894&status=done&style=none&taskId=ud3003423-13d1-4cf4-a64a-9fbee931fd1&title=&width=616.4999694824219)
- 在记事本上写代码,需要先保存,再编译。
![image.png](https://img-blog.csdnimg.cn/img_convert/67fc7192d8bee50e26ca01aefd006676.png#clientId=u641a9f64-56b3-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=107&id=ubb615c34&margin=[object Object]&name=image.png&originHeight=121&originWidth=696&originalType=binary&ratio=1&rotation=0&showTitle=false&size=12109&status=done&style=none&taskId=u7b73e092-f071-4b67-a110-656df6f3006&title=&width=616.9999694824219)
编译完后,可在当前目录中看到 .class文件
![image.png](https://img-blog.csdnimg.cn/img_convert/5b2bb09c47409960e16cb8af4ed00213.png#clientId=u641a9f64-56b3-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=195&id=uc59da54c&margin=[object Object]&name=image.png&originHeight=236&originWidth=724&originalType=binary&ratio=1&rotation=0&showTitle=false&size=12583&status=done&style=none&taskId=ua986a4d8-7830-4798-ac9a-8fc13e64fcf&title=&width=598.9915771484375)
- 使用
java 文件名
来运行文件(在JVM(java虚拟机)里运行)
![image.png](https://img-blog.csdnimg.cn/img_convert/267316a8f8e3a2b6611811164228fa48.png#clientId=u641a9f64-56b3-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=67&id=u47894503&margin=[object Object]&name=image.png&originHeight=79&originWidth=623&originalType=binary&ratio=1&rotation=0&showTitle=false&size=7998&status=done&style=none&taskId=u30049cf0-e886-4af3-a288-094d1882184&title=&width=531.4957885742188)
注意:java 和 javac 都属于JDK命令。
![image.png](https://img-blog.csdnimg.cn/img_convert/4420f9d445c0e87fddf5d77a60246889.png#clientId=u641a9f64-56b3-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=278&id=u6bf2a0a7&margin=[object Object]&name=image.png&originHeight=401&originWidth=954&originalType=binary&ratio=1&rotation=0&showTitle=false&size=44924&status=done&style=none&taskId=u2b8441fc-2c6a-417c-9bd7-50a5d5ffe10&title=&width=660.9999694824219)
3. Java当中的注释
- 块注释(快捷键,选中要注释的内容,ctrl+shift+/)
/*这是块注释*/
- 文档注释
/**
* 文档注释:
* 作者:
* 日期:
* 描述:
*/
- 行注释(快捷键:ctrl+/)
// 这是行注释
但是如果程序里面有注释,编译的时候会出现错误,如下图:
![image.png](https://img-blog.csdnimg.cn/img_convert/603ffa7dba9c441df09c4f5d30b23705.png#clientId=u641a9f64-56b3-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=407&id=ucd7cbb94&margin=[object Object]&name=image.png&originHeight=512&originWidth=580&originalType=binary&ratio=1&rotation=0&showTitle=false&size=24673&status=done&style=none&taskId=uecb2606b-73c6-440a-a05d-acf0730243b&title=&width=460.9915771484375)
![image.png](https://img-blog.csdnimg.cn/img_convert/c4835de6a37076ad947edef219cfb057.png#clientId=u641a9f64-56b3-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=267&id=ua5218a55&margin=[object Object]&name=image.png&originHeight=359&originWidth=800&originalType=binary&ratio=1&rotation=0&showTitle=false&size=48989&status=done&style=none&taskId=u7ebdbe7e-84f9-4af9-9a07-b751ffd7a46&title=&width=593.9957885742188)
原因是,代码里面有中文,但是javac编译默认使用GBK来编码的,这就是“字节码格式不匹配导致”的。
这时候我们只需要在后面加-encoding utf-8
编译即可:
![image.png](https://img-blog.csdnimg.cn/img_convert/c461b1a92e3d0c15421b39e595fb0d5a.png#clientId=u641a9f64-56b3-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=59&id=u8ad98e2a&margin=[object Object]&name=image.png&originHeight=85&originWidth=822&originalType=binary&ratio=1&rotation=0&showTitle=false&size=11706&status=done&style=none&taskId=u590dddee-ccc8-4c15-b924-8fffd8a0fea&title=&width=573.9999694824219)
这就告诉编译器,统统以utf-8来编码。
4. 打印数据
有三种方式打印:
![image.png](https://img-blog.csdnimg.cn/img_convert/66dc0c1c0ebecc03fb62a67868696284.png#clientId=u641a9f64-56b3-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=251&id=u40a78957&margin=[object Object]&name=image.png&originHeight=236&originWidth=391&originalType=binary&ratio=1&rotation=0&showTitle=false&size=16381&status=done&style=none&taskId=u591c2b0d-f9d0-4fbd-8712-151998d5eae&title=&width=415.49159240722656)
结果如下:
![image.png](https://img-blog.csdnimg.cn/img_convert/a1c3cac28176fda424b8991261c1895a.png#clientId=u641a9f64-56b3-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=78&id=u5d94ea0b&margin=[object Object]&name=image.png&originHeight=93&originWidth=565&originalType=binary&ratio=1&rotation=0&showTitle=false&size=7382&status=done&style=none&taskId=u9a7d155e-d465-498c-9793-270abd2472f&title=&width=472.4915771484375)
5. 数据类型
5.1 基本数据类型
- 长整型(long)
public static void main1 (String[] args) {
long a = 10L;
System.out.println(a);
System.out.println("最大值:" + Long.MAX_VALUE); // + 为拼接
System.out.println("最小值:" + Long.MIN_VALUE);
int b = 10;
int c = 20;
System.out.println(b + c);
//注意:任何类型的数据 和 字符串进行拼接,结果都是字符串
System.out.println("hhh" + b + c);
}
- 双精度浮点型(double)
/**
* 双精度 浮点型
* @param args [description]
*/
public static void main3 (String[] args) {
double d = 12.5;
System.out.println(d);
System.out.println(Double.MAX_VALUE);
System.out.println(Double.MIN_VALUE);
}
- 单精度浮点型(float):定义变量数值的时候,需要加上
f
或F
/**
* 单精度 float
* 1. double 8个字节
* 2. float 4个字节
*/
public static void main4 (String[] args) {
// float f = 12.3; 会出现错误,不允许从double类型转到float类型
float f = 12.3f;
System.out.println(f);
System.out.println(Float.MAX_VALUE);
System.out.println(Float.MIN_VALUE);
}
- 字符型(char)
/**
* 字符数据类型:
* char 2个字节 0 ~ 65535
* Unicode --> 包含很多字符集,如中文,拉丁文等等
*/
public static void main5 (String[] args) {
char ch = 'a';
System.out.println(ch);
char ch2 = '高';
System.out.println(ch2);
char ch3 = 97;
System.out.println(ch3);
}
- 字节型(byte)
// 字节:byte 1个字节 数值:-128 ~ 127
// 每一种数据类型,在给其赋值的时候,一定不能超过它的范围
public static void main6 (String[] args) {
byte b = 12;
byte c = 21;
System.out.println(b + " " + c);
// byte d = Byte.MAX_VALUE + 1;此处会进行整型提升,从int->byte会编译错误
System.out.println(Byte.MAX_VALUE + 1); //默认输出整型,整型是可以保存数值128的
System.out.println(Integer.MAX_VALUE);
//int i1 = 2147483648; //报错,超出数据类型的范围(Java只会检查 直接赋值的字面值常量是否超出)
//下面的均不会编译报错
int i2 = 2147483647 + 1;
System.out.println(i2);
int i3 = Integer.MAX_VALUE + 1;
System.out.println(i3);
System.out.println(Integer.MAX_VALUE + 1);
}
- 短整型(short)
//短整型:short 2个字节 数值:-32768 ~ 32767
public static void main7 (String[] args) {
short sh = 12;
System.out.println(Short.MAX_VALUE);
System.out.println(Short.MIN_VALUE);
}
- 布尔型(boolean)
/**
* 布尔类型:
* 1.在JAVA中,布尔类型 没有明确的大小
* 2.在JAVA中,布尔类型 只有两个取值 true 和 false
* 3.在JAVA中,没有 所谓的 0是假 非0是真
*/
public static void main7 (String[] args) {
boolean flg = true;
System.out.println(flg);
//报错,只能为布尔值
/*if (1) {
}*/
}
![image.png](https://img-blog.csdnimg.cn/img_convert/bf7008d3bdf242f7f53f5203e3a25f3a.png#clientId=u76f3e23f-5532-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=79&id=uda162622&margin=[object Object]&name=image.png&originHeight=101&originWidth=913&originalType=binary&ratio=1&rotation=0&showTitle=false&size=61178&status=done&style=none&taskId=ua25279b5-6edc-4dc6-b7ef-699ceefdb48&title=&width=714.483154296875)
5.2 引用数据类型
String
语法格式:String 变量名 = "初始值";
- 可以使用转义字符
String name = "My name is \"张三\"";
- 字符串的
+
操作,表示字符串拼接:
String a = "hello";
String b = "world";
String c = a + b;
//输出 helloworld
System.out.println(c);
- 还可以用字符串和整数进行拼接:
String str = "result = ";
int a = 10;
int b = 20;
String result = str + a + b;
//输出为result = 1020
System.out.println(result);
数组(Arrays:操作数组的工具类)
数组的创建
T[] 数组名 = new T[N];
T:表示数组中存放元素的类型。
T[]:表示数组的类型。
N:代表数组的长度。
int[] arr1 = new int[10]; //创建一个可以容纳10个int类型元素的数组
double[] arr1 = new double[5]; //创建一个可以容纳5个double类型元素的数组
跟C语言不同,Java数组是创建在堆上的,不像C语言创建在栈上的。
数组的初始化
分为两种:动态初始化,静态初始化。
- 动态初始化:在创建数组时,直接指定数组中元素的个数。
int[] array = new int[10]; //里面存放了10个0
- 静态初始化:在创建数组时不直接指定数据元素个数,而直接将具体的数据内容进行指定。
语法格式:T[] 数组名称 = {data1,data2,.....,datan};
int[] array = new int[]{1,2,3,4};
array是开辟在栈上,存储的是数组的首地址,数组是开辟在堆上的。也就是说,array是指向{1,2,3,4}这个对象的。
这个时候就有个问题:我们能拿到栈上的地址吗?(比如 int a = 10; 能拿到a 的地址吗?)
答案是:不能,Java很安全,不会让你拿到栈上的地址的。
![image.png](https://img-blog.csdnimg.cn/img_convert/fe14173535a046322654920c0c98025c.png#clientId=u273ed9db-1810-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=239&id=u37d655e0&margin=[object Object]&name=image.png&originHeight=323&originWidth=836&originalType=binary&ratio=1&rotation=0&showTitle=false&size=43312&status=done&style=none&taskId=uaf13c7c0-c7d3-444e-8494-206b5c4305c&title=&width=618.9957885742188)
【注意事项】:
- 静态初始化虽然没有指定数组的长度,编译器在编译时会根据 {} 中元素个数来确定数组的长度。
- 静态初始化时,{} 中数据类型必须与[]前数据类型一致。
- 静态初始化可以简写,省去后面的 new T[]。
- 如果不确定数组当中内容时,使用动态初始化,否则建议使用静态初始化。
- 静态和动态初始化可分为两步,但是省略格式不可以:
int[] array1;
array1 = new int[10];
int[] array2;
array2 = new int[]{10, 20, 30};
//注意省略格式不可以拆分,否则编译失败
// int[] array3;
// array3 = {1, 2, 3};
- 如果没有对数组进行初始化,数组中元素有其默认值:
- 若数组中存储元素类型为基类类型,默认值为基类类型对应的默认值,如:
![image.png](https://img-blog.csdnimg.cn/img_convert/235f7a69c69315e13ea67574cf27e11e.png#clientId=u273ed9db-1810-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=304&id=ufeda2f53&margin=[object Object]&name=image.png&originHeight=471&originWidth=950&originalType=binary&ratio=1&rotation=0&showTitle=false&size=33185&status=done&style=none&taskId=ucca79a2b-f01b-408f-89bb-414241ab520&title=&width=612.9957580566406)
- 如果数组中存储元素类型为引用类型,默认值为null。
#### 数组的使用
数组中元素的访问
数组在内存中是一段连续的空间,空间的编号都是从0开始的,依次递增,该编号称为数组的下标,可通过下标访问数组任意位置的元素。
但是,如果下标越界则会报出下标越界异常。
int[] arr = {1,2,3};
System.out.println(arr[3]); //会抛出越界异常
上面代码的异常为java.lang.ArrayIndexOutOfBoundsException
。
遍历数组
有三种遍历方式:
- for 循环遍历
int[] arr = new int[]{1,2,3,4,5,6,7};
for(int i = 0; i < arr.length;++i) {
System.out.print(arr[i] + " ");
}
在数组中可以通过 数组对象
.length
来获取数组的长度。
- for-each遍历
int[] arr = new int[]{1,2,3,4,5,6,7};
for (int e : arr) {
System.out.print(e + " ");
}
- 使用类
Arrays
的方法toString
,将数组以字符串的形式输出
import java.util.Arrays; // 需包含该类
int[] arr = new int[]{1,2,3,4,5,6,7};
System.out.println(Arrays.toString(arr));
//输出
//[1,2,3,4,5,6,7]
初始JVM的内存分布
内存是一段连续的存储空间,主要用来存储程序运行时的数据。如:
- 程序运行时代码需要加载到内存。
- 程序运行产生的中间数据要存放在内存。
- 程序中常量也要保存。
- 有些数据可能需要长时间存储,而有些数据当方法运行结束后就要被销毁。
如果对内存中存储的数据不加区分的随意存储,那对内存管理起来将会非常麻烦。
因此 JVM 也对所使用的内存按照功能的不同进行了划分:
![JVM内存分布.png](https://img-blog.csdnimg.cn/img_convert/e93697edd6fd321885491c955f481aa1.png#clientId=u273ed9db-1810-4&crop=0&crop=0&crop=1&crop=1&from=ui&height=220&id=ue83718e5&margin=[object Object]&name=JVM内存分布.png&originHeight=611&originWidth=1776&originalType=binary&ratio=1&rotation=0&showTitle=false&size=92011&status=done&style=none&taskId=u9b9dcdc5-3d8c-48c1-8de7-22b9877a496&title=&width=640.8361206054688)
- **程序计数器(PC Register):**只是一个很小的空间,保存下一条指令的地址。
> - **虚拟机栈(JVM Stack):**与方法调用相关的一些信息,**每个方法在执行时,都会先创建一个栈帧,**栈帧包含**局部变量表、操作数栈、动态链接、返回地址**以及其他的一些信息,保存的都是与方法执行时相关的一些信息。比如:局部变量。**当方法运行结束后,栈帧就被销毁,即栈帧中保存的数据也被销毁了。** >
> - **本地方法栈(Native Method Stack):**本地方法栈和虚拟机栈的作用类似,只不过**保存的内容是Native方法的局部变量。(Native方法:底层是用C/C++写的,运行速度快)。** >
> - **堆(Heap):**JVM所管理的最大内存区域。使用**new 创建的对象都是在堆上保存**(例如前面的`new int[]{1,2,3}`),**堆是随着程序开始运行时而创建,随着程序的退出而销毁,堆中的数据只要还有在使用,就不会被销毁。** >
> - **方法区(Method Area):**用于**存储已被虚拟机加载的类信息、常量、静态变量、即时编译器编译后的代码等数据。**方法编译出的字节码就是保存在这个区域。
基本类型变量与引用类型变量的区别
基本数据类型创建的变量,称为基本变量,该变量空间中直接存放的是其所对应的值。
引用数据类型创建的变量,一般称为对象的引用,其空间中存储的是对象所在空间的地址。
public static void func(){
int a = 10;
int b = 20;
int[] arr = new int[]{1,2,3};
}
下面是存放示意图:
![引用变量在内存的位置.png](https://img-blog.csdnimg.cn/img_convert/044ee1a8f2915a4b9ba01c6ce43f8afd.png#clientId=u296f67bb-fb04-4&crop=0&crop=0&crop=1&crop=1&from=ui&id=uf92ab25e&margin=[object Object]&name=引用变量在内存的位置.png&originHeight=694&originWidth=1218&originalType=binary&ratio=1&rotation=0&showTitle=false&size=51412&status=done&style=none&taskId=u5f4def8e-e42a-4b03-bf57-d6cd8a1217c&title=)
认识null
null 在Java中表示“空引用”,也就是一个不指向对象的引用。
![image.png](https://img-blog.csdnimg.cn/img_convert/4047e985e1c9f439265428db5b561058.png#clientId=u296f67bb-fb04-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=99&id=uc060bf34&margin=[object Object]&name=image.png&originHeight=109&originWidth=456&originalType=binary&ratio=1&rotation=0&showTitle=false&size=9212&status=done&style=none&taskId=u07e5e251-cbd0-4a37-9a0c-ac34c96da3c&title=&width=414.99998474121094)
![image.png](https://img-blog.csdnimg.cn/img_convert/868794b240e6ef7fc7430e501bb44198.png#clientId=u296f67bb-fb04-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=60&id=u4e6c1611&margin=[object Object]&name=image.png&originHeight=87&originWidth=837&originalType=binary&ratio=1&rotation=0&showTitle=false&size=14325&status=done&style=none&taskId=u719d2f00-707d-4d4c-b6b0-38fa9763b13&title=&width=572.4957885742188)
null 的作用类似于C语言中的NULL(空指针),都是表示一个无效的内存位置。因此不能对这个内存进行任何读写操作,一旦尝试读写,就会抛出 NullPointerException。
注意:java中并没有约定 null 和 0 号地址的内存有任何关联。
#### 数组作为函数的参数 ```java public class Demo_arr2 { public static void main(String[] args) { int[] arr = {1,2,3}; func(arr); System.out.println("arr[0] = " + arr[0]); }
public static void func(int[] a) {
a[0] = 10;
System.out.println("a[0] = " + a[0]);
}
}
![image.png](https://cdn.nlark.com/yuque/0/2022/png/22870205/1646487657133-17ad7d74-6868-4498-bb07-7f44041e9974.png#clientId=u296f67bb-fb04-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=98&id=u12553f3c&margin=%5Bobject%20Object%5D&name=image.png&originHeight=101&originWidth=348&originalType=binary&ratio=1&rotation=0&showTitle=false&size=7100&status=done&style=none&taskId=u38f0bb07-560b-4922-aa77-5a065be8101&title=&width=337.99998474121094)
<a name="AggJi"></a>
#### 数组作为函数的返回值
```java
import java.util.Arrays;
public class Demo_arr2 {
public static void main(String[] args) {
int[] array = {1,2,3,4,5,6};
int[] ret = func2(array);
System.out.println(Arrays.toString(ret));
}
//将数组a里面的元素扩大两倍,并返回,不改变原有的数组
public static int[] func2(int[] a) {
int[] tmp = new int[a.length];
for (int i = 0;i < a.length; ++i) {
tmp[i] = a[i] * 2;
}
return tmp;
}
}
数组练习
1. 数组转字符串
import java.util.Arrays;
int[] arr = {1,2,3,4,5,6};
String newArr = Arrays.toString(arr);
System.out.println(newArr);
//执行结果
[1,2,3,4,5,6]
2. 数组拷贝
import java.util.Arrays;
public class Demo1 {
// 数组拷贝
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6};
// newArr和arr引用的是同一个数组
int[] newArr = arr;
newArr[0] = 100;
System.out.println("newArr: " + Arrays.toString(arr));
// 使用Arrays中copyOf方法完成数组的拷贝
// copyOf方法在进行数组拷贝时,创建了一个新数组
arr[0] = 1;
// arr和newArr引用的不是同一个数组
newArr = Arrays.copyOf(arr,arr.length);
System.out.println("newArr: " + Arrays.toString(newArr));
// 修改arr引用的内容时,对newArr没有影响
arr[0] = 90;
System.out.println("arr: " + Arrays.toString(arr));
System.out.println("newArr: " + Arrays.toString(newArr));
// 拷贝某个范围
int[] newArr2 = Arrays.copyOfRange(arr,2,4);
System.out.println("newArr2: " + Arrays.toString(newArr2));
}
}
![image.png](https://img-blog.csdnimg.cn/img_convert/93d043c0c68dd211ede893e7e221ec09.png#clientId=uda65bb8b-df7d-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=156&id=u3976561b&margin=[object Object]&name=image.png&originHeight=175&originWidth=491&originalType=binary&ratio=1&rotation=0&showTitle=false&size=17655&status=done&style=none&taskId=u8e94a81d-af7c-4d06-8057-96fd0a14821&title=&width=437.49578857421875)
注意:数组当中存储的是基本数据类型时,无论怎么拷贝基本都不会出现什么问题,但如果存储的是引用数据类型时,拷贝时需要考虑深浅拷贝的问题,这样以后细说。
实现自己版本的拷贝数组:
// 实现自己版本的拷贝数组
public static int[] myCopyOf(int[] arr) {
int[] ret = new int[arr.length];
for (int i = 0; i < arr.length; ++i) {
ret[i] = arr[i];
}
return ret;
}
3. 求数组中元素的平均值
// 求数组中元素的平均值
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7};
System.out.println(avg(arr));
}
public static double avg(int[] arr) {
int sum = 0;
for (int x : arr) {
sum += x;
}
return (double)sum / (double)arr.length;
}
![image.png](https://img-blog.csdnimg.cn/img_convert/47bea6df189bd9964cdb7de8cfc0ff66.png#clientId=uda65bb8b-df7d-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=66&id=u7bea43c5&margin=[object Object]&name=image.png&originHeight=67&originWidth=276&originalType=binary&ratio=1&rotation=0&showTitle=false&size=2238&status=done&style=none&taskId=uab16f297-c98d-40c5-b862-7f612247d0a&title=&width=270.99998474121094)
4. 查找数组中指定元素(顺序查找)
// 查找数组中指定元素(顺序查找)
public static int find(int[] arr, int data) {
for (int i = 0; i < arr.length; ++i) {
if (arr[i] == data) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7};
System.out.println(find(arr,3));
System.out.println(find(arr,0));
}
![image.png](https://img-blog.csdnimg.cn/img_convert/d90bcc5c75d26135a6268304e30d2376.png#clientId=uda65bb8b-df7d-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=121&id=ud57f25ed&margin=[object Object]&name=image.png&originHeight=96&originWidth=217&originalType=binary&ratio=1&rotation=0&showTitle=false&size=1530&status=done&style=none&taskId=ud4353f75-c73c-417c-970c-3d862cf4c36&title=&width=272.49159240722656)
5. 查找数组中指定元素(二分查找)
// 二分查找
public static int binarySearch(int[] arr, int data) {
int left = 0;
int right = arr.length-1;
while (left <= right) {
int mid = left + (right >> 1);
if (arr[mid] > data) { //到左半区间找
right = mid - 1;
} else if (arr[mid] < data) { // 到右半区间找
left = mid + 1;
} else {
return mid; //找到了
}
}
return -1; //代表没找到
}
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6};
System.out.println(binarySearch(arr,6));
}
![image.png](https://img-blog.csdnimg.cn/img_convert/9d701a8bb2b85b167496c24929893b19.png#clientId=uda65bb8b-df7d-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=110&id=u020479fb&margin=[object Object]&name=image.png&originHeight=129&originWidth=320&originalType=binary&ratio=1&rotation=0&showTitle=false&size=8541&status=done&style=none&taskId=ue4577d4d-b244-407c-b8e0-b522e9ce4f5&title=&width=272.99578857421875)
6. 冒泡排序
// 冒泡排序
public static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length; ++i) {
// 每一趟排序后,最大值都会跑到数组的最末端
for (int j = 1; j < arr.length - i; ++j) {
if (arr[j-1] > arr[j]) {
int tmp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = tmp;
}
}
}
}
public static void main(String[] args) {
int[] arr = {9,5,2,7};
bubbleSort(arr);
System.out.println(Arrays.toString(arr));
}
![image.png](https://img-blog.csdnimg.cn/img_convert/2c4bfe0a8215e081012f771fedb12d41.png#clientId=uda65bb8b-df7d-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=92&id=u5408af65&margin=[object Object]&name=image.png&originHeight=137&originWidth=596&originalType=binary&ratio=1&rotation=0&showTitle=false&size=13858&status=done&style=none&taskId=u85aa9498-66bc-4363-84c7-9df533b3a21&title=&width=398.99578857421875)
冒泡排序性能较低,java中内置了更高效的排序算法:
public static void main(String[] args) {
//java中更高效的排序算法
int[] arr = {9,5,2,7};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
7. 数组逆序
// 数组逆序
public static void reverse(int[] arr) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
int tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
++left;
--right;
}
}
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
reverse(arr);
System.out.println(Arrays.toString(arr));
}
![image.png](https://img-blog.csdnimg.cn/img_convert/1f9f39d607025c2a59c3ab1a328cb918.png#clientId=uda65bb8b-df7d-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=129&id=u7f621402&margin=[object Object]&name=image.png&originHeight=185&originWidth=697&originalType=binary&ratio=1&rotation=0&showTitle=false&size=15490&status=done&style=none&taskId=ucc0c9605-4c75-423d-ac79-b4e9b7ede87&title=&width=487.4915771484375)
二维数组
基本语法:数据类型[][] 数组名称 = new 数据类型 [行数][列数] {初始化数据};
代码示例:
// 二维数组
public static void main(String[] args) {
int[][] arr = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12}
};
for (int row = 0; row < arr.length; ++row) {
for (int col = 0; col < arr[row].length; ++col) {
System.out.print(arr[row][col] + "\t");
}
System.out.println();
}
}
![image.png](https://img-blog.csdnimg.cn/img_convert/55d07a1a18bd1bdecba034db3ba6539d.png#clientId=uda65bb8b-df7d-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=143&id=u4dae9b41&margin=[object Object]&name=image.png&originHeight=192&originWidth=574&originalType=binary&ratio=1&rotation=0&showTitle=false&size=16598&status=done&style=none&taskId=u0ccb650c-51ee-4a61-a676-0d1283727e9&title=&width=428.9915771484375)
![image.png](https://img-blog.csdnimg.cn/img_convert/186e0ca982a1e2e389b37f28d47c73ff.png#clientId=u46c63b6e-569d-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=387&id=u692580f7&margin=[object Object]&name=image.png&originHeight=599&originWidth=888&originalType=binary&ratio=1&rotation=0&showTitle=false&size=63123&status=done&style=none&taskId=u0f7ba88b-b199-4d90-b8fb-06904662e7b&title=&width=573.9999694824219)
打印二维数组的方法Arrays.deeptoString();
int[][] arr = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12}
};
// 打印二维数组的方法
System.out.println(Arrays.deepToString(arr));
![image.png](https://img-blog.csdnimg.cn/img_convert/bf861efb926730edc3119e78bc4d4baa.png#clientId=u46c63b6e-569d-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=57&id=ub3564c3e&margin=[object Object]&name=image.png&originHeight=70&originWidth=636&originalType=binary&ratio=1&rotation=0&showTitle=false&size=11211&status=done&style=none&taskId=u18929e8a-224c-48b2-9625-355d6376d78&title=&width=517.9999694824219)
不规则的二维数组:
// 不规则的二维数组
public static void main(String[] args) {
int[][] array = new int[2][];
// 注意:C语言 是可以指定列,行可以自动推导
// Java中,行必须指定,列不可以自动推导
array[0] = new int[3]; // 第一行有三列
// 也可以进行初始化:array[0] = new int[]{1,2,3};
array[1] = new int[2]; // 第二行有两列
}
![image.png](https://img-blog.csdnimg.cn/img_convert/ab35fba3e10d50560b108420386e7da6.png#clientId=u46c63b6e-569d-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=222&id=ue4d0329c&margin=[object Object]&name=image.png&originHeight=318&originWidth=742&originalType=binary&ratio=1&rotation=0&showTitle=false&size=29279&status=done&style=none&taskId=ufb7527a2-547b-45c9-8232-362a7f0f14c&title=&width=517.9915771484375)
6. 常量
6.1 字面值常量
![image.png](https://img-blog.csdnimg.cn/img_convert/677d8a6e843ea031b5d4be10e5e2c0a2.png#clientId=u76f3e23f-5532-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=207&id=uef38ebd3&margin=[object Object]&name=image.png&originHeight=291&originWidth=796&originalType=binary&ratio=1&rotation=0&showTitle=false&size=80785&status=done&style=none&taskId=u7d11eb60-91cc-4ad8-9c95-760cadf49a6&title=&width=565.9915771484375)
6.2 final 关键字修饰的常量
// 常量只能被初始化一次,且使用的时候一定要记得初始化
public static void main (String[] args) {
// 定义常量,建议名称全大写
final int MAXNUM = 10;
System.out.println(MAXNUM);
}
常量不能在程序运行过程中发生修改。
# 7. int 和 String 之间的相互转换 ## 7.1 int 转成 String ```java int num = 10; //方法1: String str1 = num + ""; //方法2: String str2 = String.valueOf(num); ``` ## 7.2 String 转成 int ```java String str = "100"; int num = Integer.parseInt(str);
//如果字符串包含除数字外别的东西,则报错
Stringstr2 = “100abc”;
int num2 = Integer.parseInt(str2); //报错
<a name="uvx9U"></a>
# 8. 运算符
这里没什么好说的,跟C语言的差不多。此处只提及Java与C语言不同的部分。
- % 不仅可以对整型取模,还可以对double类型取模,但是没有意义,一般对整型取模。
```java
System.out.println(11.5 % 2.0);
//运行结果
1.5
- 自增或自减运算符
int i = 10;
i = i++;
//输出10,这个跟C语言不同
System.out.println(i);
详细原因以后再探讨。
9. 程序逻辑控制
9.1 switch 语句
switch 语法基本和C语言一致,下面给出示例:
int day = 1;
switch(day) {
case 1:
System.out.println("1");
break;
case 2:
System.out.println("2");
break;
default:
System.out.println("输入有误");
break;
}
【注意事项】:
- 多个case后的常量值不可以重复。
- switch的括号内只能是以下类型的表达式:
- 基本类型:byte,char,short,int,char,注意不能是long,float,double,boolean
- 引用类型:String常量串,枚举类型
错误示例:
![image.png](https://img-blog.csdnimg.cn/img_convert/9a36c76cda948feada5cf1684717cdc0.png#clientId=u76f3e23f-5532-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=301&id=u59d4cbfb&margin=[object Object]&name=image.png&originHeight=364&originWidth=648&originalType=binary&ratio=1&rotation=0&showTitle=false&size=26306&status=done&style=none&taskId=ud95e8846-15f1-4ae8-a424-eb81f4f52e3&title=&width=534.9999694824219)
![image.png](https://img-blog.csdnimg.cn/img_convert/12f2e5d69ca6171d0ff084bee7b7c9ce.png#clientId=u76f3e23f-5532-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=92&id=ubf035067&margin=[object Object]&name=image.png&originHeight=124&originWidth=788&originalType=binary&ratio=1&rotation=0&showTitle=false&size=21179&status=done&style=none&taskId=uc26aa318-c4ca-4a6b-aac7-cdb8aec8665&title=&width=581.9957885742188)
9.2 补充
像for``while
的循环条件表达式只能为**布尔类型的,**像下面的代码就是错误的:
if (1) {
}
while (1) {
}
10. 方法的概念和使用
方法简而言之就是一个功能函数
10.1 方法定义
语法格式:
修饰符 返回值类型 方法名称(参数列表) {
方法体代码;
返回值;
}
【注意事项】:
- 修饰符:现阶段直接使用
public static
固定搭配。
原因:因为当前所有的方法 写完之后 会在main方法中调用,因为main方法是public static的。静态的main函数里面只能调用静态的方法。
- 方法名字:采用小驼峰命名。
- 在Java中,方法必须写在类当中。
- 在Java中,方法不能嵌套定义。
- 在Java中,没有方法声明一说,你的方法定义在main的上面或下面都无所谓。
## 10.2 实参和形参的关系 **在Java中,实参的值永远都是拷贝到形参中,形参和实参本质是两个实体。(这点跟C语言不一样,C语言可以传递地址,来改变实参的值,但是Java只能改变形参的值)。**
解决方法:传引用类型的参数(例如数组)
示例:
public class Demo {
public static void main(String[] args) {
int[] arr = {10,20};
swap(arr);
System.out.println("arr[0] = " + arr[0] + " arr[1] = " + arr[1]);
}
public static void swap(int[] arr) {
int tmp = arr[0];
arr[0] = arr[1];
arr[1] = tmp;
}
}
//运行结果
arr[0] = 20 arr[1] = 10
# 11. 方法的重载 **重载即是“一词多义”的意思。**
**在Java中,如果多个方法的名字相同,参数列表不同,则称该几种方法被重载了。**
示例:
public class Demo2 {
// 方法的重载
public static int maxNum(int a, int b) {
return a > b ? a : b;
}
public static double maxNum(double a, double b) {
return a > b ? a : b;
}
public static int maxNumOf3(int a, int b, int c) {
return maxNum(maxNum(a,b),c);
}
public static double maxNumOf3(double a, double b, double c) {
return maxNum(maxNum(a,b),c);
}
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 40;
System.out.println(maxNumOf3(a,b,c));
double d1 = 2.134;
double d2 = -1.739;
double d3 = 9.087;
System.out.println(maxNumOf3(d1,d2,d3));
}
}
【注意事项】:
- 方法名必须相同。
- 参数列表必须不同(参数的个数不同、参数的类型不同、类型的次序必须不同)
- 与返回值类型是否相同无关。
示例:
public class Demo2 {
// 方法的重载
public static int maxNum(int a, int b) {
return a > b ? a : b;
}
//仅仅是返回类型不同,无法构成重载
public static double maxNum(int a, int b) {
return a > b ? a : b;
}
public static void main(String[] args) {
}
}
- 编译器在编译代码时,会对实参类型进行推演,根据推演的结果来确定调用哪个方法。
# 12. 方法签名 在同一个作用域中不能定义两个相同名称的标识符。如,方法中不能定义两个名字一样的变量,那**为什么类中就可以定义方法名相同的方法呢?**
方法签名:经过编译器编译修改之后方法的最终的名字。具体方式:方法全路径名+参数列表+返回值类型,构成方法的完整的名字。
(类似于C++中函数重载中,生成的修饰名会根据函数参数的不同而不同)