java基础积累

tech2026-02-01  10

for循坏判断

equals和==返回的是boolean类型

equals方法判断的是值是否相等

==判断的是内存地址是否相等

改进

ArrayList用到的是索引,Map用到的是key

使用到indexOf,indexof方法是返回从第一个数开始查找与给定数据类型匹配的值的索引值

继续改进   Integer常用方法

String c = "151515"; int d = Integer.parseInt(c); string转int String e =Integer.toString(d); int转string Integer f = Integer.valueOf(d); int转Integer Integer g = Integer.valueOf(c); string转Integer int o = Integer.valueOf(z).intValue(); 最后加intValue是把前面的Integer类型转成int

 

获取一个变量的类型  

String a = "abcd"; String b = a.getClass().toString(); System.out.println(b);

 

String常用方法

.indexOf

if(a.indexOf("c") == -1);

string本身就是char[] 数组类型,indexOf就是数组类型的一个方法。

 

.concat

String a = "abcd"; String b = a.concat("efg"); System.out.println(b);

.split

String a ="1,2,3"; String[] b = a.split("\\,"); System.out.println(b[0]+" "+b[1]+" "+b[2]);


String.trim()   和  String.substring()

String.trim() :可以理解是截掉前后空格,中间的空格不去,返回一个新对象。其实它是截掉中间非空的字符串。

String.substring():上面是定死截掉前后,这个方法是自定义截取,截完之后返回的同样是一个新的对象。

public class test { public static void main(String[] args) { String str1 = "abc "; String str2 = "abc"; String str3 = "abc"; str1 = str1.trim(); System.out.println(str1 == str2); // false System.out.println(str3 == str2); // true String a = "abcd "; String b = "abc"; System.out.println(a.length());//7 System.out.println(a.substring(0,3));//abc System.out.println(a == b);//false String c = " a b c de "; System.out.println(c.trim());//a b c de String d = "abc"; System.out.println(b == d);//true String e = new String("abc"); System.out.println(e == d);//false } }

常量池中的对象有就拿来就用,没有就新创建,如果是自己新创建,就不是从常量池取。

 

Exception和RuntimeException的区别原理

Exception:在程序中必须使用try…catch进行处理,不加try…catch的后果就是错误会显示在前端页面上,直接暴露给用户,应该避免这种情况。 RuntimeException:可以不使用try…catch进行处理,但是如果有异常产生,则异常将由JVM进行处理。

常见的RuntimeException RuntimeException是开发中最容易遇到的,下面列举一下常见的RuntimeException: 1、NullPointerException:见的最多了,其实很简单,一般都是在null对象上调用方法了。 2、NumberFormatException:继承IllegalArgumentException,字符串转换为数字时出现。比如int i= Integer.parseInt(“ab3”); 3、ArrayIndexOutOfBoundsException:数组越界。比如 int[] a=new int[3]; int b=a[3]; 4、StringIndexOutOfBoundsException:字符串越界。比如 String s=“hello”; char c=s.chatAt(6); 5、ClassCastException:类型转换错误。比如 Object obj=new Object(); String s=(String)obj; 6、UnsupportedOperationException:该操作不被支持。如果我们希望不支持这个方法,可以抛出这个异常。既然不支持还要这个干吗?有可能子类中不想支持父类中有的方法,可以直接抛出这个异常。 7、ArithmeticException:算术错误,典型的就是0作为除数的时候。 8、IllegalArgumentException:非法参数,在把字符串转换成数字的时候经常出现的一个异常,我们可以在自己的程序中好好利用这个异常。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

最新回复(0)