- 基本代码结构
public class FirstSample
{
public static void main(String [] args)
{
System.out.println("We will not use 'Hello , World!'");
}
}
public:访问修饰符,控制其他程序对这段程序的访问级别
FirstSample:类名,不可用java保留字做类名
文件名应该与public类的类名相同
java虚拟机总是从main方法处开始执行,所以源类中必须有main方法
-
从java10以后,不需要声明变量的类型,可以用var关键词代替
-
java变量的声明与定义不可分离,这一点与c++不同
c++中可能会出现这样的声明extern int i;
-
java中使用final表示常量,常量一般全部大写。我们可以用static final设置类常量,那么类中的多个方法就可以使用。如果不声明为static,那么在类中声明但在方法外的常量,该方法就不能使用。
public class Constants2 { public static final double CM_PER_INCH = 2.54; public static void main(String[] args) { double paperWidth = 8.5; double paperHeight = 11; System.out.println("Paper size in centimeters: " + paperWidth * CM_PER_INCH + " by " + paperHeight * CM_PER_INCH); } }
-
String的各种方法
-
静态方法与静态导入
-
大数BigInter与BigDecimal
-
数组的声明(注意与C++的相区别)
int [] a; int [] a=new int [100]; var a=new int [100]; int [] a=new int [n]; //创建数组并初始化 int [] smallPrimes={2,3,5,7,11}; //下面的smallPrimes已经指向了一个新的对象 smallPrimes=new int []{17,21,28,29}; //数组长度的获取 a.length double [][] balances; balances=new double[n][m]; int[][] magicSquare = { {16, 3, 2, 13}, {5, 10, 11, 8}, {9, 6, 7, 12}, {4, 15, 14, 1} }; //让二维数组的两行之间交换 double[] temp = balances[i]; balances[i] = balances[i + 1]; balances[i + 1] = temp;
注意错误的数组赋值方式
int [] smallPrimes={2,3,5,7,11}; smallPrimes={17,21,28,29};
数组长度不要求是常量;
一旦创建了数组,就不能改变它的长度
数组列表(array list)可以扩展其大小,可以尝试这种数据结构
for each循环处理集合等容器结构循环的便利性。
数组拷贝:两个数组变量引用同一个数组
java中的数组没有指针运算,不能通过a+1获得数组中的下一个元素
数组排序Arrays.sort()
多维数组
for each循环处理二维数组的每一个元素for(double[] row:a) for(double value:row)
不规则数组的分配(java多维数组自身的构造方式),比如说我们最常用的杨辉三角
int[][] odds = new int[NMAX + 1][];
for (int n = 0; n <= NMAX; n++)
odds[n] = new int[n + 1];