Java总结之基础篇

 

目录

1.基本类型

1.1储存空间

1.2char

2.运算符

2.1三目运算符

2.2运算符优先级

2.3“equals()”与“==”

3.数组

3.1创建写法

3.2数组操作代码

3.3自定义类数组

4.面向对象

4.1重载与重写

4.2单例模式

4.3抽象类与接口

5.一些实用类

5.1String类及正则表达式

5.2Date类

5.3Calender类

5.4UUID类

6.集合

6.1List,设置以及地图比较

6.2不同场景下的使用情况

7.IO基本操作

7.1字节流与字符流的区别

7.2字节流与字符流的实例

1.基本类型

1.1储存空间

字节型 

byte

1字节
整型
short2字节
int4字节
long8字节
浮点型
float4字节
double8字节
字符型
char2字节
布尔型
boolean1字节

1.2char

1.2.1 char a ='\ u0041'可表示一个汉字,基于原始的Unicode规范

1.2.2 char a = 99 

一个可以直接比较:

 
  1. char a = 99;

  2. if (a < 'z' && a > 'a') {

  3.     System.out.println(a);

  4. }

2.运算符

2.1三目运算符

布尔表达式表达式1:表达式2

练习:

当x> 0:sgn(x)= 1;

当x = 0:sgn(x)= 0;

当x <0:sgn(x)= - 1;

输入x,输出sgn(x)的值。

 
  1. public static void function04(){

  2. System.out.println("请输入x的值:");

  3. Scanner scan = new Scanner(System.in);

  4. int x = scan.nextInt();

  5. System.out.println("sgn(x)=" + (0==x?0:(x>0?1:-1)));

  6. }

2.2运算符优先级

'  {}  '>'  ++  '>'(强制类型转换)'>'  /  '>'  +  '>'  <<  '>'  > =  '>'  ==  '>'  &  '>'  ^  '>'   |   '>'  &&  '>'  ||  '>'  ?:'>'  =  '

2.3“equals()方法”与“==”

equals()

注意:等于方法不能作用于基本数据类型的变量。

如果没有对等于方法进行重写,则比较的是引用类型的变量所指向的对象的地址;

诸如字符串,日期等类对等于方法进行了重写的话,比较的是所指向的对象的内容。

==

如果作用于基本数据类型的变量,则直接比较其存储的“值”是否相等;

如果作用于引用类型的变量,则比较的是所指向的对象的地址。

3.数组

3.1创建写法

int [] arr = new int [10]; //初始化

int [] arr = {1,2,3,4,5}; //初始化并赋值

int [] arr1 = new int [] {1,2,3,4,5};

3.2数组操作代码

 
  1. //复制数组

  2. int[] aa=new int[3];

  3. for(int i=0;i<3;i++){

  4. aa[i]=1;

  5. }

  6. int[] bb=Arrays.copyOf(aa, 4);

  7. //1 1 1 0

  8.  
  9. bb=Arrays.copyOf(aa, 4);

  10. //数组升序快排

  11. int[] a={1,4,-1,5,0};

  12. Arrays.sort(a);

  13.  
  14. //二分查找

  15. String str[] = new String[]{"ab", "cd", "ef", "yz"};//定义String型数组str

  16. Arrays.sort(str);//对数组进行排序

  17. int index = Arrays.binarySearch(str, 0, 2, "cd");//在制定范围内搜索元素“cd”的索引位置

  18.  
  19. //将Array转化成Set集合

  20. Set<String> set = new HashSet<String>(Arrays.asList(stringArray));

  21. System.out.println(set);

  22. //[d, e, b, c, a]

  23.  
  24. //数组翻转

  25. int[] intArray = { 1, 2, 3, 4, 5 };

  26. ArrayUtils.reverse(intArray);

  27. System.out.println(Arrays.toString(intArray));

  28. //[5, 4, 3, 2, 1]

  29.  
  30. //从数组中移除一个元素

  31. int[] intArray = { 1, 2, 3, 4, 5 };

  32. int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array

  33. System.out.println(Arrays.toString(removed));

  34.  
  35. //将一个int值转化成byte数组

  36. byte[] bytes = ByteBuffer.allocate(4).putInt(8).array();

  37. for (byte t : bytes) {

  38. System.out.format("0x%x ", t);

  39. }

  40.  
  41. //检查数组中是否包含某一个值

  42. String[] stringArray = { "a", "b", "c", "d", "e" };

  43. boolean b = Arrays.asList(stringArray).contains("a");

  44. System.out.println(b);

  45. // true

  46.  
  47. //连接两个数组

  48. int[] intArray = { 1, 2, 3, 4, 5 };

  49. int[] intArray2 = { 6, 7, 8, 9, 10 };

  50. // Apache Commons Lang library

  51. int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);

  52.  
  53. //将数组中的元素以字符串的形式输出

  54. String j = StringUtils.join(new String[] { "a", "b", "c" }, ", ");

  55. System.out.println(j);

3.3自定义类数组

class Person {...}

static Person [] aa = new Person [N];

for(int i = 0; i<N-1; i++){

    aa [i] =Person ();

    赋值操作;

}

即必须每个自定义类数组元素使用前都应该先初始化!

4.面向对象

4.1重载与重写

比较项目

重载

覆写/重写

英文名

超载

覆盖

函数签名

只要求函数的参数个数或类型不一致,对返回值没要求

函数的参数个数,类型,返回值都必须完全一样。

发生地方

同一个类或者具有继承关系的两个类中

只能发生在继承关系的两个类中

访问权限

没有限制

 

子类覆写方法的访问权限必须大于或等于父类的方法的访问权限

4.2单例模式

 
  1. //饿汉(推荐)

  2. public class demo {

  3. public static void main(String[] args) {

  4. test1 s = test1.get();

  5. System.out.println(s);

  6. }

  7. }

  8. class test1 {

  9. private static test1 s = new test1();

  10. public static test1 get() {

  11. return s;

  12. }

  13. }

  14.  
  15. //懒汉

  16. public class demo1 {

  17. public static void main(String[] args) {

  18. test2 s = test2.get();

  19. System.out.println(s);

  20. }

  21. }

  22. class test2 {

  23. private static test2 s;

  24. public static test2 get() {

  25. if (s == null) {

  26. s = new test2();

  27. }

  28. return s;

  29. }

  30. }

  31. //懒汉式是延时加载, 懒汉式如果在创建实例对象时不加上synchronized则会导致对对象的访问不是线程安全的,

  32. 他是在需要的时候才创建对象,而饿汉式在虚拟机启动的时候就会创建。

4.3抽象类与接口

类抽象艺术的英文用来捕捉子类的通用特性的。它不能被实例化,只能被用作子类的超类。抽象类是被用来创建继承层级里子类的模板。

 
  1. public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {

  2. abstract void service(ServletRequest req, ServletResponse res);

  3. }

  4. //继承抽象类,实现抽象方法

  5. public class HttpServlet extends GenericServlet {

  6. void service(ServletRequest req, ServletResponse res) {

  7. // implementation

  8. }

  9. }

接口的抽象艺术英文艺术方法的集合。如果一个类实现了某个接口,那么它就继承了这个接口的抽象方法。这就像契约模式,如果实现了这个接口,那么就必须确保使用这些方法接口。只是一种形式,接口自身不能做任何事情。

 
  1. public interface Externalizable extends Serializable {

  2. void writeExternal(ObjectOutput out) throws IOException;

  3. void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;

  4. }

  5. //继承并实现接口的方法

  6. public class Employee implements Externalizable {

  7. int employeeId;

  8. String employeeName;

  9.  
  10. @Override

  11. public void writeExternal(ObjectOutput out) throws IOException {

  12. out.writeInt(employeeId);

  13. out.writeObject(employeeName);

  14. }

  15.  
  16. @Override

  17. public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {

  18. employeeId = in.readInt();

  19. employeeName = (String) in.readObject();

  20. }

  21. }

什么时候使用抽象类和接口

  • 如果你拥有一些方法并且想让它们中的一些有默认实现,那么使用抽象类吧。

  • 如果你想实现多重继承,那么你必须使用接口。由于Java的的不支持多继承,子类不能够继承多个类,但可以实现多个接口。因此你就可以使用接口来解决它。

  • 如果基本功能在不断改变,那么就需要使用抽象类。如果不断改变基本功能并且使用接口,那么就需要改变所有实现了该接口的类。

5.一些实用类

5.1String类及正则表达式

 
  1. /**

  2. * 1:输出字符串"HelloWorld"的字符串长度

  3. * 2:输出"HelloWorld"中"o"的位置

  4. * 3:输出"HelloWorld"中从下标5出开始第一次出现"o"的位置

  5. * 4:截取"HelloWorld"中的"Hello"并输出

  6. * 5:截取"HelloWorld"中的"World"并输出

  7. * 6:将字符串" Hello "中两边的空白去除后输出

  8. * 7:输出"HelloWorld"中第6个字符"W"

  9. * 8:输出"HelloWorld"是否是以"h"开头和"ld"结尾的。

  10. * 9:将"HelloWorld"分别转换为全大写和全小写并输出。

  11. */

  12. public class Test01 {

  13. public static void main(String[] args) {

  14. String str = "HelloWorld";

  15. test1(str);

  16. }

  17. public static void test1(String str){

  18. System.out.println(str.length());

  19. }

  20. public static void test2(String str){

  21. System.out.println(str.indexOf('o'));

  22. }

  23. public static void test3(String str){

  24. System.out.println(str.indexOf('o', 5));

  25. }

  26. public static void test4(String str){

  27. System.out.println(str.substring(0,5));//substring()内取右不取左

  28. }

  29. public static void test5(String str){

  30. System.out.println(str.substring(5));

  31. }

  32. public static void test6(String str){

  33. System.out.println(str.trim());

  34. }

  35. public static void test7(String str){

  36. System.out.println(str.charAt(5));

  37. }

  38. public static void test8(String str){

  39. System.out.println(str.startsWith("h")+"\n"+str.endsWith("ld"));

  40. }

  41. public static void test9(String str){

  42. System.out.println(str.toLowerCase()+"\n"+str.toUpperCase());

  43. }

  44. }

  45.  

正则表达式:

常见的正则表达式

[abc]                 abc中任意一个字符

[^abc]                除了abc的任意字符

[a-z]                  a-z中任意一个字符

[a-zA-Z0-9]       a-z,A-Z,0-9中任意一个字符

[a-z&&[^bc]]      一个字符,a-z中除了bc意外的任意字符。

 

\d                      任意一个数字字符 [0-9]

\D                     任意一个非数字字符[^0-9]

\s                      空白字符,[\t\n\r\x0B\f]

\S                     非空白字符 [^\s]

\w                     就是[a-zA-Z_0-9]

\W                     [^\w]

 

A?                    表示0个或1个A

A*                     表示0个或多个A

A+                    表示1个或多个A

A{5}                  表示5个A

A{5,}                 表示5个到任意多个A

A{5,11}             表示5个到11个A

 
  1. 1.从键盘输入一个手机号,判断手机号格式是否合法。

  2. 1) 全是数字

  3. 2) 11位

  4. 3) 1开头,第二位号码为345678,

  5. static void function04() {

  6. Scanner scan = new Scanner(System.in);

  7. System.out.println("请输入用户手机号:");

  8. String str = scan.next();

  9. boolean b = str.matches("1[345678][0-9]{9}");

  10. System.out.println(b?"号码正确!":"手机号有误!");10)

  11. }

  12.  
  13. 2.检查邮箱格式是否合法

  14. 1) @前 字母数字_ 至少1个

  15. 2) @后 字母数字 至少1个

  16. 3) 有形如.cn域名

  17. 实例:

  18. //neo@sina.com

  19. //huangliang@yaohoo.com.cn

  20. static void function01(){

  21. Scanner scan = new Scanner(System.in);

  22. System.out.println("请输入你的邮箱地址:");

  23. String email = scan.next();

  24. boolean b = email.matches("[a-zA-Z_0-9]+@[a-z0-9]+(\\.[a-z]{2,})+");

  25. System.out.println(b);

  26. scan.close();

  27. }

  28.  

5.2Date类

 
  1. //1.日期格式化输出

  2. public static void name1() {

  3. Date aaData = new Date();

  4. DateFormat aa = new SimpleDateFormat("yyyy-MM-dd HH:mm");

  5. String string = aa.format(aaData);

  6. System.out.println(string);

  7. }

  8. //2018-07-19 21:35

  9.  
  10. //2.用户输入日期字符串,解析成Date 并打印。

  11. public static void name2() {

  12. System.out.println("请输入日期:如2018-07-18");

  13. Scanner scanner = new Scanner(System.in);

  14. String ss = scanner.nextLine().trim();

  15. try {

  16. SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");

  17. Date date = format1.parse(ss);

  18. System.out.println("Date:"+date);

  19. String string = format1.format(date);

  20. System.out.println("Date:"+string);

  21. } catch (ParseException e) {

  22. e.printStackTrace();

  23. }

  24. }

  25. //键入2018-07-18

  26. //Date:Wed Jul 18 00:00:00 CST 2018

  27. //Date:2018-07-18

  28.  
  29. //3.计算你们在一起多少天了。

  30. static void function06() throws Exception{

  31. System.out.println("请你们认识的日期:如2018-07-18");

  32. Scanner scan = new Scanner(System.in);

  33. String str = scan.nextLine().trim();

  34.  
  35. SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");

  36. Date date = format1.parse(str);//相遇日期

  37. long t = date.getTime();

  38.  
  39. Date date1 = new Date();//当前日期

  40. long t1 = date1.getTime();

  41. long s = t1 - t;

  42.  
  43. long days = s/1000/60/60/24;

  44. if(days<0) {

  45. System.out.println("你的女票将在"+(-days)+"天后出现,请注意查收。");

  46. }else {

  47. System.out.println("你们已经认识"+days+"天。");

  48. }

  49. }

  50. //today:2018-07-19

  51. //键入2018-07-10

  52. //你们已经认识9天。

5.3Calender类

 
  1. //显示当前时间

  2. public class Calendar_ {

  3. public static void main(String[] args) {

  4. function02();

  5. }

  6. static void function02(){

  7. Calendar c = Calendar.getInstance();

  8. System.out.println(c);

  9. //显示设置的时间

  10. //c.set(2099, 1, 9, 9, 9);

  11. int year = c.get(Calendar.YEAR);

  12. int month = c.get(Calendar.MONTH)+1;//month从0开始

  13. int day = c.get(Calendar.DAY_OF_MONTH);

  14. int hour = c.get(Calendar.HOUR_OF_DAY);

  15. int m = c.get(Calendar.MINUTE);

  16. System.out.println(year+"年"+month+"月"+day+"日"+hour+"点"+m+"分");

  17. }

  18. }

  19. //2018年7月20日9点30分

5.4UUID类

 
  1. // 生成一个id

  2. public static String createId() {

  3. UUID uid = UUID.randomUUID();

  4. String userId = uid.toString();

  5. String id = userId.replace("-", "");

  6. return id;

  7. }

  8. //80e1146c3c7344dd9b957be907056c8f

6.集合

6.1List,Set以及Map比较

List:

  • 可以允许重复的对象。
  • 可以插入多个null元素。
  • 是一个有序容器,保持了每个元素的插入顺序,输出的顺序就是插入的顺序。
  •  常用的实现类有 ArrayList、LinkedList 和 Vector。ArrayList 最为流行,它提供了使用索引的随意访问,而 LinkedList 则对于经常需要从 List 中添加或删除元素的场合更为合适。

Set:

  • 不允许重复对象
  • 只允许一个 null 元素
  • 无序容器,你无法保证每个元素的存储顺序,TreeSet通过 Comparator  或者 Comparable 维护了一个排序顺序。
  • Set 接口最流行的几个实现类是 HashSet、LinkedHashSet 以及 TreeSet。最流行的是基于 HashMap 实现的 HashSet;TreeSet 还实现了 SortedSet 接口,因此 TreeSet 是一个根据其 compare() 和 compareTo() 的定义进行排序的有序容器

Map:

  • Map不是collection的子接口或者实现类。Map是一个接口。
  • Map 的 每个 Entry 都持有两个对象,一个键一个值(key,value),Map 可有相同的value但key必须是唯一的。
  • TreeMap也通过Comparator或者Comparable维护了一个排序顺序。
  • 地图里你可以拥有随意个空值但最多只能有一个空键键,。
  • 5.Map接口最流行的几个实现类是HashMap,LinkedHashMap,Hashtable和TreeMap。(HashMap,TreeMap最常用)

6.2不同场景下的使用情况

  1. 如果你经常使用索引查找,用ArrayList。如果经常添加删除元素,用LinkedList。
  2. 如果你想容器中的元素有序存储,那么List。
  3. 如果你不想有重复值的出现,选择Set的实现类,所有存储于TreeSet中的元素可以使用Java里的比较器或者Comparable进行排序.LinkedHashSet的遍历序和插入序是一致。
  4. 如果你以键和值的形式进行数据存储那么Map。

7.IO基本操作

7.1字节流与字符流的区别

  • 字节流操作的基本单元为字节;字符流操作的基本单元为Unicode的的码元。
  • 字节流默认不使用缓冲区;字符流使用缓冲区。
  • 字节流通常用于处理二进制数据,实际上它可以处理任意类型的数据,但它不支持直接写入或读取的Unicode的码元;字符流通常处理文本数据,它支持写入及读取的Unicode的码元。

那开发中究竟用字节流好还是用字符流好呢?

一般选择字节流

字符流操作文本,其他的字节流。

7.2字节流与字符流的实例

 
  1. //字节流写入"好好学习Java"到.txt

  2. public class WriteIntoTXT {

  3. public static void main(String[] args) {

  4. FileOutputStream fos = null;

  5. try {

  6. String str = "好好学习Java";

  7. byte[] words = str.getBytes();

  8. fos = new FileOutputStream("D:\\Project resources\\Java_File_txt\\hello.txt");

  9. fos.write(words, 0, words.length);

  10. System.out.println("hello文件已更新!");

  11. } catch (IOException obj) {

  12. System.out.println("创建文件时出错!");

  13. } finally {

  14. try {

  15. if (fos != null){

  16. fos.close();

  17. }

  18. } catch (IOException e) {

  19. e.printStackTrace();

  20. }

  21. }

  22. }

  23. }

  24.  
  25. /**

  26. * 字符流

  27. * 文件数据读写

  28. 1) 在硬盘上创建一个文件

  29. 2) 一个方法写入 20 个 byte, 整数: 1, 2, ... 20

  30. 3) 定义一个方法逐个 byte 读取内容, 并且累加全部的结果,返回

  31. */

  32. public class FileToAry {

  33. static int sum = 0;

  34. public static void main(String[] args) throws Exception {

  35. FileWriter fiss = null;

  36. FileWriter fisss = null;

  37. BufferedReader br = null;

  38. try {

  39. int[] ary = null;

  40. byte[] num = new byte[20];

  41. fisss = new FileWriter("D:\\Project resources\\Java_File_txt\\1`20.txt");

  42. fiss = new FileWriter("D:\\Project resources\\Java_File_txt\\1加到20的和.txt");

  43. // 使用BufferedReader最大好处是可以按行读取,每次读取一行

  44. br = new BufferedReader(new FileReader("D:\\Project resources\\Java_File_txt\\1`20.txt"));

  45. String temp;// 定义字符串,用于保存每行读取到的数据

  46. for (int i = 0; i < 20; i++) {

  47. num[i] = (byte) (i + 1);

  48. System.out.println(num[i]);

  49. }

  50. for (int i = 0; i < 20; i++)

  51. fisss.write(String.valueOf(num[i]) + "\t");

  52. fisss.flush();

  53. while ((temp = br.readLine()) != null) {

  54. ary = aryChange(temp);// 通过函数把字符串数组解析成整数数组

  55. }

  56. for (int i = 0; i < 19; i++) {

  57. fiss.write(String.valueOf(ary[i]) + "+");

  58. }

  59. fiss.write(String.valueOf(ary[19]) + "=");

  60. fiss.write(String.valueOf(sum));

  61. fiss.flush();

  62. } catch (IOException obj) {

  63. System.out.println("文件出错!");

  64. } finally {

  65. try {

  66. br.close();// 关闭输入流

  67. fiss.close();

  68. fisss.close();

  69. } catch (IOException e) {

  70. e.printStackTrace();

  71. }

  72. }

  73. }

  74.  
  75. static int[] aryChange(String temp) {// 字符串数组解析成int数组

  76. String[] ss = temp.trim().split("\t");// .trim()可以去掉首尾多余的空格

  77. int[] ary = new int[ss.length];

  78. for (int i = 0; i < ss.length; i++) {

  79. ary[i] = Integer.parseInt(ss[i]);// 解析数组的每一个元素

  80. sum += ary[i];

  81. }

  82. return ary;// 返回一个int数组

  83. }

  84. }

  85. //1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20=210

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值