Java中的String 和char[] ,int和Integer

本文通过具体实例对比了Java中String与char[], 以及Integer与int的使用差异,深入解析了对象存储位置及其比较方式的不同,并指出了Integer在特定范围内值的比较特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/***********************************************************/
public class StringVSChar {
public static void main(String[] args) {
String s1 = "abc";
String s2 = "abc";

char[] ch = { 'a', 'b', 'c' };
String s3 = new String(ch);
String s4=new String("abc");

char[] c = s1.toCharArray();
if (s1.equals(s2)) {
System.out.println(true);
} else {
System.out.println(false);
}

if (s1.equals(ch)) {
System.out.println(true);
} else {
System.out.println(false);
}
if (c.equals(ch)) {
System.out.println(true);
} else {
System.out.println(false);

}
if (s1.equals(s3)) {
System.out.println(true);
} else {
System.out.println(false);
}
if (s1.equals(s4)) {
System.out.println(true);
}else {
System.out.println(false);
}
if (s1==s4) {
System.out.println(true);
} else {
System.out.println(false);
}

if (s1==s3) {
System.out.println(true);
} else {
System.out.println(false);
}

}
}
/***********************************************************/
结果:
true
false
false
true
true
false
false
/***********************************************************/
从结果可以看出要弄清几点:
1.String类型可以和char[]进行相互转换,但两种是不同的类型;
2.弄清楚创建的对象在内存中是处于栈还是堆;
3.String中重写了equal(),比较的是两个对象的内容是否一样,如果不重写,和==一样都是比较的对象的引用,new出来的对象都是放在堆中的。
/***********************************************************/
public class IntVSInteger {
public static void main(String[] args) {
Integer i1 = -18;
Integer i2 = -18;

Integer i3=new Integer(-18);
Integer i4=new Integer(-18);

if (i1 == i2) {
System.out.println(true);
} else {
System.out.println(false);
}

if (i1.equals(i2)) {
System.out.println(true);
} else {
System.out.println(false);
}


if (i3==i4) {
System.out.println(true);
} else {
System.out.println(false);
}

if (i3.equals(i4)) {
System.out.println(true);
} else {
System.out.println(false);
}
}
}
/***********************************************************/
结果:
true
true
false
true
/***********************************************************/
经调试,在Java中,integer的-128~127是系统预留在栈中的共享数据,这个范围之外的赋值,用==比较就是false.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值