基础篇-java开发

开局必知

  1.变量

  • 在java中,以{}为作用域,所以就存在成员变量和局部变量之说
  • 由于java是强类型语言,所以在申明变量的时候,必须指定类型
  • java里,一个变量有声明过程和初始化过程(也就是赋值过程),当变量要参数运算时,就必须初始化变量
public class HelloWorld {

    // 声明int型成员变量
    int y;

    public static void main(String[] args) {

        // 声明int型局部变量
        int x;
        // 声明float型变量并赋值
        float f = 4.5f;

        x = 10;
        System.out.println("x = " + x);// 编译错误,局部变量 x未初始化
        System.out.println("f = " + f);

        if (f < 10) {
            // 声明型局部变量
            int m = 5;
        }
        //System.out.println(m);
    }

}
View Code

  2.常量

  • 定义常量的关键词为final
  • 存在静态常量和和成员常量、局部常量之说,取决于所在的位置
  • 其中静态常量还要加上public static
public class HelloWorld {
    
    // 静态常量,替代const
    public static final double PI = 3.14;
    
    // 声明成员常量
    final int y = 10;
    
    public static void main(String[] args) {
        // 声明局部常量
        final double x = 3.3;
        
    }

}
View Code

  3.命名规范

  不要忽视了命名规范的重要性,它是一个团队互相协作的基石,也是对你以后进行代码维护和代码重构做到事半功倍

  • java中命名一般采用驼峰命名法,其中又分大驼峰命名法(每个单词的首字母大写)和小驼峰命名法(第一个单词的首字母不大写,其他的单词首字母大写)
  • 包名:全部小写字母,中间可以由点分隔开,作为命名空间,包名应该具有唯一性,推荐采用公司或者组织域名的倒置,如:com.apple.quicktime.v2,但是java核心库包名不采用域名的倒置命名,java.awt.event

  • 类和接口名:采用大驼峰法
  • 文件名:采用大驼峰法
  • 变量和方法名:小驼峰法
  • 常量名:全大写,多个单词用下划线隔开

  4.代码排版

  漂亮的排版,可以增加代码的易读性,维护代码时也比较方便,代码排版包括空行,空格,断行和锁紧等内容

空行:

  类声明和接口声明之间保留两个空行

  两个方法之间保留一个空行

  方法的第一条语句之前保留一个空行

  代码注释前(尾端注释外),保留一个空行

  一个方法的两个逻辑之间

空格:

  赋值符号 = 前后各一个空格

  所有的二元运算符都应该使用空格与操作数分开

  一元操作符:负号-,自增++,自减--等,和操作数没有空格

  小左括号"("之后,小右括号")"之前不应该有空格,  a = (a + b) / (c + d)

  大左括号之前有一个空格

  关键词之后跟着紧跟小左括号,关键词后有一空格

缩进

  在方法、lambda、控制语句等包含大括号"{}"的代码中,代码块的内容相对于首行缩进一个级别(4个空格)

  如果是if语句中条件表达式的断行,那么新的一行应该相对于上一行缩进两个级别(8个空格),再往后的断行要与第一次的断行对齐

断行

  在一个逗号后面断开

  在一个操作符前面断开,要选择高级别的运算符

  5.注释规范

  java中注释的语法有三种:单行注释(//),多行注释(/*...*/)和文档注释(/**..*/)

  • 文件注释
  • 文档注释

  @author  说明类或接口的作者

  @deprecated  说明类、接口或者成员已经废弃

  @param  说明方法参数

  @return  说明返回值

  @see  参考另一个主题的链接

  @exception  说明方法所抛出的异常类

  @throws  同@exception标签

  @version  类或接口的版本

  • 代码注释
  • 使用地标注释

  TODO:说明此处有待处理的任务,或代码没有编写完成

  FIXME:说明此处代码是错误的,需要修正

  XXX:说明此处代码虽然实现了功能,但是实现的方法有待商榷,希望将来能改进

  6.其他规范

  • 在声明变量或常量时推荐一行一个声明
  • 每行至多包含一条语句
  • 不推荐使用 在if for等控制语句下只有一行代码省去大括号的做法

数据类型 

  1.整型类型

public class HelloWorld {

	public static void main(String[] args) {
		// 声明整数变量
		// 输出一个默认整数常量
		System.out.println("默认整数常量	=  " + 16);
		byte a = 16;
		short b = 16;
		int c = 16;
		long d = 16L;
		long e = 16l;
		
		System.out.println("byte整数 		=  " + a);
		System.out.println("short整数		=  " + b);
		System.out.println("int整数		=  " + c);
		System.out.println("long整数 		=  " + d);
		System.out.println("long整数 		=  " + e);
		
	}
}

  

  2.浮点类型

public class HelloWorld {

	public static void main(String[] args) {
		// 声明浮点数
		// 输出一个默认浮点常量
		System.out.println("默认浮点常量	=  " + 360.66);
		float myMoney = 360.66f;
		double yourMoney = 360.66;
		final double PI = 3.14159d;
		
		System.out.println("float整数 	=  " + myMoney);
		System.out.println("double整数	=  " + yourMoney);
		System.out.println("PI		=  " + PI);
		
	}
}

  

  3.数字表达方式

public class HelloWorld {

	public static void main(String[] args) {

		// 进制表示方式
		int decimalInt = 28;
		int binaryInt1 = 0b11100;
		int binaryInt2 = 0B11100;
		int octalInt = 034;
		int hexadecimalInt1 = 0x1C;
		int hexadecimalInt2 = 0X1C;

		System.out.println("十进制表示 		=  " + decimalInt);
		System.out.println("二进制表示 		=  " + binaryInt1);
		System.out.println("八进制表示 		=  " + octalInt);
		System.out.println("十六进制表示	=  " + hexadecimalInt1);

		// 指数表示方式
		double myMoney = 3.36e2;
		double interestRate = 1.56e-2;

	}
}

  

  4.字符类型

public class HelloWorld {

	public static void main(String[] args) {

		char c1 = 'A';
		char c2 = '\u0041';
		char c3 = '花';

		System.out.println(c1);
		System.out.println(c2);
		System.out.println(c3);
		
		//转义符
		//在Hello和World插入制表符
		String specialCharTab1 = "Hello\tWorld.";
		//在Hello和World插入制表符,制表符采用Unicode编码\u0009表示
		String specialCharTab2 = "Hello\u0009World.";
		//在Hello和World插入换行符
		String specialCharNewLine = "Hello\nWorld.";
		//在Hello和World插入回车符
		String specialCharReturn = "Hello\rWorld.";
		//在Hello和World插入双引号
		String specialCharQuotationMark = "Hello\"World\".";
		//在Hello和World插入单引号
		String specialCharApostrophe = "Hello\'World\'.";
		//在Hello和World插入反斜杠
		String specialCharReverseSolidus = "Hello\\World.";
		
		System.out.println("水平制表符tab1: " + specialCharTab1);
		System.out.println("水平制表符tab2: " + specialCharTab2);
		System.out.println("换行: " + specialCharNewLine);
		System.out.println("回车: " + specialCharReturn);
		System.out.println("双引号: " + specialCharQuotationMark);
		System.out.println("单引号: " + specialCharApostrophe);
		System.out.println("反斜杠: " + specialCharReverseSolidus);		
		
	}
}

  

  5.布尔类型

public class HelloWorld {

	// 声明布尔类型变量
	public static boolean isWoman;
	
	public static void main(String[] args) {

		// 声明布尔类型变量
		boolean isMan = true;
		boolean isWoman = false;
		
		System.out.println("男 =  " + isMan);
		System.out.println("女 =  " + isWoman);
		
//		boolean isMan1 = 1;
//		boolean isWoman1 = 'A';
	}
}

  

  6.数值类型相互抓换

public class HelloWorld {

	public static void main(String[] args) {

		////////// 自动类型转换//////////////
		// 声明整数变量
		byte byteNum = 16;
		short shortNum = 16;
		int intNum = 16;
		long longNum = 16L;

		// byte类型转换为int类型
		intNum = byteNum;
		// 声明char变量
		char charNum = '花';
		// char类型转换为int类型
		intNum = charNum;

		// 声明浮点变量
		// long类型转换为float类型
		float floatNum = longNum;
		// float类型转换为double类型
		double doubleNum = floatNum;

		// 表达式计算后类型是double
		double result = floatNum * intNum + doubleNum / shortNum;

		////////// 强制类型转换//////////////
		//int型变量
		int i = 10;
		//把int变量i强制转换为byte
		byte b = (byte) i; 
		int i2 = (int)i;
		int i3 = (int)b;
		
		//精度与强制类型转换
		float c1 = i / 3;
		System.out.println(c1);
		//把int变量i强制转换为float
		float c2 = (float)i / 3;
		System.out.println(c2);
		
		//强制类型转换导致精度丢失
	    long yourNumber = 6666666666L;
	    System.out.println(yourNumber);
	    int myNuber = (int)yourNumber;
	    System.out.println(myNuber);
	    
	}
}

  

  7.引用数据类型

public class HelloWorld {

	public static void main(String[] args) {

		int x = 7;
		int y = x;
		
		String str1 = "Hello";
		String str2 = str1;
		str2 = "World";

		System.out.println(y);
		System.out.println(str1);
		System.out.println(str2);
	}
}

  

运算符

  1.算术运算符

public class HelloWorld {

	public static void main(String[] args) {
		int a = 12;
		System.out.println(-a);
		int	b = a++;
		System.out.println(b);
		b = ++a;
		System.out.println(b);
	}
}
public class HelloWorld {

	public static void main(String[] args) {
		
		//声明一个字符类型变量
		char charNum = 'A';
		// 声明一个整数类型变量
		int intResult = charNum + 1;
		System.out.println(intResult);

		intResult = intResult - 1;
		System.out.println(intResult);

		intResult = intResult * 2;
		System.out.println(intResult);

		intResult = intResult / 2;
		System.out.println(intResult);

		intResult = intResult + 8;
		intResult = intResult % 7;
		System.out.println(intResult);

		System.out.println("-------");

		// 声明一个浮点类型变量
		double doubleResult = 10.0;
		System.out.println(doubleResult);

		doubleResult = doubleResult - 1;
		System.out.println(doubleResult);

		doubleResult = doubleResult * 2;
		System.out.println(doubleResult);

		doubleResult = doubleResult / 2;
		System.out.println(doubleResult);

		doubleResult = doubleResult + 8;
		doubleResult = doubleResult % 7;
		System.out.println(doubleResult);

	}
}
public class HelloWorld {

	public static void main(String[] args) {
		
		int a = 1;
		int b = 2;
		a += b; 	// 相当于 a = a + b
		System.out.println(a);

		a += b + 3; // 相当于 a = a + b + 3
		System.out.println(a);
		a -= b; 	// 相当于 a = a - b
		System.out.println(a);

		a *= b; 	// 相当于 a=a*b
		System.out.println(a);

		a /= b;		// 相当于 a=a/b
		System.out.println(a);

		a %= b;		// 相当于 a=a%b
		System.out.println(a);

	}
}

  

  2.关系运算符

public class HelloWorld {

	public static void main(String[] args) {

		int value1 = 1;
		int value2 = 2;
		
		if (value1 == value2) {
			System.out.println("value1 == value2");
		}

		if (value1 != value2) {
			System.out.println("value1 != value2");
		}

		if (value1 > value2) {
			System.out.println("value1 > value2");
		}

		if (value1 < value2) {
			System.out.println("value1 < value2");
		}

		if (value1 <= value2) {
			System.out.println("value1 <= value2");
		}

	}
}

  3.逻辑运算符

public class HelloWorld {

	public static void main(String[] args) {

		int i = 0;
		int a = 10;
		int b = 9;

		if ((a > b) || (i == 1)) {
			System.out.println("或运算为 真");
		} else {
			System.out.println("或运算为 假");
		}

		if ((a < b) && (i == 1)) {
			System.out.println("与运算为 真");
		} else {
			System.out.println("与运算为 假");
		}

		if ((a > b) || (a++ == --b)) {
			System.out.printf("a = %s, b = %s", a, b);
		}
	}
}

  4.位运算符

public class HelloWorld {

	public static void main(String[] args) {

		byte a = 0B00110010;	//十进制50
		byte b = 0B01011110;	//十进制94

		System.out.println("a | b = " + (a | b)); 	// 0B01111110
		System.out.println("a & b = " + (a & b)); 	// 0B00010010
		System.out.println("a ^ b = " + (a ^ b)); 	// 0B01101100
		System.out.println("~b = " + (~b)); 		// 0B10100001

		System.out.println("a >> 2 = " + (a >> 2)); 	// 0B00001100
		System.out.println("a >> 1 = " + (a >> 1)); 	// 0B00011001
		System.out.println("a >>> 2 = " + (a >>> 2)); 	// 0B00001100
		System.out.println("a << 2 = " + (a << 2)); 	// 0B11001000
		System.out.println("a << 1 = " + (a << 1)); 	// 0B01100100

		int c = -12;
		System.out.println("c >>> 2 = " + (c >>> 2));
		System.out.println("c >> 2 = " + (c >> 2));

	}
}

  5.其他运算符

import java.util.Date;

public class HelloWorld {

	public static void main(String[] args) {

		int score = 80;
		String result = score > 60 ? "及格" : "不及格"; // 三元运算符(? : )
		System.out.println(result);
		
		Date date = new Date(); 	// new运算符可以创建Date对象
		System.out.println(date.toString());// 通过.运算符调用方法

	}
}

控制语句

  1.分支语句

  if else 和 switch case

public class HelloWorld {

	public static void main(String[] args) {

		// 1. if结构
		int score = 95;
		if (score >= 85) {
			System.out.println("您真优秀!");
		}
		if (score < 60) {
			System.out.println("您需要加倍努力!");
		}
		if ((score >= 60) && (score < 85)) {
			System.out.println("您的成绩还可以,仍需继续努力!");
		}
		if (score < 60) {
			System.out.println("不及格");
		} else {
			System.out.println("及格");
		}

		// 2. if-else结构
		if (score < 60) {
			System.out.println("不及格");
		} else {
			System.out.println("及格");
		}

		// 3. else-if结构
		int testScore = 76;
		char grade;
		if (testScore >= 90) {
			grade = 'A';
		} else if (testScore >= 80) {
			grade = 'B';
		} else if (testScore >= 70) {
			grade = 'C';
		} else if (testScore >= 60) {
			grade = 'D';
		} else {
			grade = 'F';
		}
		System.out.println("Grade = " + grade);

	}
}
public class HelloWorld {

	public static void main(String[] args) {
		
		int testScore = 75;
		
		char grade;
		switch (testScore / 10) {
		case 9:
			grade = '优';
			break;
		case 8:
			grade = '良';
			break;
		case 7: //7是贯通的
		case 6:
			grade = '中';
			break;
		default:
			grade = '差';
		}
		System.out.println("Grade = " + grade);

	}
}

  

  2.循环语句

  while 和 do-while 和 for循环

public class HelloWorld {

	public static void main(String[] args) {

		int i = 0;
		while (i * i < 100000) {
			i++;
		}

		System.out.println("i = " + i);
		System.out.println("i * i = " + (i * i));
	}
}
public class HelloWorld {

	public static void main(String[] args) {

		int i = 0;
		do {
			i++;
		} while (i * i < 100000);

		System.out.println("i = " + i);
		System.out.println("i * i = " + (i * i));
	}
}
public class HelloWorld {

	public static void main(String[] args) {

		System.out.println("---------");

		for (int i = 1; i < 10; i++) {
			System.out.printf("%d x %d = %d", i, i, i * i);
			// 打印一个换行符,实现换行
			System.out.println();
		}

		System.out.println("---------");
		
		int x;
		int y;

		for (x = 0, y = 10; x < y; x++, y--) {
			System.out.printf("(x,y) = (%d, %d)", x, y);
			// 打印一个换行符,实现换行
			System.out.println();
		}

	}
}
public class HelloWorld {

	public static void main(String[] args) {

		// 声明并初始化int数组
		int[] numbers = { 43, 32, 53, 54, 75, 7, 10 };

		System.out.println("----for-------");
		// for语句
		for (int i = 0; i < numbers.length; i++) {
			System.out.println("Count is:" + numbers[i]);
		}

		System.out.println("----for each----");
		// for-each语句
		for (int item : numbers) {
			System.out.println("Count is:" + item);
		}

	}
}

  

  3.跳转语句

  break  和 continue

public class HelloWorld {

	public static void main(String[] args) {

		int numbers[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

		for (int i = 0; i < numbers.length; i++) {
			if (i == 3) {
				// 跳出循环
				break;
			}
			System.out.println("Count is: " + i);
		}

		label1: for (int x = 0; x < 5; x++) {
			for (int y = 5; y > 0; y--) {
				if (y == x) {
					// 跳转到label1指向的外循环
					break label1;
				}
				System.out.printf("(x,y) = (%d,%d)", x, y);
				// 打印一个换行符,实现换行
				System.out.println();
			}
		}
		System.out.println("Game Over!");

	}
}
public class HelloWorld {

	public static void main(String[] args) {

		int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

		for (int i = 0; i < numbers.length; i++) {
			if (i == 3) {
				continue;
			}
			System.out.println("Count is: " + i);
		}

		label1: for (int x = 0; x < 5; x++) {
			for (int y = 5; y > 0; y--) {
				if (y == x) {
					continue label1;
				}
				System.out.printf("(x,y) = (%d,%d)", x, y);
				System.out.println();
			}
		}
		System.out.println("Game Over!");
	}
}

  

数组

  1.一维数组

public class HelloWorld {

	public static void main(String[] args) {

		// 静态初始化
		int[] intArray1 = { 21, 32, 43, 45 };
		String[] strArray1 = { "张三", "李四", "王五", "董六" };

		int intArray[];
		// 动态初始化int数组
		intArray = new int[4];
		intArray[0] = 21;
		intArray[1] = 32;
		intArray[2] = 43;
		intArray[3] = 45;

		// 动态初始化String数组
		String[] stringArray = new String[4];
		// 初始化数组中元素
		stringArray[0] = "张三";
		stringArray[1] = "李四";
		stringArray[2] = "王五";
		stringArray[3] = "董六";

	}
}
/*
 * 本例实现数组合并
 */
public class HelloWorld {

	public static void main(String[] args) {
		// 两个待合并数组
		int array1[] = { 20, 10, 50, 40, 30 };
		int array2[] = { 1, 2, 3 };

		// 动态初始化数组,设置数组的长度是array1和array2长度之和
		int array[] = new int[array1.length + array2.length];

		// 循环添加数组内容
		for (int i = 0; i < array.length; i++) {

			if (i < array1.length) {
				array[i] = array1[i];
			} else {
				array[i] = array2[i - array1.length];
			}
		}

		System.out.println("合并后:");
		for (int element : array) {
			System.out.printf("%d ", element);
		}
	}
}

  

  2.多维数组

public class HelloWorld {

	public static void main(String[] args) {
		
		// 静态初始化二维数组
		int[][] intArray = { 
				{ 1, 2, 3 }, 
				{ 11, 12, 13 }, 
				{ 21, 22, 23 },
				{ 31, 32, 33 } };

		// 动态初始化二维数组
		double[][] doubleArray = new double[4][3];

		// 计算数组intArray元素的平方根,结果保存到doubleArray
		for (int i = 0; i < intArray.length; i++) {
			for (int j = 0; j < intArray[i].length; j++) {
				// 计算平方根
				doubleArray[i][j] = Math.sqrt(intArray[i][j]);
			}
		} 

		// 打印数组doubleArray
		for (int i = 0; i < doubleArray.length; i++) {
			for (int j = 0; j < doubleArray[i].length; j++) {
				System.out.printf("[%d][%d] = %f", i, j, doubleArray[i][j]);
				System.out.print('\t');
			}
			System.out.println();
		}

	}
}
public class HelloWorld {

	public static void main(String[] args) {

		int intArray[][] = new int[4][]; //先初始化高维数组为4
		//逐一初始化低维数组
		intArray[0] = new int[2]; 
		intArray[1] = new int[1];
		intArray[2] = new int[3];
		intArray[3] = new int[3];
		
		//for循环遍历
		for (int i = 0; i < intArray.length; i++) {
			for (int j = 0; j < intArray[i].length; j++) {
				intArray[i][j] = i + j;
			}
		} 
		//for-each循环遍历
		for (int[] row : intArray) {
			for (int column : row) {				
				System.out.print(column);
				//在元素之间添加制表符,
				System.out.print('\t');
			}
			//一行元素打印完成后换行
			System.out.println();
		} 
		
		//System.out.println(intArray[0][2]); //发生运行期错误		
	}
}

  

字符串

  1.不可变字符串

  concat 字符串连接

  length 字符串长度

  charAt 获取当前索引位置所在字节

  indexOf 获取第一个找到的字节的索引位置,从左往右找

  lastIndexOf 获取倒数第一个找到的字节的索引位置,从右往左找

  equals 变量值是否相等

  equalsIgnoreCase 忽略大小写,变量值是否相等

  trim 去掉左右空格

  endsWith 以社么结尾

  startsWith 以什么开头

  toLowerCase 转换成小写

  substring 通过索引区间取子串

  split 以什么分割,获得一个数组

public class HelloWorld {

	public static void main(String[] args) {

		// 创建字符串对象
		String s1 = new String();
		String s2 = new String("Hello World");
		String s3 = new String("\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064");
		System.out.println("s2 = " + s2);
		System.out.println("s3 = " + s3);
		

		char chars[] = { 'a', 'b', 'c', 'd', 'e' };
		// 通过字符数组创建字符串对象
		String s4 = new String(chars);
		// 通过子字符数组创建字符串对象
		String s5 = new String(chars, 1, 4);
		System.out.println("s4 = " + s4);
		System.out.println("s5 = " + s5);

		byte bytes[] = { 97, 98, 99 };
		// 通过byte数组创建字符串对象
		String s6 = new String(bytes);
		System.out.println("s6 = " + s6);
		System.out.println("s6字符串长度 = " + s6.length());

	}
}
public class HelloWorld {

	public static void main(String[] args) {

		String s7 = new String("Hello");
		String s8 = new String("Hello");

		String s9 = "Hello";
		String s10 = "Hello";

		System.out.printf("s7 == s8 : %b%n", s7 == s8);
		System.out.printf("s9 == s10: %b%n", s9 == s10);
		System.out.printf("s7 == s9 : %b%n", s7 == s9);
		System.out.printf("s8 == s9 : %b%n", s8 == s9);

	}
}
public class HelloWorld {

	public static void main(String[] args) {

		String s1 = "Hello";
		// 使用+运算符连接
		String s2 = s1 + " ";
		String s3 = s2 + "World";
		System.out.println(s3);

		String s4 = "Hello";
		// 使用+运算符连接,支持+=赋值运算符
		s4 += " ";
		s4 += "World";
		System.out.println(s4);

		String s5 = "Hello";
		// 使用concat方法连接
		s5 = s5.concat(" ").concat("World");
		System.out.println(s5);

		int age = 18;
		String s6= "她的年龄是" + age + "岁。";
		System.out.println(s6);
		
		char score = 'A';
		String s7= "她的英语成绩是" + score;
		System.out.println(s7);
		
		java.util.Date now = new java.util.Date();
		//对象拼接自动调用toString()方法
		String s8= "今天是:" + now;
		System.out.println(s8);
		
	}
}
public class HelloWorld {

	public static void main(String[] args) {

		String sourceStr = "There is a string accessing example.";

		//获得字符串长度
		int len = sourceStr.length();
		//获得索引位置16的字符
		char ch = sourceStr.charAt(16);

		//查找字符和子字符串
		int firstChar1 = sourceStr.indexOf('r');
		int lastChar1 = sourceStr.lastIndexOf('r');
		int firstStr1 = sourceStr.indexOf("ing");
		int lastStr1 = sourceStr.lastIndexOf("ing");
		int firstChar2 = sourceStr.indexOf('e', 15);
		int lastChar2 = sourceStr.lastIndexOf('e', 15);
		int firstStr2 = sourceStr.indexOf("ing", 5);
		int lastStr2 = sourceStr.lastIndexOf("ing", 5);

		System.out.println("原始字符串:" + sourceStr);
		System.out.println("字符串长度:" + len);
		System.out.println("索引16的字符:" + ch);
		System.out.println("从前往后搜索r字符,第一次找到它所在索引:" + firstChar1);
		System.out.println("从后往前搜索r字符,第一次找到它所在的索引:" + lastChar1);
		System.out.println("从前往后搜索ing字符串,第一次找到它所在索引:" + firstStr1);
		System.out.println("从后往前搜索ing字符串,第一次找到它所在索引:" + lastStr1);
		System.out.println("从索引为15位置开始,从前往后搜索e字符,第一次找到它所在索引:" + firstChar2);
		System.out.println("从索引为15位置开始,从后往前搜索e字符,第一次找到它所在索引:" + lastChar2);
		System.out.println("从索引为5位置开始,从前往后搜索ing字符串,第一次找到它所在索引:" + firstStr2);
		System.out.println("从索引为5位置开始,从后往前搜索ing字符串,第一次找到它所在索引:" + lastStr2);

	}
}
public class HelloWorld {

	public static void main(String[] args) {

		String s1 = new String("Hello");
		String s2 = new String("Hello");
		// 比较字符串是否是相同的引用
		System.out.println("s1 == s2 : " + (s1 == s2));
		// 比较字符串内容是否相等
		System.out.println("s1.equals(s2) : " + (s1.equals(s2)));

		String s3 = "HELlo";
		// 忽略大小写比较字符串内容是否相等
		System.out.println("s1.equalsIgnoreCase(s3) : " + (s1.equalsIgnoreCase(s3)));

		// 比较大小
		String s4 = "java";
		String s5 = "Swift";
		// 比较字符串大小 s4 > s5
		System.out.println("s4.compareTo(s5) : " + (s4.compareTo(s5)));
		// 忽略大小写比较字符串大小 s4 < s5
		System.out.println("s4.compareToIgnoreCase(s5) : " + (s4.compareToIgnoreCase(s5)));

		// 判断文件夹中文件名
		String[] docFolder = { "java.docx", " JavaBean.docx", "Objecitve-C.xlsx", "Swift.docx " };
		int wordDocCount = 0;
		// 查找文件夹中Word文档个数
		for (String doc : docFolder) {
			// 去的前后空格
			doc = doc.trim();
			// 比较后缀是否有.docx字符串
			if (doc.endsWith(".docx")) {
				wordDocCount++;
			}
		}
		System.out.println("文件夹中Word文档个数是: " + wordDocCount);

		int javaDocCount = 0;
		// 查找文件夹中Java相关文档个数
		for (String doc : docFolder) {
			// 去的前后空格
			doc = doc.trim();
			// 全部字符转成小写
			doc = doc.toLowerCase();
			// 比较前缀是否有java字符串
			if (doc.startsWith("java")) {
				javaDocCount++;
			}
		}
		System.out.println("文件夹中Java相关文档个数是:" + javaDocCount);

	}
}
public class HelloWorld {

	public static void main(String[] args) {

		String sourceStr = "There is a string accessing example.";
		// 截取example.子字符串
		String subStr1 = sourceStr.substring(28);
		// 截取string子字符串
		String subStr2 = sourceStr.substring(11, 17);
		System.out.printf("subStr1 = %s%n", subStr1);
		System.out.printf("subStr2 = %s%n",subStr2);

		// 使用split方法分割字符串
		System.out.println("-----使用split方法-----");
		String[] array = sourceStr.split(" ");
		for (String str : array) {
			System.out.println(str);
		}
	}
}

  

  2.可变字符串

创建用new StringBuilder(),直接作用对象本身,不用重新赋值

  length 字符串长度

  capacity 字符串缓冲区容量

  append 字符串拼接

  insert 指定某个索引位置插入字符串

  delete 删除某个索引区间的字符串

public class HelloWorld {

	public static void main(String[] args) {

		//-----------------------------------
		// 字符串长度length和字符串缓冲区容量capacity
		StringBuilder sbuilder1 = new StringBuilder();
		System.out.println("包含的字符串长度:" + sbuilder1.length());
		System.out.println("字符串缓冲区容量:" + sbuilder1.capacity());

		StringBuilder sbuilder2 = new StringBuilder("Hello");
		System.out.println("包含的字符串长度:" + sbuilder2.length());
		System.out.println("字符串缓冲区容量:" + sbuilder2.capacity());

		// 字符串缓冲区初始容量是16,超过之后会扩容
		StringBuilder sbuilder3 = new StringBuilder();
		for (int i = 0; i < 17; i++) {
			sbuilder3.append(8);
		}
		System.out.println("包含的字符串长度:" + sbuilder3.length());
		System.out.println("字符串缓冲区容量:" + sbuilder3.capacity());
		
	}
}
public class HelloWorld {

	public static void main(String[] args) {

		//添加字符串、字符
		StringBuilder sbuilder1 = new StringBuilder("Hello");
		sbuilder1.append(" ").append("World");
		sbuilder1.append('.');
		System.out.println(sbuilder1);
		
		StringBuilder sbuilder2 = new StringBuilder();
		Object obj = null;
		//添加布尔值、转义符和空对象
		sbuilder2.append(false).append('\t').append(obj);
		System.out.println(sbuilder2);

		//添加数值
		StringBuilder sbuilder3 = new StringBuilder();
		for (int i = 0; i < 10; i++) {
			sbuilder3.append(i);
		} 
		System.out.println(sbuilder3);
	}
}
public class HelloWorld {

	public static void main(String[] args) {
		// 原始不可变字符串
		String str1 = "Java C";
		// 从不可变的字符创建可变字符串对象
		StringBuilder mstr = new StringBuilder(str1);

		// 插入字符串
		mstr.insert(4, " C++");
		System.out.println(mstr);

		// 具有追加效果的插入字符串
		mstr.insert(mstr.length(), " Objective-C");
		System.out.println(mstr);
		// 追加字符串
		mstr.append(" and Swift");
		System.out.println(mstr);

		// 删除字符串
		mstr.delete(11, 23);
		System.out.println(mstr);

	}
}

  

中文api: 链接

猜你喜欢

转载自www.cnblogs.com/xinsiwei18/p/8945859.html
今日推荐