java String的比较,BOX装箱拆箱,以及面向对象的小代码

package cn.hncu.day2;

public class StringDemo {

public static void main(String[] args) {
String str1 = "abc";//直接赋值,放在栈中,数据共享
String str2 = "abc";
System.out.println("str1==str2: "+(str1==str2));//true

String str3 = new String("abc");//new的东西是在堆中开的,每次都新开空间,因此内存地址是不一样的
String str4 = new String("abc");
System.out.println("str3==str4: "+(str3==str4));//false,"=="是判断栈中的值是否相同

System.out.println("str1==str4: "+(str1==str4));

System.out.println("str1.equals(str4): "+str1.equals(str4));

//综上,以后我们做项目时,判断字符串变量是否相等,一定要用equals()方法

}

}

------------------------------------------------------------------------------------------------------------

package cn.hncu.day2;

public class BoxDemo {

public static void main(String[] args) {
//demo1();
demo2();
}
private static void demo2(){
Integer i1 = 100;
Integer i2 = 100;
System.out.println("i1==i2: "+(i1==i2));

Integer i3 = 200;
Integer i4 = 200;
System.out.println("i3==i4: "+(i3==i4));

int a=100;
int b=100;
System.out.println(a==b);

}

private static void demo1() {
Integer a1 = new Integer(5);
System.out.println(a1);

//自动装箱
Integer a2 = 15;
System.out.println(a2);

//自动拆箱
int x = new Integer(10);
System.out.println(x);

//混合使用
int sum = a2+x;
System.out.println("sum="+sum);
}

}

--------------------------------------------------------------------------------

package cn.hncu.day2;

public class Ball {
private double height;
private int downTimes;
private int jumpTimes;
private double sum;
public Ball(double height) {
this.height = height;
}
public void jump(){
height = height/2;
jumpTimes++;
sum = sum + height;
}
public void fall(){
downTimes++;
sum = sum + height;
}

public static void main(String[] args) {
//第10次落地时,共经过多少米?
Ball ball = new Ball(100);
while(true){
ball.fall();
if(ball.downTimes==10){
System.out.println(ball.sum);
break;
}
ball.jump();
}

//第10次反弹多高?
Ball ball2 = new Ball(100);
while(true){
ball2.fall();
ball2.jump();
if(ball2.jumpTimes==10){
System.out.println(ball2.height);
break;
}
}

System.out.println("-------------");
test2();

}

//用面向过程的方式求解
private static void test2() {
double sum =0;
double begin=100;
double fanTan=0;
for(int i=0; i<10; i++ ){
if(i==9){//第10次落地
sum = sum + begin;
fanTan = begin/2;
}else{
sum = sum + begin + begin/2;
}
begin = begin/2;
}
System.out.println(sum+","+fanTan);
}

}

原文地址:https://www.cnblogs.com/1314wamm/p/5600134.html