黑马程序员_JavaSE基础知识总结十一:常用类

------ android培训java培训、期待与您交流! ----------


一、Object类

类 Object 是类层次结构的根类,每个类都使用 Object 作为超类,所有对象(包括数组)都实现这个类的方法。 

1,boolean equals(Object obj):

用于比较两个对象是否相等,其实内部比较的就是两个对象地址。而根据对象的属性不同,判断对象是否相同的具体内容也不一样。所以在定义类时,一般都会复写equals方法,建立本类特有的判断对象是否相同的依据。

public boolean equals(Object obj){

	if(!(obj instanceof Person))

		return false;

	Person p = (Person)obj;

	return this.age == p.age;

}

2,String toString():将对象变成字符串;默认返回的格式:类名@哈希值 = getClass().getName() + '@' + Integer.toHexString(hashCode())

为了对象对应的字符串内容有意义,可以通过复写,建立该类对象自己特有的字符串表现形式。 

public String toString(){

return "person : "+age;

}

3,Class getClass():获取任意对象运行时的所属字节码文件对象。

4,int hashCode():返回该对象的哈希码值。支持此方法是为了提高哈希表的性能。


二、String类

1、String  String , 

<span style="font-size:18px;color:#333333;">public class StringTest01 {
	public static void main(String[] args) {
		String s1 = "a";
		String s2 = "b";
		s1 = s1 + s2; // ab
		// new String(“a”);
		System.out.println(s1);
	}
}</span>

从以上内存图,大家可以看到,String 对象赋值后不能再修改,这就是不可变对象,如果对字符串修改,那么将会创建新的对象

注意:只要采用双引号赋值字符串,那么在编译期将会放到方法区中的字符串的常量池里,如果是运行时对字符串相加或相减会放到堆中(放之前会先验证方法区中是否含有相同的字符串常量,如果存在,把地址返回,如果不存在,先将字符串常量放到池中,然后再返回该对象的地址)

2、String s1 = “abc”和String s2 = new String(“abc”)

<span style="font-size:18px;color:#333333;">public class StringTest02 {
	public static void main(String[] args) {
		String s1 = "abc";
		String s2 = "abc";
		String s3 = new String("abc");
		System.out.println("s1==s2, " + (s1 == s2));
		System.out.println("s2==s3, " + (s2 == s3));
		System.out.println("s2 equlas s3," + (s2.equals(s3)));
	}
}</span>

注意:①如果是采用双引号引起来的字符串常量,首先会到常量池中去查找,如果存在就不再分配,如果不存在就分配,常量池中的数据是在编译期赋值的,也就是生成class 文件时就把它放到常量池里了,所以s1 s2 都指向常量池中的同一个字符串“abc

关于s3s3 采用的是new 的方式,在new 的时候存在双引号,所以他会到常量区中查

找“abc”,而常量区中存在“abc”,所以常量区中将不再放置字符串,而new 关键子会

在堆中分配内存,所以在堆中会创建一个对象abcs3 会指向abc

如果比较s2 s3 的值必须采用equalsString 已经对eqauls 方法进行了覆盖

2、String面试题分析

面试题①

String s1 = new String("hello") ;

String s2 = new String("hello") ;

问:以上代码创建了几个对象?

以上代码创建了个对象,堆区中个,常量池中使用String 时,不建议使用new 关键字,因为使用new 会创建两个对象记住:堆区中是运行期分配的,常量池中是编译器分配的

面试题②

下面这条语句一共创建了多少个对象:String s = “a”+“b”+”c”+”d”; 为什么?

一个, 字符串常量相加时先相加,然后为s开辟空间。

面试题③

<span style="font-size:18px;color:#333333;">class Demo {
	public void method(Object o) {
		System.out.println("Object Version");
	}

	public void method(String s) {
		System.out.println("String Version");
	}

	public static void main(String[] args) {
		Demo d = new Demo();
		d.method(null);
	}
}</span>

问:以上代码输出的结果是什么?

输出String Version,java运行机制认为当子类名作为形参和父类作为形参同时出现时,Java默认调用子类形参,把String s 换为Person p仍然输出String Version.

 

2、String常用方法简介

①获取功能

 *int length():获取字符串的长度。

 *char charAt(int index):获取指定索引位置的字符

 *int indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引。97和'a' 都是 表示'a'

 *int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引。

 *int indexOf(int ch,int fromIndex):返回指定字符在此字符串中从指定位置后第一次出现处的索引。

 *int indexOf(String str,int fromIndex):返回指定字符串在此字符串中从指定位置后第一次出现处的索引。

 *String substring(int start):从指定位置开始截取字符串,默认到末尾。

 *String substring(int start,int end):从指定位置开始到指定位置结束截取字符串。

②转换功能

 *byte[] getBytes():把字符串转换为字节数组。

 *char[] toCharArray():把字符串转换为字符数组。

 *static String valueOf(char[] chs):把字符数组转成字符串。

 *static String valueOf(int i):把int类型的数据转成字符串。

 *              valueOf(..)把里面的数据转换成字符串

 *String toLowerCase():把字符串转成小写。

 *String toUpperCase():把字符串转成大写。

 *String concat(String str):把字符串拼接。

3、使用String时的注意事项

因为String 是不可变对象,如果多个字符串进行拼接,将会形成多个对象,这样可能会造成内存溢出,会给垃圾回收带来工作量,如下面的应用最好不要用String

<span style="font-size:18px;color:#333333;">public class StringTest04 {
	public static void main(String[] args) {
		String s = "";
		for (int i = 0; i < 100; i++) {
			// 以下语句会生成大量的对象
			// 因为String 是不可变对象
			// 存在大量的对象相加或相减一般不建议使用String
			// 建议使用StringBuffer 或StringBuilder
			s += i;// s = s+i;
		}
	}
}</span>



三、StringBuffer 和StringBuilder

1、StringBuffer

StringBuffer 称为字符串缓冲区,它的工作原理是:预先申请一块内存,存放字符序列,如果字符序列满了,会重新改变缓存区的大小,以容纳更多的字符序列。

<span style="font-size:18px;color:#333333;">public class StringBufferTest01 {
	public static void main(String[] args) {
		StringBuffer sbStr = new StringBuffer();
		for (int i = 0; i < 100; i++) {
			// sbStr.append(i);
			// sbStr.append(",");
			// 方法链的编程风格
			sbStr.append(i).append(",");
			// 拼串去除逗号
			// sbStr.append(i);
			// if (i != 99) {
			// sbStr.append(",");
			// }
		}
		// 可以输出
		System.out.println(sbStr);
		System.out.println("");
		System.out.println(sbStr.toString());
		System.out.println("");
		// 去除逗号
		System.out.println(sbStr.toString().substring(0,
				sbStr.toString().length() - 1));
		System.out.println("");
		System.out.println(sbStr.substring(0, sbStr.length() - 1));
	}
}</span>

StringBuffer和String的区别

    String:字符串长度固定;内容不能改变;底层是一个长度固定的字符数组。

StringBuffer:长度可变,内容可以修改,底层是一个长度可变的字符数组。

 

2、StringBuffer的构造方法和一般方法

A:StringBuffer的构造方法:

public StringBuffer():构造一个其中不带字符的字符串缓冲区,其初始容量为 16 个字符。

    public StringBuffer(int capacity):构造一个不带字符,但具有指定初始容量的字符串缓冲区。

public StringBuffer(String str):指定字符串内容的字符串缓冲区对象。

 

B:StringBuffer的方法:

public int capacity():返回当前容量。理论值

public int length():返回长度(字符数)。 实际值

<span style="font-size:18px;color:#333333;">public class StringBufferDemo {
		      public static void main(String[] args) {
		    	//使用无参构造案例
				StringBuffer sb = new StringBuffer();
				System.out.println(sb);
				System.out.println("sb.capacity():"+sb.capacity());
				System.out.println("-------------------");
				
				StringBuffer(int capacity)
				StringBuffer sb = new StringBuffer(5);
				System.out.println(sb);
				System.out.println("sb.capacity():"+sb.capacity());
				
				StringBuffer(String str) 
				StringBuffer sb = new StringBuffer("helloworld");
				System.out.println(sb);
				System.out.println("sb.capacity():"+sb.capacity());
				System.out.println("sb.length():"+sb.length());
			}
public class StringBufferDemo {
		      public static void main(String[] args) {
		    	//使用无参构造案例
				StringBuffer sb = new StringBuffer();
				System.out.println(sb);
				System.out.println("sb.capacity():"+sb.capacity());
				System.out.println("-------------------");
				
				//StringBuffer(int capacity)
				StringBuffer sb = new StringBuffer(5);
				System.out.println(sb);
				System.out.println("sb.capacity():"+sb.capacity());
				
				//StringBuffer(String str) 
				StringBuffer sb = new StringBuffer("helloworld");
				System.out.println(sb);
				System.out.println("sb.capacity():"+sb.capacity());
				System.out.println("sb.length():"+sb.length());
			}
		}
</span>

3、StringBuffer的功能

①添加功能

public StringBuffer append(String str):(做拼接)

可以把任意类型数据添加到字符串缓冲区里面,并返回字符串缓冲区本身

public StringBuffer insert(int offset,String str):

在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身

②删除功能

public StringBuffer deleteCharAt(int index):

删除指定位置的字符,并返回本身;

public StringBuffer delete(int start,int end):

删除从指定位置开始指定位置结束的内容,并返回本身。

<span style="font-size:18px;color:#333333;">public class StringBufferDemo3 {
			      public static void main(String[] args) {
					   StringBuffer sb = new StringBuffer();
					   sb.append("hello").append("world");
					   System.out.println(sb);
					   //想把 world编程word:去除world中的l字符
					   //public StringBuffer deleteCharAt(int index)
				//System.out.println("sb.deleteCharAt(8):"+sb.deleteCharAt(8));
				  
			           //public StringBuffer delete(int start,int end):
					   System.out.println(sb.delete(5, sb.length()));
			      }
			}
</span>

③替换和反转功能

 *   StringBuffer的替换功能

 public StringBuffer replace(int start,int end,String str):

 

 从start开始到end用str替换,返回的是该字符串缓冲区本身

 *   StringBuffer的反转功能

 public StringBuffer reverse():

 字符串反转,返回的是该字符串缓冲区本身

<span style="font-size:18px;color:#333333;">public class StringBufferDemo4 {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		sb.append("helloJavaSe");
		System.out.println(sb);
		public StringBuffer replace(int start,int end,String str):
		StringBuffer sb2 = sb.replace(5, sb.length(), "world");
		System.out.println(sb2);
}	}</span>

④截取功能

public String substring(int start):                                        

从指定位置截取到末尾,生成一个新的字符串,其字符串缓冲区不会发生改变 

public String substring(int start,int end):                                

截取从指定位置开始到结束位置,包括开始位置,不包括结束位置    

<span style="font-size:18px;color:#333333;">			public class StringBufferDemo5 {
			       public static void main(String[] args) {
					   StringBuffer sb = new StringBuffer();
					   sb.append("woaimadongmei");
					   System.out.println(sb);
					   //截取public String substring(int start):
					   System.out.println("sb.substring(4):"+sb.substring(4));
				       System.out.println("sb:"+sb);
				       
				       //public String substring(int start,int end):
					   //截取madong
				 System.out.println("sb.substring(4,10):"+sb.substring(4, 10));
			       }
			}</span>

4、String和StringBuffer分别作为参数传递

<span style="font-size:18px;color:#333333;"> public class StringBufferTest4 {
	public static void main(String[] args) {
		String str = "hello";
		System.out.println("str: "+str); //hello
		change(str);
		System.out.println("str: "+str); //hello
		
		StringBuffer sb = new StringBuffer("Java");
		System.out.println(sb.toString());//Java
		change(sb);
		System.out.println(sb.toString());//Java哈哈
		
	}

	//StringBuffer作为参数传递,形式参数的改变对实现参数有影响
	private static void change(StringBuffer sb) {
		sb.append("哈哈");
	}

	//String作为参数传递, 形式参数的改变对实现参数没有影响, String它是一个字符  //串是常量;它们的值在创建之后不能更改
	private static void change(String str) {
		str = "12345";
	}
	
	
}</span>


5、StringBuffer和StringBuilder的区别

StringBuilder用法同StringBuffer,StringBuilder 和StringBuffer 区别是StringBuffer 中所有的方法都是同步的,是线程安全的,但速度慢,StringBuilder 的速度快,但不是线程安全的

 

一、基本类型对应的包装类

1、包装类概述

基本类型的包装类主要提供了更多的实用操作,这样更容易处理基本类型。所有的包装类都final 的,所以不能创建其子类,包装类都是不可变对象

基本类型

包装类

byte

Byte

Short

Short

char

Character

int

Integer

Long 

Long

Float

Float

double

Double

boolean

Boolean

2、类层次结构

除了boolean Character 外,其它的包装类都有valueOf()parseXXX 方法,并且还具有byteVaue(),shortVaue(),intValue(),longValue(),floatValue()doubleValue()方法,这些方法是最常用的方法

<span style="font-size:18px;color:#333333;">public class IntegerTest01 {
	public static void main(String[] args) {
		int i1 = 100;
		Integer i2 = new Integer(i1);
		double i3 = i2.doubleValue();
		String s = "123";
		int i4 = Integer.parseInt(s);
		Integer i5 = new Integer(s);
		Integer i6 = Integer.valueOf(s);
	}
}</span>

3、JDK5.0的新特性

JDK5.0 以前,包装类和基本类型做运算时,必须将包装类转换成基本类型才可以, 而

JDK5.0 提供Auto-boxing/unboxing自动装箱和拆箱

自动将基础类型转换为对象

自动将对象转换为基础类型

<span style="font-size:18px;color:#333333;">public class IntegerTest01 {
	public static void main(String[] args) {
		// jdk1.5 以前版本,必须按如下方式赋值
		Integer i1 = new Integer(100);
		// jdk1.5 及以后版本支持
		// 自动装箱
		Integer i2 = 100;
		// jdk1.5 及以后版本支持
		// 自动拆箱
		int i3 = i2;
		// jdk1.5 以前版本,必须按如下方式赋值
		int i4 = i2.intValue();
	}
}</span>
<span style="font-size:18px;color:#333333;">/*
 * A:JDK5的新特性
		自动装箱:把基本类型转换为包装类类型
		自动拆箱:把包装类类型转换为基本类型
	B:案例演示
		JDK5的新特性自动装箱和拆箱
		Integer i = new Integer(100);可以直接写成
		Integer i = 100;//自动装箱
		i=i + 50;//自动拆箱,实际是一个intValue()
 */
public class IntegerDemo2 {
      public static void main(String[] args) {
    	  //Integer i = new Integer(100);
    	  Integer i = 100;//自动装箱
    	  /*
    	   * Integer i = Integer.valueOf(100);
    	   */
    	  
          i =i+50;
          /*
           * 执行i+50, i是Integer类型  会产生一个自动拆箱过程 会把i对象转换成基本数据类型
           * i+50----->i.intValue()+50 
           * i =(i+50)  将基本数据类型赋值给i对象  做了自动装箱
           */
	}
}</span>
<span style="font-size:18px;color:#333333;">package cn.itcast.Character;
/*
 *  A:Character类概述
		Character 类在对象中包装一个基本类型 char 的值
		此外,该类提供了几种方法,以确定字符的类别(小写字母,数字,等等),并将字符从大写转换成小写,反之亦然
	  B:构造方法
			public Character(char value)
      C:成员方法
        public static boolean isUpperCase(char ch)  是不是大写
		public static boolean isLowerCase(char ch)  是不是小写
		public static boolean isDigit(char ch)      是不是数字
		public static char toUpperCase(char ch)     转成大写
		public static char toLowerCase(char ch)     转成小写
      D:案例:
        统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)
 */
public class CharacterDemo {
       public static void main(String[] args) {
		       String huluwa = "JINGang1345hu22luwawawa";
		       countChar(huluwa);
	   }

	private static void countChar(String str) {
		  //判断传递过来的字符串中 大写,小写,数字出现次数
		  int numCount = 0;
		  int bigCount = 0;
		  int smaCount = 0;
		  
		  //遍历
		  for (int i = 0; i < str.length(); i++) {
			  char c = str.charAt(i);
		    if (Character.isDigit(c)) {
				numCount++;
			} else if (Character.isUpperCase(c)) {
				bigCount++;
			}else if(Character.isLowerCase(c)){
				smaCount++;				
			} 	
		  }
		  System.out.println("大写字母有:"+bigCount+"个,小写字母有"+smaCount+"个,数字有"+numCount+"个.");
		
	}
}</span>

4、面试题:看程序写结果

<span style="font-size:18px;color:#333333;">package cn.itcast.Integer;

public class IntegerTest {
        public static void main(String[] args) {
        	
        	Integer i1 = new Integer(127);
    		Integer i2 = new Integer(127);
    		System.out.println(i1 == i2);//false
    		System.out.println(i1.equals(i2));//true
    		System.out.println("-----------");

    		Integer i3 = new Integer(128);
    		Integer i4 = new Integer(128);
    		System.out.println(i3 == i4);//false
    		System.out.println(i3.equals(i4));//true
    		System.out.println("-----------");

            Integer.valueOf(127);//这里面有个 Integer缓冲区 范围是-128~127之间 ,
                                 //如果你要转换的int类型在这个范围内,系统就不在给你创建Integer对象,而是从缓冲区里拿对象

    		Integer i5 = 128;//隐含了  Integer.valueof(127)
    		Integer i6 = 128;//自动装箱
    		System.out.println(i5 == i6);//false
    		System.out.println(i5.equals(i6));//true
    		System.out.println("-----------");

    		Integer i7 = 127;
    		Integer i8 = 127;
    		System.out.println(i7 == i8);//false
    		System.out.println(i7.equals(i8));//true
		}
}</span>



五、日期类

常用日期类有java.util.Datejava.text.SimpleDateFormatjava.util.Calendar

<span style="font-size:18px;color:#333333;">import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class DateTest01 {
	public static void main(String[] args) throws Exception {
		// 取得今天的日期
		Date today = new Date();
		System.out.println(today);
		// 格式化日期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println(sdf.format(today));
		Calendar c = Calendar.getInstance();
		System.out.println(c.get(Calendar.DAY_OF_MONTH));
		// 取得2000-10-01 为星期几
		Date d = new SimpleDateFormat("yyyy-MM-dd").parse("2000-10-01");
		c.setTime(d);
		System.out.println(c.get(Calendar.DAY_OF_WEEK));
	}
}</span>

<span style="font-size:18px;color:#333333;">package cn.itcast.Date;

import java.util.Date;

/*
 *  A:Date类的概述
		类 Date 表示特定的瞬间,精确到毫秒。 
		
		
	B:构造方法
		public Date()
		public Date(long date)分配 Date 对象并初始化此对象,
		long类型的毫秒值
		这样定义构造什么意思呢?
		1970年1月1日8小时0分0秒+你输入毫秒值
	C:成员方法
	    public String toString()把此 Date 对象转换为以下形式的 String: 
 				dow mon dd hh:mm:ss zzz yyyy
		public long getTime();当前对象的时间的毫秒值减去基准时间的毫秒值的差值
		public void setTime(long time)
 */
public class DateDemo {
         public static void main(String[] args) {
			//创建Date对象
        	 Date d = new Date();//当前时间
       //Date d = new Date(60*1000);//1970年1月1日8小时0分0秒+你输入毫秒值
        	 System.out.println(d);
        	 
        	 //long time1 = d.getTime();
        	 //System.out.println(time1);
        	 
        	 //set
        	 //d.setTime(60*10000);
        	 //System.out.println(d);
        	 
        	 //当前时间的毫秒值
        	 System.out.println(d.getTime());
        	 
        	 System.out.println(System.currentTimeMillis());
        	 
		}
}</span>
<span style="font-size:18px;color:#333333;">import java.util.Calendar;

/*
 * Calendar类的概述
		Calendar 类是一个抽象类,它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 
		等日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。
	B:成员方法
		public static Calendar getInstance() 获取到一个日历类对象
		public int get(int field)获取对应的日历字段
		
		A:成员方法
		public void add(int field,int amount)
		public final void set(int year,int month,int date)
 */
public class CalendarDemo {
     public static void main(String[] args) {
		 //创建了一个日期类引用  
//    	 Calendar  c = Calendar.getInstance();
//    	 
//    	 int year = c.get(Calendar.YEAR);
//    	 System.out.println(year);
//    	 int month = c.get(Calendar.MONTH)+1;
//    	 System.out.println(month);
//    	 int day = c.get(Calendar.DAY_OF_MONTH);
//    	 System.out.println(day);
    	 
    	 Calendar c = Calendar.getInstance();
    	 
    	 //c.add(Calendar.DAY_OF_MONTH, -5);//往前推五天
    	 //c.add(Calendar.YEAR, 5);//正数是往后推
    	 c.set(2015,11,11);
    	 int year = c.get(Calendar.YEAR);
    	
    	 int month = c.get(Calendar.MONTH);
    	 
    	 int day = c.get(Calendar.DAY_OF_MONTH);
    	 
    	 int week = c.get(Calendar.WEDNESDAY);
    	 System.out.println(week);
    	
    	 
    	 System.out.println(year+"年"+month+"月"+day+"日");
		   
		  
	}
}</span>
<span style="font-size:18px;color:#333333;">import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
 *  DateFormat类的概述
		DateFormat 是日期/时间格式化子类的抽象类,它以与语言无关的方式格式化并解析日期或时间。
		是抽象类,所以使用其子类SimpleDateFormat
	B:SimpleDateFormat构造方法
		public SimpleDateFormat()
		public SimpleDateFormat(String pattern)
    c:  public final String format(Date date)
		public Date parse(String source)
		
		"2015年11月11日 11:11:11"
		
		y  年
		M  月
		d  日
		H  时
		m  分
		s  秒
 */
public class SimpleDateFormatDemo {
	public static void main(String[] args) throws ParseException {
		//以下代码将日期变成了字符串的展示格式
		//Date---->String
		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat();
		//对日期做格式化
		String format = sdf.format(d);
		System.out.println(format);
		
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		System.out.println(sdf2.format(d));
		
		//String ----Date
		String time = "2015-11-11 11:11:11";
		
	    Date parse = sdf2.parse(time);
		System.out.println(parse);
		
	}

}
</span>


六、数字类

主要有BigIngetet、Java.text.DecimalFormat java.math.BigDecimal

<span style="font-size:18px;color:#333333;">package cn.itcast.BigIngeter;

import java.math.BigInteger;
/*
 *      public BigInteger add(BigInteger val)   加
		public BigInteger subtract(BigInteger val)  减
		public BigInteger multiply(BigInteger val)  乘
		public BigInteger divide(BigInteger val)   除
		public BigInteger[] divideAndRemainder(BigInteger val)
 */
public class BigIngeterDemo {
      public static void main(String[] args) {
		//System.out.println(Integer.MAX_VALUE);
		//可以接收最大值
//		Integer i = new Integer(2147483647);
//		//Integer i2 = new Integer(2147483648);超出范围了
//		BigInteger b = new BigInteger("2147483648");
//		System.out.println(b);
    	BigInteger bi1 = new BigInteger("110");
  		BigInteger bi2 = new BigInteger("50");

  		System.out.println(bi1.add(bi2));//加法
  		System.out.println(bi1.subtract(bi2));//
  		System.out.println(bi1.multiply(bi2));
  		System.out.println(bi1.divide(bi2));//除法,得到的结果是商
  		BigInteger[] b = bi1.divideAndRemainder(bi2);
  		//做了除法  用数组存放商和余数   第一个存商,第二个存余数
  		System.out.println(b[0]);
  		System.out.println(b[1]);	
	}
}</span>
<span style="font-size:18px;color:#333333;">import java.math.BigDecimal;

/*
 * public BigDecimal add(BigDecimal augend)
 public BigDecimal subtract(BigDecimal subtrahend)
 public BigDecimal multiply(BigDecimal multiplicand)
 public BigDecimal divide(BigDecimal divisor)
 public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode)

 除完之后精确到小数点scale 位
 BigDecimal.ROUND_HALF_UP  四舍五入
 */
public class BigDecimalDemo {
	public static void main(String[] args) {

		// System.out.println(0.09 + 0.01);//0.10 0.1
		// System.out.println(1.0 - 0.32); //0.68
		// System.out.println(1.015 * 100);//101.5
		// System.out.println(1.301 / 100);//0.01301

		BigDecimal bd1 = new BigDecimal("0.09");
		BigDecimal bd2 = new BigDecimal("0.01");
		System.out.println(bd1.add(bd2));

		BigDecimal bd3 = new BigDecimal("1.0");
		BigDecimal bd4 = new BigDecimal("0.32");
		System.out.println(bd3.subtract(bd4));

		BigDecimal bd5 = new BigDecimal("1.015");
		BigDecimal bd6 = new BigDecimal("100");
		System.out.println(bd5.multiply(bd6));

		BigDecimal bd7 = new BigDecimal("1.991");
		BigDecimal bd8 = new BigDecimal("100");
		System.out.println(bd7.divide(bd8));

		// 1.301 100 2
		System.out.println(bd7.divide(bd8, 2, BigDecimal.ROUND_HALF_UP));
	}
}</span>
<span style="font-size:18px;color:#333333;">//示例代码:DecimalFormat
import java.text.DecimalFormat;

public class DecimalTest01 {
	public static void main(String[] args) throws Exception {
		// 加入千分位,保留两位小数
		DecimalFormat df = new DecimalFormat("###,###.##");
		System.out.println(df.format(1234.23452));
		// 加入千分位保留4 位小数,不够补零
		System.out.println(new DecimalFormat("###,###.0000").format(12345.12));
	}
}</span>
<span style="font-size:18px;color:#333333;">//示例代码:BigDecimal 可以精确计算,特别是财务数据
import java.math.BigDecimal;

public class BigDecimalTest01 {
	public static void main(String[] args) throws Exception {
		BigDecimal v1 = new BigDecimal(10);
		BigDecimal v2 = new BigDecimal(20);
		// 相加运算
		BigDecimal v3 = v1.add(v2);
		System.out.println(v3);
	}
}</span>



七、Random

Random 位于java.util 包下,可以产生随机数

<span style="font-size:18px;color:#333333;">package cn.itcast.Random;

import java.util.Random;

/*
 * 随机数
 * A:Random类的概述
		此类用于产生随机数如果用相同的种子创建两个 Random 实例,
		则对每个实例进行相同的方法调用序列,它们将生成并返回相同的数字序列。
	B:构造方法
		public Random() 使用默认的种子用来创建随即数对象的空参构造方法,
		(默认种子就是当前时间毫秒值)把一秒分成类1000
		public Random(long seed):使用指定的种子来创建随机数对象,
	C:方法:
	   public int nextInt()返回一个随机的int范围内的整数
	   public int nextInt(int n) 0~指定范围内的,包括0不包括指定数
	  
	//很多应用程序会发现 Math.random() 方法更易于使用。 
 */
public class RandomDemo {
         public static void main(String[] args) {
			//int范围
        	 System.out.println(Integer.MIN_VALUE);
        	 System.out.println(Integer.MAX_VALUE);
        	 //创建对象
        	 //Random r = new Random();
        	 //public Random(long seed):使用指定的种子来创建随机数对象,
        	 Random r = new Random(1111L);
        	 System.out.println("-------------");
        	 for (int i = 0; i < 10; i++) {
        		 //System.out.println(r.nextInt());
        		 //public int nextInt(int n)
        		 System.out.println(r.nextInt(100));
			}
        	 
		 }
}</span>




八、System类

1、System.exit使用

<span style="font-size:18px;color:#333333;">package cn.itcast.System;
/*
 * System类:
 *   public static final InputStream in;
 *         “标准”输入流。 做键盘录入
 *   out
		public static final PrintStream out
		“标准”输出流
		
		public static void exit(int status);
		退出JVM
		public static long currentTimeMillis()
 */
public class SystemDemo {
   public static void main(String[] args) {
//	     System.out.println("aaaaa");
//	     
//	     System.out.println("bbbbbbbbb");
//	     //System.exit(0);//退出JVM
//	     System.out.println("dddddddddd");
	     
	     //public static long currentTimeMillis()
	   long time1 = System.currentTimeMillis();
	   for (int i = 0; i < 10000; i++) {
		System.out.println("hello huluwa");
	    }
	   long time2 = System.currentTimeMillis();
	   System.out.println("该程序运行时间是:"+(time2-time1)+"毫秒");
   }
}</span>


2、System.gc使用

<span style="font-size:18px;color:#333333;">public class SystemDemo2 {
   public static void main(String[] args) {
	    Person p = new Person("葫芦娃",7);
	    
	    System.out.println(p);
	    p=null;
	    
	    System.gc();//呼喊垃圾回收器
	    
   }
}
package cn.itcast.System;

public class Person {
	private String name;
	private int age;

	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
   
	@Override
	protected void finalize() throws Throwable {
		System.out.println("收垃圾咯!!");
		super.finalize();
	}
}</span>



九、Enum

1、为什么使用枚举

<span style="font-size:18px;color:#333333;">//以下返回1 或0 存在问题
//在编译器就容易把程序错了,如:1 和111 没有什么区别,编译器认为两者是一样的
//不会报错,错误发现的越早越好,最好在编译器把所有的错误都消除掉
public class EnumTest01 {
	public static void main(String[] args) throws Exception {
		int ret = method1(10, 2);
		if (ret == 1) {
			System.out.println("成功!");
		}
		if (ret == 0) {
			System.out.println("失败!");
		}
	}

	// 正确返回1,失败返回:0
	private static int method1(int value1, int value2) {
		try {
			int v = value1 / value2;
			return 1;
		} catch (Exception e) {
			return 0;
		}
	}
}</span>
<span style="font-size:18px;color:#333333;">	//改进示例一
	//此种方式比第一种方案好一些
	//有一个统一的约定,成功用1 表示,失败采用0 标识
	//但是也存在问题,如果不准许约定也会产生问题
	//如果成功我们可以返回SUCCESS,但也可以返回100,因为返回值为int ,
	//并没有强制约束要返回1 或0
	public class EnumTest02 {
		private static final int SUCCESS = 1;
		private static final int FAILURE = 0;
		public static void main(String[] args) throws Exception{
		int ret = method1(10, 2);
		if (ret == SUCCESS) {
		System.out.println("成功!");
	}
		if (ret == FAILURE) {
		System.out.println("失败!");
	}
	}
	//正确返回1,失败返回:0
	private static int method1(int value1, int value2) {
	try {
	int v = value1/value2;
	return SUCCESS;
	}catch(Exception e) //采用枚举改进
	//使用枚举类型,能够限定取值的范围
	//使程序在编译时就会及早的返现错误
	//这样程序会更加健壮
	public class EnumTest03 {
	public static void main(String[] args) throws Exception{
	Result r = method1(10, 2);
	if (r == Result.SUCCESS) {
	System.out.println("成功!");
	}
	if (r == Result.FAILURE) {
	System.out.println("失败!");
	}
	}
	//正确返回SUCCESS,失败返回:FAILURE
	private static Result method1(int value1, int value2) {
		try {
		int v = value1/value2;
		return Result.SUCCESS;
		}catch(Exception e) {
		return Result.FAILURE;
		}
	}
	}
	enum Result {
	SUCCESS,FAILURE
}}</span>



























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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值