码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA学习第二十八课(常用对象API)- String类

时间:2014-10-14 02:52:17      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:style   color   ar   java   strong   sp   on   html   new   

多线程告一段落,开始常用对象API的涉及,背也要背下来!!!

日后开发,遇见最多的对象是文字,也就是字符串

String类

字符串是一个特殊对象

字符串一旦初始化就不可以被改变


一、特点

public class Main {
	public static void main(String[] args)
	{
		Demo1();
		System.out.println("--------------");
		Demo2();
	}
	/*演示字符串的第一种定义方式,并明确字符串常量池的特点*/
	private static void Demo1()
	{
		String s1 = "asd";
		s1 = "sd";//s1只是字符串的引用,而字符串“asd”本身不变
		String s2 = new String("sdf");
		System.out.println(s1);
		s2 = "sd";
		System.out.println(s2==s1);//s1 和 s2实际上指向的同一个地址值
		//sd储存在缓冲区(字符串常量池)
		//如果没有,就创建,没有就不创建
	}
	/*演示字符串的第二种定义方式,*/
	public static void Demo2() 
	{
		String s = "abc";//在字符串常量池中创建一个对象
		String s1 = new String("abc");//没有在字符串常量池中创建,在堆内存创建对象两个对象
		//一个是s1 一个“abc”
		System.out.println(s == s1);//false,比较的地址值不一样
		System.out.println(s.equals(s1));//true
		/*String类中的equals复写了Object中的equals建立了String类
		 * 自己的判断字符串对象是否相同
		 * 也就是比较字符串内容*/
		System.out.println("s = "+s);
		System.out.println("s1 = "+s1);
	}
}

二、构造函数

public class Main
{
	public static void main(String[] args)
	{
		StringconstructorDemo1();
		charDemo();
	}
	public static void StringconstructorDemo1()
	{
		String s = new String(); // 等效于String s = "";地址值不一样,不等效String s = null
		byte[] sub = {97,66};
		String s1 = new String(sub);
		System.out.println("s1 = "+s1);
	}
	public static void charDemo()
	{
		char[] ch = {'a','b','c','d','e','f'};
		String string = new String(ch);//将数组变成字符串,只能是byte 和 char
		System.out.println("string = "+string);
		
		String string1 = new String(ch,0,3);//从0角标开是截取3个字符
		System.out.println("string1 = "+string1);
		//String类剩下的方法,查手册
	}
	

未完。。。。



JAVA学习第二十八课(常用对象API)- String类

标签:style   color   ar   java   strong   sp   on   html   new   

原文地址:http://blog.csdn.net/wjw0130/article/details/40056575

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!