Day 7 – Object, String, StringBuffer.

news/2024/7/24 11:58:59 标签: runtime, python, java

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

Today I learned about Object class, String, StringBuffer, StringBuilder.

Object class:

The most common methods which are applicable for any java object are defined in Object class, it acts as root for all java classes.

There are 11 methods in Object class, I am going to explain about some.

1. toString():

We use this method to get String representation of an object, if our class do not contain a toString() method then Object class toString() executes.

java">class Student 
{
	String name;
	int rollno;
	Student(String name, int rollno)
	{
		this.name = name;
		this.rollno = rollno;
	}
	public static void main(String[] args) 
	{
		Student s1 = new Student("sri",476);
		Student s2 = new Student("Mohan",467);
		System.out.println(s1); // We did not override toString() hence Object class toString() is called
		System.out.println(s2);
	}}
/* the output is 
Student@1c78e57
Student@5224ee
*/




In the above example Object class toString() is executed which returns Classname@hexadecimalString_representation_of_hashcode.

In String classes, StringBuffer, all Wrapper classes, all Collection classes toString() is overridden for meaningful representation of an object.

Now lets override toString() in our class to return name.

java">class Student 
{
	String name;
	int rollno;
	Student(String name, int rollno)
	{
		this.name = name;
		this.rollno = rollno;
	}
	public String toString()
	{
		return name;
	}
	public static void main(String[] args) 
	{
		Student s1 = new Student("sri",476);
		Student s2 = new Student("Mohan",467);
		System.out.println(s1); // We did not override toString() hence Object class toString() is called
		System.out.println(s2);
	}}
/* the output is 
sri
Mohan
*/




2. hashCode():

For every object JVM will generate a unique number which is known as hashcode.JVM will use this hashcode while saving objects into  hashing related datastructures like hashset, hashmap, hashtable.

We can override hashCode() based on our requirement but its good if we have a unique number as hashcode for every object.

If in our class, object class toString() executes then it calls hashCode() internally.

Lets override hashCode() in the below example and observe the output.

java">class Test 
{
	int i;
	Test(int i)
	{
		this.i = i;
	}
	public int hashCode()
	{
		return i;
	}
	public static void main(String[] args) 
	{
		Test t1 = new Test(10);
		Test t2 = new Test(100);
		System.out.println(t1);//Test@a
		System.out.println(t2);//Test@64
	}}




You can observe that output for t1 is Test@a , since we overridden hashCode in our class to return i , toString() internally calls our hashCode() in place of Object class hashCode().

3. equals()

Object class equals() is used for reference comparision. In String , Wrapper, Collection classes .equals() is overridden for content comparison, but in StringBuffer class .equals() isn’t overridden hence even if both objects are equal .equals() returns false.

java">class Test1 
{
	public static void main(String[] args) 
	{
		String s1 = new String("harsha");
		String s2 = new String("harsha");
		System.out.println(s1.equals(s2)); //true
                System.out.println(s1.hashCode() == s2.hashCode());//true 
 
		StringBuffer a1 = new StringBuffer("harsha");
		StringBuffer a2 = new StringBuffer("harsha");
		System.out.println(a1.equals(a2)); //false
                System.out.println(a1.hashCode() == a2.hashCode());//false
	}}




If two objects are equal by .equals() then their hashcodes are equal.

String

Strings are Immutable i.e., once we create any String object then we cannot make any changes to it, if we make any then with those changes a new object will be created this is known as Immutability.

java">class StringDemo 
{
	public static void main(String[] args) 
	{
		String s1 = new String("harsha");
		s1.concat(" solutions");
		String s2 = s1.concat("innovations!");
		s1.concat("soft");
		System.out.println(s2);
		System.out.println(s1);
	}}




In above example eight objects are created, 4 in heap and 4 in SCP.

In Heap:

“harsha” is created and assigned to s1, “harsha solutions” is created in heap and has no reference, now “harsha innovations” is created and is assigned to s2 and at last “harsha soft” is also dynamically created and eventually lost as it has no reference.

In String Constant Pool:

“harsha”, “solution”,”innovations”,”soft” are created.

Some points you need to know about Strings

  • Garbage collector is not allowed to access SCP area, i.e.,even though the object do not contain any reference variable its not eligible for GC.
  • For every String constant one object will be created in SCP.
  • Object creation is optional in SCP, first JVM will check if any object is present with SCP with same content, if any match is found then its reused and if no match is found then new object is created.
  • If we use “new” operator then compulsorily an object will be created in Heap.
  • Due to Runtime operation if an object is to be created then it is done in Heap not in SCP.
  • Existence of duplicate objects in SCP is not possible.
java">class StringDemo2 
{
public static void main(String[] args) 
	{
		String s1 = new String("I am the boss!");
		String s2 = new String("I am the boss!");
		System.out.println(s1 == s2); //false
		//since s1 and s2 are two different objects created in heap.
		String s3 = "I am the boss!";
		System.out.println(s1 == s3); //false
		//since s1 is an object created in heap and s3 is object created in SCP.
		String s4 = "I am the boss!";
		System.out.println(s3 == s4);//true
		//s3 and s4 points to same object in SCP, since duplicate objects are not allowed in SCP.
		String s5 = "I am" +" the boss!";
		System.out.println(s3 == s5);//true
		//for runtime operation, a new object will be created in heap and the above isn't a runtime operation!
		//so it points to same object previously created in SCP.
		String s6= "I am";
		String s7 = s6 + " the boss!";
		System.out.println(s3 == s7);//false
		//s7 is an object created during Runtime so it is created in heap.
 
	}}




 intern():

By using heap object if we want to get corresponding SCP object then we should go for intern() method.

java">class StringInternDemo 
{
	public static void main(String[] args) 
	{
		String s1 = new String("harsha");
		String s2 = s1.intern();		
		System.out.println(s1 == s2); //false
		//since s2 is created in SCP
		String s3 = "harsha";
		System.out.println(s2 == s3); //true
		//since s3 is created in SCP
	}}




java">//Program demonstrating some methods of String class
class StringDemo3  
{
	public static void main(String[] args) 
	{
		String s = "Sri Harsha";
		System.out.println(s.charAt(3));
		s = s.concat(" Bolisetti");
		System.out.println("Sri".equals(s));
		//this is overriding version of .equals() in Object class
		System.out.println("sri harsha bolisetti".equalsIgnoreCase(s));
		String lname = s.substring(11);
		System.out.println(lname);
		String fname = s.substring(0,10);
		System.out.println(fname);
 
		System.out.println("length of my name is " +s.length());
 
		String s2 = s.replace('s','Z');
		System.out.println(s2);
 
		System.out.println(s.toLowerCase());
		System.out.println(s.toUpperCase());
 
		System.out.println("    Sri Harsha Bolisetti    ".trim()); 
		//trim() removes spaces at the begining and end of the String but not middle blank spaces.
		System.out.println(s.indexOf('B'));
		System.out.println(s.lastIndexOf('i'));
	}}
	/*
	Output of the above program is 	
false
true
Bolisetti
Sri Harsha
length of my name is 20
Sri HarZha BoliZetti
sri harsha bolisetti
SRI HARSHA BOLISETTI
Sri Harsha Bolisetti
11
19
*/




StringBuffer

StringBuffer is mutable i.e, we can make changes in an object without need to create a new object.

Constructors:

1. StringBuffer sb = new StringBuffer();

It creates an empty StringBuffer object with default initial capacity 16. Once it reaches its maximum capacity, a new StringBuffer object  is created with capacity (current capacity + 1)* 2.

2.  StringBuffer sb = new StringBuffer(int initial capacity);

It creates StringBuffer with specified initial capacity.

3. StringBuffer sb = new StringBuffer(String s);

Creates an equivalent StringBuffer object for the given String with capacity equal to s.length()+16.

java">class StringBufferDemo1 
{
	public static void main(String[] args) 
	{
		StringBuffer sb = new StringBuffer();
		System.out.println(sb.capacity());
		sb.append("0123456789123456");
		System.out.println(sb.capacity()); //16
		sb.append("1");
		System.out.println(sb.capacity()); //34
 
		StringBuffer sb1 = new StringBuffer(11);
		System.out.println(sb1.capacity());//11
 
		StringBuffer sb2 = new StringBuffer("harsha");
		System.out.println(sb2.capacity());// 22 (16+6 )
	}
}




Program to demonstrate methods in StringBuffer

java">class StringBufferDemo2 
{
	public static void main(String[] args) 
	{
		StringBuffer sb = new StringBuffer("I will win no matter the consequences");
		System.out.println(sb.charAt(3));
		sb.setCharAt(3,'I');
		System.out.println(sb);
 
		sb.append(" Cool!");
		System.out.println(sb);
 
		sb.insert(12,"!!Inserted here!!");
		System.out.println(sb);
 
		sb.delete(12,28);
		System.out.println(sb);
 
		sb.deleteCharAt(12);
		System.out.println(sb);
 
		System.out.println(sb.reverse());
		System.out.println(sb.reverse());
 
		sb.setLength(14);
		System.out.println(sb);
 
		sb.ensureCapacity(100);
		System.out.println(sb.capacity());
 
		sb.trimToSize();
		System.out.println(sb.capacity());
	}}
	/* Output
	i
I wIll win no matter the consequences
I wIll win no matter the consequences Cool!
I wIll win n!!Inserted here!!o matter the consequences Cool!
I wIll win n!o matter the consequences Cool!
I wIll win no matter the consequences Cool!
!looC secneuqesnoc eht rettam on niw llIw I
I wIll win no matter the consequences Cool!
I wIll win no
108
14
*/




 StringBuilder:

Its almost same as StringBuffer including methods and constructors, except that every method present inside StringBuffer is synchronized while methods in StringBuilder aren’t synchronized.

转载于:https://my.oschina.net/u/138995/blog/215325


http://www.niftyadmin.cn/n/1382828.html

相关文章

SSH框架中Spring框架搭建的初步理解(一)

接手基于SSH框架的web项目已经一个月有余了。早有听说javaweb三大框架,第一次接触,先来说下感受。 我感觉SSH框架最明显的优点有如下: 采用MVC模式,层次结构清晰,使程序员只需关注业务逻辑的实现。 通过配置文件&…

生成指定位数的随机数

2019独角兽企业重金招聘Python工程师标准>>> /*** 生成指定位数的随机数* param length* return*/public static String getRandom(int length){String val "";Random random new Random();for (int i 0; i < length; i) {val String.valueOf(rand…

关于html中viewport和initial-scale以及device-width的理解

上图是一些放大镜&#xff0c;不是打酱油的… 我们在初始化一个html页面的时候&#xff0c;往往会首先在页面头部加上这样一个标签&#xff1a; <meta name"viewport" content"widthdevice-width, initial-scale1">那么这个标签中viewport&#xf…

table( 表格)以及列表的使用

<p>table知识总结</p><ol type"A"><li>table即是表格的意思&#xff0c;以table开始以及结束。</li><li>caption标签 是为表格添加标题&#xff0c;不现实在表格范围之内&#xff0c;且只能有一个。</li> <li>tr代…

[开源项目] Laravel Shop 电商新增高级功能

功能 功能清单&#xff1a; 高性能无限级分类&#xff1b;众筹商品管理&#xff1b;众筹商品下单逻辑&#xff1b;众筹商品结束逻辑&#xff1b;使用分期付款支付订单&#xff1b;计算分期付款逾期费&#xff1b;分期付款订单的退款&#xff1b;给商品增加属性&#xff1b;使用…

Web学习一些专业名词

1.API API&#xff08;Application Programming Interface,应用程序编程接口&#xff09;是一些预先定义的函数&#xff0c;目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力&#xff0c;而又无需访问源码&#xff0c;或理解内部工作机制的细节。 2.浏览器…

discuz核心函数库function_core的函数注释

/** * 系统错误处理 * param <type> $message 错误信息 * param <type> $show 是否显示信息 * param <type> $save 是否存入日志 * param <type> $halt 是否中断访问 */ function system_error($message, $show true, $save true, $halt true) { …

Antd如何优雅的定制主题

官方有详细的说明&#xff0c;可以看官方文档说明 我这里白话说一下&#xff1a; antd react vue的配置是一样&#xff0c;思路就是&#xff1a; 因为antd的ui色调都是定义在了公用的样式配置文件&#xff1a;完整版可以看这里 所以你可以使用你提供的less文件覆盖antd的le…