赵雅智_java java类

类库、应用程序的编程接口(Application Programming Interface,API):Java系统提供了大量的类和接口供程序开发人员使用,并且按照功能的不同,存放在不同的包中。

java API的概念:

  • java包的分类
    • Java的核心包(Java core package)
      1. java.lang包:Java语言包,主要包含与语言、数据类型相关的类。自动导入
      2. java.awt包和javax.swing包:提供了创建图形界面元素的类,通过这些类,可以控制应用程序的外观界
      3. java.io包:输入/输出包
      4. java.util包:实用程序包
      5. java.net包:网络包
      6. java.sql包:数据库编程相关的类/接口
    • Java的扩展包(Java extension package)

java.lang.Object类:

  • java.lang.Object类是所有Java类的最高层次父类。
  • 属性:没有定义任何属性
  • 方法
    1. toString()

        • 返回当前对象的有关信息(对象所属的类型名称以及对象的哈希码)。
        • 原始方法定义:
          public String toString(){
          	return getClass().getName()+"@"+integer.toHexString(hashCode());
          }
        • 测试Object类的toString()方法。
          class TestObject1 
          {
          	public static void main(String[] args) 
          	{
          		Object o = new Object();
          		System.out.println(o.hashCode());//十进制哈西码
          		System.out.println(Integer.toHexString(o.hashCode()));//十六进制哈西码
          		System.out.println(o.toString());//等于System.out.println(o)
          	}
          }
          

        • 可以根据需要在自己定义的Java类中重写toString()方法,以提供更适用的说明信息。
          class Car  
          {
          	String color;
          	String name;
          	public String toString(){
          		return "车的颜色是:"+color+"     车的名字是:"+name;
          	}
          }
          public class TestObject2
          {
          	public static void main(String[] args) 
          	{
          		Car c = new Car();
          		c.color = "红色";
          		c.name = "奥迪";
          		System.out.println(c);
          		System.out.println(c.toString());
          	}
          }
          车的颜色是:红色 车的名字是:奥迪
          车的颜色是:红色 车的名字是:奥迪
      1. equals()
        • 比较两个对象是否等价,非空引用值来说,同一个对象,返回true
        • 比较一些特定的引用类型(如String、java.io.File、java.util.Data以及封装类等)数据时,两个对象内容等价,返回为true。 
          String变量赋值内容相同的话,在内存中将只保存一份。
          String s1="abc"; String s2="abc"; //s1和s2指向同一对象
          System.out.println(s1==s2); //结果为true
        • “equals”和"==":
          class TestEquals 
          {
          	public static void main(String[] args) 
          	{
          		String s1 = new String("abc");
          		String s2 = new String("abc");
          		System.out.println(s1==s2);//f不是同一对象
          		System.out.println(s1.equals(s2));//t是同一内容
          		s2 = s1;
          		System.out.println(s1==s2);//t
          		System.out.println(s1.equals(s2));//t
          		
          		String s3 = "abc";
          		String s4 = "abc";
          		System.out.println(s3==s4);//t
          		System.out.println(s3.equals(s4));//t
          
          		String s5 = "abc";
          		String s6 = new String("abc");
          		System.out.println(s5==s6);//f
          		System.out.println(s5.equals(s6));//t
          	}
          }
          
          判断字符串数据是否相等时,适合用equals()
        • 子类String重写父类Object
      2. hashCode()
        • 返回当前对象的哈希码(HashCode)
        • 系统为每个Java对象自动创建的整型编号,任何两个不同的Java对象的哈希码一定不同,而在Java程序的一次执行期间,在同一对象上多次调用hashCode()方法时,必须一致返回相同的整数。
    字符串相关类型 

      1. java.lang.String
        • 表示的是16位Unicode编码字符组成的字符串,用于记录和操作文本信息
        • final,不可被继承,对象一经创建,内容不可改变
        • 构造方法
          1. public String()
          2. public String (byte[] bytes)
          3. public String(char[] value)
          4. public String(String original)
          5. public String(StringBuffer stringBuffer)
            class TestString1 
            {
            	public static void main(String[] args) 
            	{
            		byte[] b = {67,68,66,100,101};
            		System.out.println(new String(b));//=String s = new String(b);System.out.println(s);
            		char[] c = {'a','b','c','c','b','a'};
            		System.out.println(new String(c));
            		System.out.println(new String("Hello,World"));//System.out.println(new String(c));//String str3 = "abc";
            		System.out.println(new String("abc"));
            	}
            }
            CDBde
            abccba
            Hello,Word
            abc
        • 成员方法
          • 连接、转换、截断
            1. public String concat (String str)连接
            2. public String replace(char oldChar,char newChar)替换
            3. public String substring(int beginIndex)和public String substring(int beginIndex,endIndex):提取
            4. public String toLowerCase()小写
            5. public String toUperCase()大写
            6. public String trim()空格
              class TestString1 
              {
              	public static void main(String[] args) 
              	{
              		String str1 = "Java Application",str2="     and   Apples";
              		System.out.println(str1.trim().concat(str2));
              		System.out.println(str1.replace('A','a'));
              		System.out.println(str1.toUpperCase())
              		System.out.println(str2.toLowerCase())
              		System.out.println(str1.substring(5,8));
              	}
              }
              public int lastIndexOf(int ch)和public int lastIndexOf(String str):
              Java Application and Apples
              java application
              JAVA APPLICATION
              and Apples
              App

          • 检索和查找
            1. public char charAt(int index):返回指定索引位置的字符
            2. contains是否包含
            3. public boolean endsWith(String suffix)是否以子串结尾
            4. public boolean startsWidth(String prefix)是否以子串开头
            5. public int indexOf(int ch)和public int indexOf(String str):指定字符、串在当前字符串中出现的下标
            6. public int lastIndexOf(int ch)和public int lastIndexOf(String str): 最后一次出现的下标
            7. public int length()字符串长度
              class TestString3 
              {
              	public static void main(String[] args) 
              	{
              		String s = "java App and app";
              		for(int i=0;i<s.length();i++){
              			System.out.print(s.charAt(i));//java App and app
              	}
              	System.out.println();
              	System.out.println(s.startsWith("java"));//t
              	System.out.println(s.startsWith("va",2));//t
              	System.out.println(s.endsWith("app"));//t
              	System.out.println(s.indexOf("java"));//0
              	System.out.println(s.lastIndexOf("p"));//15
              	}
              }
              
              查找某字符串a出现的次数
              class findA 
              {
              	public static int getCount(String str){
              		int count = 0;
              		for(int i=0;i<str.length();i++){
              			char ch = str.charAt(i);
              			if(ch == 'a'){
              				count++;
              			}	
              		}return count;
              	}
              	public static void main(String[] args) 
              	{
              		String s = "java App and app";
              		int count = getCount(s);
              		System.out.println(count);//4
              	}
              }
              
              查找字符串中某个字符出现的次数
              class findA 
              {
              	public static int getCount(String str,char c){
              		int count = 0;
              		for(int i=0;i<str.length();i++){
              			char ch = str.charAt(i);
              			if(ch == c){
              				count++;
              			}	
              		}return count;
              	}
              	public static void main(String[] args) 
              	{
              		String s = "java App and app";
              		int count = getCount(s,'n');
              		System.out.println(count);//1
              	}
              }
              
              查找字符串中某子串出现的次数
              //1.定义一个计数器
              //2.获取查找字串出现的位置
              
              class  FindStr
              {
              	public static int getCountString(String str,String sub){
              	    int count=0;
              		int index=0;
              		while(true){
              			index=str.indexOf(sub,index); //defabcdefefabcdedf
              			if(index==-1){
              				break;
              			}
              			index=index+sub.length();
              			count++;
              		}
              		return count;
              	}
              	public static void main(String[] args) 
              	{
              		int count=getCountString("defabcdefefabcdedf","de");
              		System.out.println(count);
              	}
              }
              



          • 比较
            1. public boolean equals(Object anObject)等价性
            2. public boolean equalsIgnoreCase(String anotherString):忽略大小写
            3. public int compareTo(String anotherString)大小,按字典顺序
              class TestString4 
              {
              	public static void main(String[] args) 
              	{
              		String s1 = "Hello I am Javk";
              		String s2 = "Hello I am Javk";
              		String s3 = "Hello i am Javk";
              		System.out.println(s1.equals(s2));//t
              		System.out.println(s1.equalsIgnoreCase(s3));//t
              		System.out.println(s1.compareTo(s2));//0
              		System.out.println(s1.compareTo(s3));//-32
              	}
              }
              

          • 拆分
            1. public String[] sprit(String regex)正则表达式的匹配拆分字符串

      2. java.lang.StringBuffer
        • 内容可以修改的Unicode编码的字符序列,其对象创建之后,所保存的字符串内容和长度均可以修改。
        • 构造方法:
          1. public StringBuffer() ;不带字符的字符串缓冲区,16字符
          2. public StringBuffer(int capacity) :不带字符,指定容量
          3. public StringBuffer(String str)带字符,内容初始化为指定的字符内容
        • 常用方法:
          1. append() 追加
          2. insert() ; 指定位置
          3. reverse() ; 序列反转
          4. setCharAt ();指定位置替换
            import java.util.*;
            class  TestStringBuffer
            {
            	public static void main(String[] args) 
            	{
            		StringBuffer s = new StringBuffer("aaa");
            		System.out.println(s.append("bbb"));//aaabbb
            		System.out.println(s.insert(3,"+"));//aaa+bbb
            		System.out.println(s.reverse());//bbb+aaa
            		System.out.println(s.append(new Date()));//bbb+aaaMon......
            	}
            }
            

      java.lang.System

      • 类中所有成员都是静态的,当要引用这些变量和方法的时候,System.属性 System.方法()
      • exit(int x)方法:终止当前正在运行的JVM
      • currentTimeMillis()方法:返回毫秒数
        class TestSystem 
        {
        	public static void main(String[] args) 
        	{
        		long timeStart = System.currentTimeMillis();
        		long count = 0;
        		for(long i=0; i<100000000;i++){
        			count+=i;
        		}
        		long timeEnd = System.currentTimeMillis();
        		System.out.println("运行时间是:"+(timeEnd-timeStart));//运行时间是:47
        	}
        }

      java,lang.Runtime

      • 该类封装了Java命令本身所启动的实例进程信息---Java虚拟机进程。
      • 不能直接创建对象,通过Runtime.getRuntime()获得实例
        import java.io.*;
        class  TestRuntime
        {
        	public static void main(String[] args) 
        	{
        		try{
        			Runtime r = Runtime.getRuntime();//通过静态方法获得该类实例
        			Process p = r.exec("C:\\Windows\\System32\\Notepad.exe");//启动子进程,返回代表子进程的Person对象
        		}catch(IOException ex){
        			System.out.println(ex.toString());//打开一个记事本
        		}
        	}
        }

      封装类

      • 针对各种基本数据类型均提供了相应的引用数据类型
      • 由于基本类型数据不是对象,在有些场合其使用是受到限制的
        public void test(Object o){
        	System.out.println(o.toString());
        }//该方法可处理任何引用类型的数据,不能处理基本类型数据
        
      • java.lang包中引入
      • 基本数据类型与封装类的关系
        基本数据类型封装类
        intInteger
        charcharacter
        shortShort
        longLong
        byteByte
        floatFloat
        doubleDouble
        booleanBoolean

        封装类均被定义为final,不能被继承,内容不被改变,只读型

      • 每个Integer类的对象可以封装一个int型的整数值,该类中还提供了多个用于处理int型数据的功能方法。
        • 构造方法
          1. public Integer(int value) :封装参数value指定的int型数值//Integer i1=new Integer(123);
          2. public Integer(String s)throws NumberFormatEcception:0-9数字组成//Integer i2=new Integer(“123”);
        • 其它常用方法
          1. public int intValue():内容
          2. public boolean equals(Object obj); :比较(内容、对象)
          3. public String toString();:int型数值转换成字符串。等于String中的ValueOf(int i)
          4. public static String toString(int i);:参数i指定的int型数值以字符串的形式返回。
          5. public static String toBinaryString(int i);将i指定的int型数值的二进制无符号整数表示以字符串形式返回。
          6. public static String toOctalString(int i);:8
          7. public static String toHexString(int i);:16
          8. public static int parseInt(String s) throws NumberFormatException;:字符串转换成整型。
            class TestWrapper 
            {
            	public static void main(String[] args) 
            	{
            		Integer int1=new Integer(786);//串---int
            		Integer int2=new Integer("786");
            		int i = int1.intValue();//串---int
            		System.out.println(i);//786//串---int
            
            		System.out.println(int1==int2);//f
            		System.out.println(int1.equals(int2));//t
            		i=Integer.parseInt("777"); //串---int
            		System.out.println(i);//777串---int
            
            		System.out.println(Integer.toHexString(-1));//ffffffff
            		System.out.println(String.valueOf(i)); //===将参数d转化为字符串的形式返回 777
            		System.out.println(Integer.toString(i));// ===将整型i转换为字符串的形式返回777
            	}
            }
      • 自动封装/拆封
        • 基本数据类型值和其对应的包装类对象之间完成自动转换的过程
          class TestAutoBoxing 
          {
          	public static void main(String[] args) 
          	{
          		int j = 4;
          		Integer obj1 = j;//自动封装
          		Integer obj2 = new Integer(3);//自动拆封
          		int i = obj2;
          
          		System.out.println(i);
          		System.out.println(obj1.toString());
          	}
          }
          //自动封装
          Integer obj1;   
          int num1=33;                              
          obj1=num1;  
          //自动拆封
          Integer obj2=new Integer(22);
          intnum2;
          num2=obj2
        • 自动封装/拆封中,隐含的调用了有关封装类的构造方法和解析方法。
        • Integer obg1 = j --->Integer obj1 = new Integer(j);
        • 任何需要封装类型数据的场合,均可使用相应的基本数据类型代替

      日期

      • Data类
        • 构造方法
          1. public Date() Date d2 = new Date();
          2. public Date(long date) Date d1 = new Date(20000);
        • 常用方法
          1. public int compareTo(Date anotherDate) :比较前后顺序
          2. public boolean equals(Object obj) :等价性
          3. public long getTime() :返回自基准时间点到当前时刻(当前对象表示的时间点)所经历的毫秒数
          4. public String toString() :将当前时刻转换为字符串形式返回,其格式为:“星期 月份 日期 小时:分钟:秒 时区 年份”
            import java.util.*;
            class  TestDate
            {
            	public static void main(String[] args) 
            	{
            		Date d1 = new Date(20000);
            		long time = d1.getTime();
            		System.out.println(time);//20000
            		System.out.println(d1);//系统日期,1097。。。
            
            		Date d2 = new Date();
            		System.out.println(d2.getTime());//毫秒数
            		System.out.println(d2);//今天日期
            
            		System.out.println(d2.compareTo(d1));//1
            		System.out.println(d1.equals(new Date(20000)));//t
            	}
            }
            

      • Calendar类
        • java.util.Calendar类是Date类的一个增强版,该类提供了常规的日期修改功能和国际化支持,以及对日历操作提供方便。
        • Calendar类是一个抽象类,可以调用其静态方法getInstance()来获得该类的实例(实际上是其子类的实例):Calendar c=Calendar.getInstance();
        • 常用类:
          • public void set(int field,int value) 将参数field指定的时间域(年、月、日、时、分、秒等)设置为参数value指定的值。field可为:Calendar.YEAR、Calendar.MONTH、Calendar.HOUR等
          • public final void set(int year,int month,int date) 
          • public final void set(int year,int month,int date,int hourOfDay,int minute)
          • public final void set(int year,int month,int date,int hourOfDay,int minute,int second) 
          • public final Date getTime():返回一个表示此时间值的Date对象
          • public final get(int field):当前日历指定时间域的值
          • public abcstract void add(int field,int amount) 为当前日历的指定时间域添加或减去指定的时间量。
            import java.util.*;
            class  TestCalendar
            {
            	public static void main(String[] args){
            		Calendar c = Calendar.getInstance();
            		display(c);
            		c.set(Calendar.YEAR,2009);
            		c.set(Calendar.MONTH,4);
            		c.set(Calendar.DATE,30);
            		display(c);
            		c.set(2009,8,12);
            		display(c);
            		c.set(2009,8,12,10,23,15);
            		display(c);
            		c.set(Calendar.MONTH,2);
            		display(c);
            		Date d = c.getTime();
            		System.out.println(d);
            	}
            	public static void display(Calendar c){
            		String s = c.get(Calendar.YEAR)+"年"+(c.get(Calendar.MONTH)+1)+"月"+c.get(Calendar.DATE)+"日"+c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND)+" "+(c.get(Calendar.AM_PM)==0?"上午":"下午");
            		System.out.println(s);
            	}
            }
            

        • 需注意:
          1. 属性Calender.HOUR标记的时间域“小时”是12小时制的,要想获得24小时制的数值,则必须使用Calender.HOUR_OF_DAY来标记。
          2. 从Calender获取的月份信息值是从0开始的,即一月份的时间域获取值为0,因此display方法中将该字段的值加1已以得到实际的月份数。
      • DateFormat类
        • java.text.DateFormat类提供了将日期/时间信息进行格式化处理的功能,主要是将日期/时间信息(Date类型数据)转换成人们所习惯的格式字符串以及反向转换的功能。
        • 主要方法:
          1. public static final DateFormat getDateInstance() 获得一个具有默认语言环境、默认格式化风格的DateFormat对象。
          2. public static final DateFormat getDateInstance(int style,Locale aLocale)获得具有给定语言环境、给定格式化风格的DateFormat对象。
          3. public static final DateFormat getTimeInstance() 获取具有默认语言环境、默认格式化风格的日期/时间DateFormat对象。
          4. public final String format(Date date) 将一个Date对象格式化为日期/时间字符串。
          5. DateFormat类中定义了相应的整型常量来标识各种转换风格,包括:DateFormat.SHORT、DateFormat.MEDIUM、DateFormat.LONG、DateFormat.FULL。
            例7.18 DateFormat类的使用。
      • SimpleDateFormat类
        • java.text.SimpleDateFormat类是DateFormat类的子类,它方便用户自己定义日期、时间表示格式,并提供更灵活的日期和字符串信息转换和解析的功能。
          例7.19 SimpleDateFormat类的使用。 
          Locale locale1; SimpleDateFormat sdf1,sdf2; 
          Date d=new Date(); locale1 = new Locale("zh","CN");
          sdf1 = new SimpleDateFormat();
          sdf2 = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
          System.out.println(sdf2.format(d));
        • 注意:
          1. 模式串中可以包含模式符以外的字符或字符串,如“年”、“月”、“日”等字符,这些字符或字符串在转换过程中将被原样保留;
          2. 如果要在模式串中包含字母(a~z,A~Z)且不希望其被当做模式符转换掉,则可以将其用半角单引号“‘”括起来;
          3. 由于单引号已被用作分隔标记,如果在模式串中要作为普通字符来包含它,就需要使用两个连续的半角单引号(“''”,注意这不同于一个双引号)来代替。例如,"'On' yyyy-MM-dd HH 'o''clock,We tesed it.'"

      基本数学功能类Math

      • 属性和方法均被定义为public和static的,因此不需要创建Math的实例即可直接访问或调用
      • 常用方法:
        • 随机数:
          • public static double random() 生成double型随机数,其取值区间为[0.0,1.0)
            例如,int i=(int)(Math.random()*100);
        • 数据截断:
          1. public static double ceil (double a):
          2. public static double floor (double a):
          3. public static long round (double a):
        • 最大最小值:
          1. public static int max (int a,int b):
          2. public static int min (int a,int b):
          3. public static int/float/long/double abs (int /float/long/double a):
        • 三角函数
          1. sin()、cos()、tan()
          2. asin()、acos()、atan():
          3. public static double toDegrees (double degrees):
          4. public static double toRadians(double degrees):
        • 幂运算和对数运算
          1. public static double pow(double a,double b):
          2. public static double exp(doubloe a):
          3. public static double sqrt(doubloe a):
          4. public static double log(doubloe a):
          5. public static double log10(doubloe):
        • 常量
          1. public static double PI:
          2. public static double E:
      • 数据格式化工具类
        • java.text.NumberFormat:所有数据格式的抽象基类
          1. public static final NumberFormat getInstance() 返回当前默认语言环境的通用数字格式对象。
          2. public static NumberFormat getInstance(Locale intLocale) 返回指定语言环境的通用数字格式对象。
          3. public final String format(double number) 格式化指定的数据,返回格式化字符串。
          4. public static final NumberFormat getCurrencyInstance() 返回默认语言环境的货币格式对象。
          5. public static final NumberFormat getCurrencyInstance(Locale inLocale) 返回默认语言环境的货币格式对象。
          6. public static final NumberFormat getPercentInstance() 返回当前默认语音那环境的百分比格式对象。
          7. public static NumberFormat getPercentInstance(Locale inLocale)返回指定语言环境的百分比格式对象。
            例7.20 使用NumberFormat格式化数字举例。
            例7.21 格式化货币和百分比数据。
        • java.text.DecimalFormat:格式化十进制数据字符串表示形式。
          1. public DecimalFormat() 使用默认模式语言环境创建DecimalFormat对象
          2. public DecimalFormat(String pattern) 给定模式和默认语言环境创建DecimalFormat对象
          3. public final String format(double number):
          4. public Number parse(String source) throws ParseException:
            例7.22 DecimalFormat类用法举例。

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

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

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

      请填写红包祝福语或标题

      红包个数最小为10个

      红包金额最低5元

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

      抵扣说明:

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

      余额充值