Java基础语法

Java语法快速入门

1.1 程序的入口

# java程序入口为类中的static的viod的main函数,参数固定为字符串数组
public static void main(String[] args) {
     System.out.println("hello world");
}

1.2 文件名

# 一个文件中最多只能有一个public类 且 【文件名】必须和【public类名一致】
# 文件中可以有多个类,但是文件名与public类名一致,其它类不能用public修饰
# 如果文件中有多个类 且 无public类,文件名可以是任意类名
public class Main {
    public static void main(String[] args){
        System.out.println("hello world");
        Demo.add(3,4);
    }
}
​
class Demo{
    public static void add(int a,int b){
        System.out.println(a+b);
    }
}

1.3 类规范

###1 类名规范
类名首字母大写且驼峰式命名
例如:Hello、UserInfo、PersonApplication
 
### 2 类修饰符(写在类前面的修饰符)
public、default(不写)

### 3 类中成员(变量,方法)修饰符:
public、private、protected、default(不写)
 
 
### 4 静态成员方法(static修饰)
无序实例化就可以指定调用
 
### 5 void表示方法没有返回值
public class Main {
    public static String name = "彭于晏";
​
    public static void main(String[] args) {
        // 1 调用其他类的静态方法---》类似于python中的类方法
        Demo.add(3, 4);
        // 2 调用类自己的静态成员变量
        System.out.println(name);
        // 3 调用其他类公开的成员变量
        System.out.println(Demo.age);
        // 4 调用其他类的对象方法,必须实例化才能调用
        Demo d = new Demo();
        d.test();
    }
}
​
class Demo {
    private static String name = "张三"; // 私有变量,只能当前类中使用
    public static int age = 19; // 公有变量,所有类都可以使用
public static void add(int a, int b) {
        System.out.println(a + b);
        System.out.println(name);
    }
​
    public void test() {
        System.out.println("我是test");
    }
}

2 基本语法

2.1 注释

## 1 单行注释
以双斜杠“//”标识,只能注释一行内容,用在注释信息内容少的地方
快捷键:【注释 ctrl+/ 】  【 取消注释 ctrl+/ 】
​
### 2 多行注释
包含在“/*”和“*/”之间,能注释很多行的内容,可以换行
快捷键:【注释 ctrl+shift+/ 】 【取消注释 ctrl+shift+\ 】
​
### 3 文档注释
包含在“/**”和“*/”之间,也能注释多行内容,一般用在类、方法和变量上面,用来描述其作用。注释后,鼠标放在类和变量上面会自动显示出我们注释的内容
  /**
   * 
   * @param a
   * @param b
   */
  public static void add(int a, int b) {
      System.out.println(a + b);
      System.out.println(name);
  }

2.2 变量和常量

// 变量
String name="彭于晏";
name = "李易峰";

int age = 19;
age = 20;
System.out.println(name);
System.out.println(age);

// 常量
final String hobby="足球";
hobby="篮球" // 不允许修改
System.out.println(hobby);

// final 修饰方法
父类中的 final 方法可以被子类继承,但是不能被子类重写。
声明 final 方法的主要目的是防止该方法的内容被修改
 
 
//final 修饰类
final 类不能被继承,没有类能够继承 final 类的任何特性

2.3 输入输出

// 输出
System.out.println("hello");
System.out.print("world");
System.out.printf("变量值是:%s%n",name);

// 输入(一般不用)
import java.util.Scanner;
public class Hello {
   public static void main(String[] args) {
       System.out.print("请输入您的名字:");
       Scanner input = new Scanner(System.in);
       String InputName = input.nextLine();
       System.out.printf("您输入的名字是:%s",InputName);

  }
}

2.4 条件语句

import java.util.Scanner;
​
public class Demo02 {
    public static void main(String[] args) {
        System.out.println("请输入您的分数:");
        Scanner scanner = new Scanner(System.in);
        int score = Integer.valueOf(scanner.nextLine()); // 强制类型转换为int
if (score >= 90 && score <= 100) {
            System.out.println("优秀");
        } else if (score >= 70 && score < 90) {
            System.out.println("良好");
        } else if (score >= 60 && score < 70) {
            System.out.println("及格");
        } else {
            System.out.println("不及格");
        }
    }
}
import java.util.Scanner;
​
public class Demo02 {
    public static void main(String[] args) {
        System.out.println("请输入您的分数:");
        Scanner scanner = new Scanner(System.in);
        int score = Integer.valueOf(scanner.nextLine()); // 强制类型转换为int
        switch (score){
            case 99:
                System.out.println("恭喜您99分");
                break;
            case 88:
                System.out.println("恭喜您88分");
                break;
            default:
                System.out.println("不知道多少分");
​
        }
    }
}

2.5 循环语句

while循环

// 打印0--9
public class Demo03 {
    public static void main(String[] args) {
        int count = 0;
        while (count < 10) {
            System.out.println(count);
            count += 1;
        }
    }
}

do while循环(至少执行1次)

public class Demo03 {
    public static void main(String[] args) {
        int count = 0;
        do{
            System.out.println(count);
            count++;
​
        }while (count<10);
    }
}

for循环

public class Demo03 {
    public static void main(String[] args) {
        for(int i=0;i<10;i++){
            System.out.println(i);
        }
    }
}
 

// 循环数组
public class Demo03 {
    public static void main(String[] args) {
        String[] nameList = {"李易峰", "刘亦菲", "彭于晏", "古天乐"};
        for(int i=0;i<nameList.length;i++){
            System.out.println(nameList[i]);
        }
    }
}

3 数据类型

3.1 字节类型

// byte,字节        【1字节】表示范围:-128 ~ 127 即:`-2^7 ~ 2^7 -1  `  
// 单纯的字节类型,一般就是用来表示数字
​
​
​
public class Demo04 {
    public static void main(String[] args) {
        byte b='A';
        System.out.println(b); // 10 进制显示
        System.out.println(Integer.toBinaryString(b));  // 2进制显示
        System.out.println(Integer.toHexString(b)); // 16进制显示
byte a=98;
        System.out.println(a); // 98
        System.out.println(Integer.toBinaryString(a)); //2进制显示
        System.out.println(Integer.toHexString(a)); // 16进制显示
    }
}
​
// 注意:两个字节相加得到的是int类型,除非强制类型转换成byte类型
byte b=65;
byte a=66;
int c=a+b;
byte d=(byte)(a+b);  // 因为有可能加超过byte的范围
System.out.println(c);
System.out.println(d);

python中字符串与字节

##### python中字符串与字节
v1 = '彭于晏'
v2 = v1.encode('utf-8')
print(v2)  # b'\xe5\xbd\xad\xe4\xba\x8e\xe6\x99\x8f'   16进制表示
v3 = v1.encode('GBK')
print(v3)  # b'\xc5\xed\xd3\xda\xea\xcc'  16进制表示
# 转换为10进制
v3 = [item for item in v2]
print(v3)  # [229, 189, 173, 228, 186, 142, 230, 153, 143]
# 转换为二进制
v4 = [bin(item) for item in v2]
print(v4)  # ['0b11100101', '0b10111101', '0b10101101', '0b11100100', '0b10111010', '0b10001110', '0b11100110', '0b10011001', '0b10001111']
# 转换为16进制
v5 = [hex(item) for item in v2]
print(v5) # ['0xe5', '0xbd', '0xad', '0xe4', '0xba', '0x8e', '0xe6', '0x99', '0x8f']

java中字符串与字节数组

import java.util.Arrays;
​
public class Demo04 {
    public static void main(String[] args) throws Exception {
        String v1 = "彭于晏";
        byte[] v2 = v1.getBytes(); // 默认utf-8
        System.out.println(v2);  // [B@1540e19d  对象形式显示
        System.out.println(Arrays.toString(v2));  // [-27, -67, -83, -28, -70, -114, -26, -103, -113]
// GBK
        byte[] v22 = v1.getBytes("GBK"); // 默认utf-8
        System.out.println(v22);  //[B@677327b6
        System.out.println(Arrays.toString(v22)); //[-59, -19, -45, -38, -22, -52]
​
    }
}

字节有无符号

# 字节有无符号
   Python字节无符号(不含负数): 0 ~ 255
       0 1 2 3 4 5 ... 127  128  129  130 ... 255
​
   Java字节是有符号(含有负数):-128 ~ 127
       0 1 2  3 4 5 ...127  -128 -127 - 126 -125 .... -2  -1
    
# python:彭于晏
[229, 189, 173, 228, 186, 142, 230, 153, 143]
# java:彭于晏
[-27, -67, -83, -28, -70, -114, -26, -103, -113]
​
​
### 编写一个java字节数组转换为python的字符串代码
    逻辑是:数字大于0,不操作,小于0,加上256
​
v1 = [-27, -67, -83, -28, -70, -114, -26, -103, -113]
def java_arr_to_python_str(v1):
    num_list = bytearray()
    for i in v1:
        if i < 0:
            i = i + 256
        num_list.append(i)
    return num_list.decode('utf-8')
​
​
if __name__ == '__main__':
    print(java_arr_to_python_str(v1))

3.2 整数类型

// byte 带符号字节型    8位    -128 ~ 127
// short    带符号字节型  16位 -32768 ~ 32767
// int  带符号字节型    32位   -231    -2147483648 ~ 2147483647
// long 带符号字节型    64位   -263    -9223372036854775808 ~ 9223372036854775807
byte v1 = 32;
short v2 = 10000;
int v3 = 22221331;
long v4 = 554534353424L;
System.out.println(v1);
System.out.println(v2);
System.out.println(v3);
System.out.println(v4);

3.3 小数类型

//float   单精度   32位   
//double    双精度 64位 
float f=1.123456789012f;
System.out.println(f);
double d=1.12345678901234567890d;
System.out.println(d);

3.4 字符类型

char v1 = 'x';
char v2 = '贾';
String v3 = "彭于晏";

3.5 字符串类型

String v1 = "彭于晏";
String v2 = new String("彭于晏");
​
String v3 = new String(new byte[]{-27, -67, -83, -28, -70, -114, -26, -103, -113});
String v9 = new String(new byte[]{-59, -19, -45, -38, -22, -52},"GBK");
String v4 = new String(new char[]{'彭', '于', '晏'});
​
System.out.println(v1);
System.out.println(v2);
System.out.println(v3);
System.out.println(v4);

字符串常用方法

String origin = "hello world 中国";
​
  // 1 取指定位置字符
  char v1 = origin.charAt(13); // 取出字符   国
  System.out.println(v1);
​
  // 2 循环输出每个字符
  int len = origin.length();  // 字符串长度
  for (int i = 0; i < len; i++) {
      char item = origin.charAt(i);
      System.out.println(item);
  }
  // 3 去除前后空白
  String v2 = origin.trim(); // 去除空白
  System.out.println(v2);
  // 4 转大写
  String v3 = origin.toLowerCase(); // 小写
  System.out.println(v3);
  String v4 = origin.toUpperCase(); // 大写
  System.out.println(v4);
  String[] v5 = origin.split(" "); // 按空格分隔
  System.out.println(v5);
  String v6 = origin.replace("h", "l"); // 把h替换为l
  System.out.println(v6);
  String v7 = origin.substring(2, 6);  // 子字符串=切片 [2:6]
  System.out.println(v7);
  boolean v8 = origin.equals("hello world"); // 比较字符串是否相等
  System.out.println(v8);
  boolean v9 = origin.contains("中"); // 字符串是否包含
  System.out.println(v9);
  boolean v10 = origin.startsWith("a"); // 字符串是否以xx开头
  System.out.println(v10);
  String v11 = origin.concat("哈哈哈"); //在字符串末尾追加
  System.out.println(v11);

 

字节数组和字符串相互转换

//1  字符串转字节数组
byte[] b = v4.getBytes(); // 默认utf8形式
System.out.println(b); // 输出对象形式,看不到字节数组
System.out.println(Arrays.toString(b));
​
​
//        try {
//            byte[] b1 = v4.getBytes("GBK"); // 'GBK'形式,需要捕获异常
//        } catch (Exception e) {
//
//        }
byte[] b1 = v4.getBytes("GBK"); // 'GBK'形式,需要捕获异常,或在方法上  throws Exception
System.out.println(Arrays.toString(b1));
​
​
// 2 字节数组转字符串
String v8 = new String(new byte[]{-27, -67, -83, -28, -70, -114, -26, -103, -113});
String v9 = new String(new byte[]{-59, -19, -45, -38, -22, -52},"GBK");
System.out.println(v8);
System.out.println(v9);

字符数组和字符串相互转换

// 1 字符数组转字符串
  char[] c=new char[]{'彭','于','晏'};
  String v1 = new String(c);
  System.out.println(v1);
​
  // 2 字符串串转字符数组
  String str1 = "彭于晏";
  char[] c=str1.toCharArray();
  System.out.println(c.length);
  System.out.println(c[0]);

字符串拼接

### 1 直接相加,效率低
String s="hello"+"world"+"中国";
​
### 2 使用StringBuilder或StringBuffer拼接
StringBuilder sb = new StringBuilder();  // StringBuffer线程安全
//StringBuffer sb = new StringBuffer();  // StringBuffer线程安全
sb.append("hello");
sb.append(" ");
sb.append("world");
sb.append(" ");
sb.append("中");
sb.append("国");
System.out.println(sb.toString());

3.5 数组类型

// 存放固定长度的元素。 容器类型,放多个元素,但是 固定长度,存储类型固定
int[] numArray = new int[3];
numArray[0] = 123;
//        numArray[1] = "xxx";  // 不能放字符串类型
numArray[2] = 99;
System.out.println(numArray);  // 打印出对象形式
System.out.println(Arrays.toString(numArray));
​
​
String[] names = new String[]{"彭于晏", "刘亦菲", "迪丽热巴"};
System.out.println(Arrays.toString(names));
​
String[] nameArray = {"彭于晏", "刘亦菲", "迪丽热巴"};
System.out.println(Arrays.toString(nameArray));

3.6 boolean类型

boolean b=true;
b=false;
System.out.println(b);
posted @ 2023-07-01 10:02  小青年て  阅读(70)  评论(0)    收藏  举报