具体语法查看菜鸟教程,大部分基础语法与C是相差不多的(像循环、条件、运算)。
https://www.runoob.com/java/java-basic-syntax.html
目录
1、运算
byte short char int四个运算的时候,都会将自己提升为int类型后,在进行运算。当是比int类型大的类型做运算,就会自动转换成它们中最大类型那个。
Java的八种基本类型:(按字节来分)
boolean 布尔型 1个字节 8bit(8位)
byte 字节类型 1个字节
char 字符类型 2个字节
short 短整型 2个字节
int 整型 4个字节
float 浮点型(单精度)4个字节
long 长整型 8个字节
double 双精度类型 8个字节
Java中默认的整数类型是int,如果要定义为long ,则要在数值后加上L或者l
默认的浮点型是双精度浮点,如果要定义float,则要在数值后面加上f或者F
一个字节等于8位,1个字节等于256个数。2^8
一个英文字母或者阿拉伯数字占一个字节
一个汉字占2个字节
还是有一些字符定义和C语言是一样的,例如int
2、产生随机数
这里跟C的随机数差不多。
Random r =new Random();
int num = r.nextInt(10);
System.out.println(num);
3、数组
(1)数组定义格式 :
- 数据类型[] 数组名;
- 示例: int[] arr;
- 示例: double[] arr;
- 数据类型 数组名[];
- 示例: int arr[];
- 示例: double arr[];
(2)数组初始化 :
动态初始化
int[] arr = new int[5];
静态初始化
int[] arr = new int[]{123,23,45};
int[] arr = {123,23,45};//简化格式
int arr[] = {123,23,45};//与C一样了,这样写也可以
4、方法重载
这找个地方与C不同,C虽然存在虚函数(weak)重新定义(函数名相同),但这里java允许函数名相同,来根据参数的不同,调用时候执行不同的函数(方法)。
方法重载规则
- 在同一个类中 , 方法名相同 , 参数列表不同 , 与返回值无关
- 参数列表不同 ( 个数不同, 类型不同, 顺序不同 )
public class MethodTest {
public static void main(String[] args) {
//调用方法
System.out.println(compare(10, 20));
System.out.println(compare((byte) 10, (byte) 20));
System.out.println(compare((short) 10, (short) 20));
System.out.println(compare(10L, 20L));
}
//int
public static boolean compare(int a, int b) {
System.out.println("int");
return a == b;
}
//byte
public static boolean compare(byte a, byte b) {
System.out.println("byte");
return a == b;
}
//short
public static boolean compare(short a, short b) {
System.out.println("short");
return a == b;
}
//long
public static boolean compare(long a, long b) {
System.out.println("long");
return a == b;
}
}
5、异常处理
捕获异常try catch
// 文件名 : ExcepTest.java
import java.io.*;
public class ExcepTest{
public static void main(String args[]){
try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
6、修饰符
public : 对所有类可见。使用对象:类、接口、变量、方法;
private : 在同一类内可见。使用对象:变量、方法。 注意:不能修饰类(外部类);
protected : 对同一包内的类和所有子类可见。使用对象:变量、方法。 注意:不能修饰类(外部类)。
7、byte[]转换为String
String s = “fs123fdsa”;//String变量
byte b[] = s.getBytes();//String转换为byte[]
String t = new String(b);//bytep[]转换为String