Java常用类

Java常用类

1.String类

  java.lang.String代表不可变的字符序列

  “xxxx”为该类的一个对象

  String是由一组字符组成的字符串

  声明格式:

  String s = “abc”;

  String s = new String(“abc”);

  1>常见的构造方法:

String(String original)//创建一个String对象为original的拷贝
String(char90 value)//用一个字符数组创建一个String对象
String(char[] value,int offset,int count)//用一个字符数组从offset项开始的count个字符序列创建一个String对象  

  2>常用方法

比较equals()

去字符串两端空格

trim()
替换replace()
查找,有则返回索引,无则返回-1indexOf()
lastIndexOf()
判断是否有前缀后缀startsWith()
endsWith()
判断是否包含某些字符contains()
子串substring()
格式化字符串format()
转换为字符数组toCharArray()
转换为数组,并存入指定数组getChars(),getBytes()
将基本数据类型转换为StringString.valueOf()
返回一个字符串为该字符串的大写形式toUpperCase()

返回一个字符串为该字符串的小写形式

toLowerCase()

 

//测试类
public class Test {
    public static void main(String[] args){
        String s1 = "sun java";
        String s2 = "Sun java";
        System.out.println(s1.charAt(1));//u
        System.out.println(s2.length());//8
        System.out.println(s1.indexOf("java"));//4
        System.out.println(s1.indexOf("Java"));//-1
        System.out.println(s1.equals(s2));//false
        System.out.println(s1.equalsIgnoreCase(s2));//true
        
        String s = "我是程序员,我在学习java";
        String sr = s.replace('我', '你');
        System.out.print(sr);  
    }    
}
//输出结果
//你是程序员,你在学习java

  方法public Strint[] split(String regex)可以将一个字符串按照指定的分隔符分割,返回分隔后的字符串数组

//测试类
public class Test {
    public static void main(String[] args){
        
        int i = 123456;
        String sNumber = String.valueOf(i);
        System.out.println(“i是”+sNumber.length()+”位数”);
        String s = "Nice to meet you";
        String[] sPlit = s.split(" ");
        for(int k=0;k<sPlit.length;k++){
            System.out.println(sPlit[k]);
        }
    }    
}

//输出结果:

//i是7位数//Nice
//to
//meet
//you

2.StringBuffer类

  2.1概述

    1)我们如果对字符串进行拼接操作,每次拼接,都会构建一个新的String对象,既耗时,又浪费空间。而StringBuffer就可以解决这个问题

    2)StringBuffer是线程安全的可变字符序列
    3)StringBuffer和String的区别
      · 前者长度和内容可变,后者不可变。
            · 如果使用前者做字符串的拼接,不会浪费太多的资源。 

    StringBuffer类的常见构造方法:

StringBuffer()//创建一个不包含字符序列的“空”的StringBuffer对象
public StringBuffer(int capacity) //指定容量的字符串缓冲区对象
StringBuffer(String str)//创建一个StringBuffer对象,包含与String对象str相同的字符串序列

    重载方法     

      • public StringBuffer append(…)可以为该StringBuffer对象添加字符串序列,返回添加后的该StrintBuffer对象引用,例如:

  public StringBuffer append(String str)

  public StringBuffer append(StringBuffer sbuf)

  public StringBuffer append(char[] str)

  public StringBuffer append(char[] str,int offset,int len)

  public StringBuffer append(double d)

  public StringBuffer append(object obj)

  …

      • public StringBuffer insert(…)可以为该StringBuffer对象在指定位置插入字符串序列,返回修改后的该StringBuffer对象引用,例如:

public StringBuffer insert(int offset,String str)

public StringBuffer insert(int offset,double d)

      • public StringBuffer delete(int start,int end)可以删除从start开始到end-1为止的一段字符串序列,返回修改后的该StringBuffer对象引用
      • 和String类含义类似的方法:

public int indexOf(String str)

public int indexOf(String str,int fromIndex)

public String substring(int start)

public String substring(int start,int end)

public int length()

      • public StringBuffer reverse()用于将字符序列逆序,返回修改后的该S他ringBuffer对象引用
        public class StringBufferDemo1 {
            public static void main(String[] args) {
                //String --> StringBuffer
                String s = "hello";
                // 注意:不能把字符串的值直接赋值给StringBuffer
                // StringBuffer sb = "hello";
                // StringBuffer sb = s;
                //方式一:通过构造方法
                StringBuffer sb = new StringBuffer(s);
                //方式二:通过append方法
                StringBuffer sb2 = new StringBuffer();
                sb2.append(s);
                System.out.println("sb:"+sb); //sb:hello
                System.out.println("sb2:"+sb2); //sb2:hello
                System.out.println("-------------------------");
                //StringBuffer --> String
                 StringBuffer buffer = new StringBuffer("java");
                //方式一:通过构造方法
                String str = new String(buffer);
                //方式二:通过toString()方法
                String str2 = buffer.toString();
                System.out.println("str:"+str); //str:java
                System.out.println("str2:"+str2); //str2:java
            }
        }
        public class StringBufferDemo2 {
        public static void main(String[] args){ String s = "Mircosoft"; char[] a = {'a','b','c'}; StringBuffer sb1 = new StringBuffer(s); sb1.append('/').append("IBM").append('/').append("Sun"); System.out.println(sb1); StringBuffer sb2 = new StringBuffer("数字: "); for(int i=0;i<=9;i++) { sb2.append(i); } System.out.println(sb2); sb2.delete(8, sb2.length()).insert(0, a); System.out.println(sb2); System.out.println(sb2.reverse()); } } //输出结果: //Mircosoft/IBM/Sun //数字: 0123456789 //abc数字: 0123 //3210 :字数cba

3.基本数据类型的包装类

  包装类(如:Iteger,Double等)这些类封装了一个相应的基本数据类型数值,并为其提供了一系列操作。实现int和Integer相互转换 ,Integer类通过构造方法将int装箱,通过intValue()方法进行拆箱。Java 1.5之后,Java支持自动装箱和拆箱。

  int与Integer区别 :

1、int是作为Java提供的8种原始数据类型之一;Integer是一个类。 
2、初始值不同。
int默认值是0;Integer默认值是null,即可以区分是否对其赋值。
1)在JSP中使用el表达式,Integer默认是null,不显示;而int会显示为0.
2)在Hibernate中使用Integer作为ID的类型,可以根据其是是否为null来判断这个对象是不是临时的。

 

  以java.lang.Integer为例;构造方法:

    • Integer(int value)
    • Integer(String s)

  常见的方法:

public static final int MAX_VALUE //最大的int型数(2的31次方-1)
public static final int MIN_VALUE //最小的int型数(-231)
public long longValu() //返回封装数据的long型值
public double doubleValue() //返回封装数据的double型值
public int intVlaue() //返回封装数据的int型值
public static int parseInt(String s) throwsNumberFormatException//将字符串解析成int型数据,并返回值
public static Integer valueOf(String s) shrows NumberFormatException //返回Integer对象,其中封装的整型数据为字符串s所表示

  实例:

public class Test {
    public static void main(String[] args){
        
       Integer i = new Integer(100);
          Double d = new Double("123.456");
          int j = i.intValue()+d.intValue();
          float f = i.floatValue()+d.floatValue();
          System.out.println(j); //223
          System.out.println(f); //223.456

        double pi = Double.parseDouble("3.1415926");
        double r = Double.valueOf("2.0").doubleValue();
        double s = pi * r * r;
        System.out.println(s);//12.5663704
        
        try { 
            int k = Integer.parseInt("1.25");
        } catch(NumberFormatException e ) {
            System.out.println("数据格式不对");//数据格式不对
        }
        System.out.println(Integer.toBinaryString(123)+"B");//1111011B
        System.out.println(Integer.toHexString(123)+"H");//7bH
        System.out.println(Integer.toOctalString(123)+"O");//173O
    }    
}

4.Math类

  Math类位于java.lang包中,提供了一系列静态方法用于科学计算;其方法的参数和返回值类型一般为double型

  常用的方法有:

abs //绝对值
cos//求余弦
sin//求正弦
tan//求正切
acos//求反余弦
asin//求反正弦
atan//求反正切
atan2(y,x)//求向量(x,y)与x轴夹角
sqrt //平方根
pow(double a,double b) //a的b次冥
log //自然对数
exp e //底指数
max(double a,double b) //最大值
min(double a,doublle b)//最小值
random() //返回0.0到1.0的随机数
long round(double a) //double型的数据a转换为long型(四舍五入)
toDegrees(double angrad) //弧度->角度
toRadians(double angdeg) //角度->弧度

  示例:

public class MathDemo {
    public static void main(String[] args){

        double i = Math.random();
        double j = Math.random();
        System.out.println(Math.sqrt(i*i+j*j));
        System.out.println(Math.pow(i, 8));
        System.out.println(Math.round(j));
        System.out.println(Math.log(Math.pow(Math.E,15 )));
        double d = 60.0 , r = Math.PI/4; 
        System.out.println(Math.toRadians(d));
        System.out.println(Math.toDegrees(r));

    }    
}

5.枚举类(Enum)

  Enum类位于java.lang包中,是枚举类型

    • 只能够取特定值中的一个
    • 使用enum关键字
    • 是java.lang.Enum类型

  枚举的意思其实就是事先定义一个范围,让程序在编译的时候就来检查你的变量、对象什么的是不是在这个范围内,而不是在执行的时候才发现 

要点:
使用的是enum关键字而不是class。
多个枚举变量直接用逗号隔开。
枚举变量最好大写,多个单词之间使用”_”隔开(比如:INT_SUM)。
定义完所有的变量后,以分号结束,如果只有枚举变量,而没有自定义变量,分号可以省略(例如上面的代码就忽略了分号)。
在其他类中使用enum变量的时候,只需要【类名.变量名】就可以了,和使用静态变量一样。

  简单的示例:

public class EnumDemo {
    public enum color {red, green, blue,yellow,black};    
    public static void main(String[] args){
        color c = color.black;
        switch (c) {
            case red:
                System.out.println("red");
                break;
            case green:
                System.out.println("green");
                break;
            case yellow:
                System.out.println("yellow");
                break;
            case black:
                System.out.println("black");
                break;
            default:
                System.out.println("default: blue");
                break;
        }        
    }    
}

  再看一个自定义的Enum实例:

public enum Weekday {
    SUN(0),MON(1),TUS(2),WED(3),THU(4),FRI(5),SAT(6);
    private int value;
    private Weekday(int value){
        this.value = value;
    }
    public static Weekday getNextDay(Weekday nowDay){
        int nextDayValue = nowDay.value;
        if (++nextDayValue == 7){
            nextDayValue =0;
        }
        return getWeekdayByValue(nextDayValue);
    }
    public static Weekday getWeekdayByValue(int value) {
        for (Weekday c : Weekday.values()) {
            if (c.value == value) {
                return c;
            }
        }
        return null;
    }
}

class Test2{
    public static void main(String[] args) {
        System.out.println("nowday ====> " + Weekday.SAT);
        System.out.println("nowday int ====> " + Weekday.SAT.ordinal());
        System.out.println("nextday ====> " + Weekday.getNextDay(Weekday.SAT)); // 输出 SUN
        //输出:
        //nowday ====> SAT
        //nowday int ====> 6
        //nextday ====> SUN
    }
}

6.File类

  java.io.File类代表系统文件名(路径和文件名)

  Java.io.File类主要是完成了文件夹管理的命名、查询文件属性和处理目录等到操作它不进行文件夹内容的读取操作

  常见构造方法:

public File(String pathname)//以pathname为路径创建File对象,如果pathname是相对路径,则默认的当前路径在系统属性user.dir中存储
public File(String parent,String child)//以parent为父路径,child为子路径创建File对象

  File的静态属性String separator存储了当前系统的路径分隔符(windows下是反斜杠,linux下是正斜杠,为了跨平台使用,事实上,在windows上使用正斜杠也是可以的)

  常见方法:

//通过file对象可以访问文件的属性
public boolean canRead()//返回文件是否可读
public boolean canWrite()//返回文件是否可写
public boolean exists()//查看文件是否存在public boolean isDirectory()//判断该路径指示的是否是文件
public boolean isFile()//判断该路径指示的是否是文件
public boolean isHidden()//是否隐藏的
public long lastModified()//上次修改时间(从创建到目前为止过了多少毫秒)
public long length()//返回文件长度
public String getName()//返回文件名称
public String getPath()//返回文件的潜在相对路径
//通过file对象创建空文件或目录(在该对象所知的文件或目录不存在的情况下)
public boolean createNewFile() throws IOException
public boolean delete()//从文件系统内删除该文件
public boolean mkdir()//生成指定的目录
public boolean mkdirs() //创建在路径中的一些列路径

  创建一个文件示例:

public class FileTest {
    public static void main(String[] args) throws IOException {
        File file = new File("D:/java/file.txt");
        File directory = new File("D:/java/hk");
        File dir = new File("D:/java/hu/file.txt");
        if (!directory.exists()) {
            System.out.println(directory.mkdir());
        }
        if (!dir.exists()) {
            System.out.println(dir.mkdirs());
        }
        if (!file.exists()) {
            System.out.println(":" + file.createNewFile());
        }
    }
}

 

实现int和Integer相互转换 
Integer类通过构造方法将int装箱,通过intValue()方法进行拆箱。

转载于:https://www.cnblogs.com/hh2012/p/10007696.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值