int 和 Integer使用区别与使用场景

int是java提供的8种原始数据类型之一。Java为每个原始类型提供了封装类,Integer是java为int提供的封装类。
int的默认值为0,而Integer的默认值为null,即Integer可以区分出未赋值和值为0的区别,int则无法表达出未赋值的情况;
例如,要想表达出没有参加考试和考试成绩为0的区别,则只能使用Integer。
在JSP开发中,Integer的默认为null,所以用el表达式在文本框中显示时,值为空白字符串,而int默认的默认值为0,所以用
el表达式在文本框中显示时,结果为0,故int不适合作为web层的表单数据的类型。
在Hibernate中,如果将OID定义为Integer类型,那么Hibernate就可以根据其值是否为null而判断一个对象是否是临时的,
如果将OID定义为了int类型,还需要在hbm映射文件中设置其unsaved-value属性为0
另外,Integer提供了多个与整数相关的操作方法,例如,将一个字符串转换成整数,Integer中还定义了表示整数的最大值和最小值的常量。
*/
package Integer_int_package;
/**
* 问题:要想表达出没有参加考试和考试成绩为0的区别?我们应该用Integer表示还是用int表示?
*/
public class Integer_int {
private static int score;
private static Integer score2;
public static void main(String[] args) {
System.out.println("int类型的默认值score2:" + score);// 0
System.out.println("Integer类型的默认值score:" + score2);// null
//if(score==null){}//报错因为score是int类型的不能和null比较
if (score2 == null) {
System.out.println("没有参加考试!!!");
} else if (score2 == 0) {
System.out.println("考试成绩为0分!!!");
} else {
System.out.println("考试成绩为" + score2);
}
integer();
}
public static void integer() {
String string = "12345";
Integer i = Integer.parseInt(string);// 把字符串解析为Integer类型
Integer max = Integer.MAX_VALUE;
Integer min = Integer.MIN_VALUE;
System.out.println("Integer.parseInt(string)=" + i);
System.out.println("integer的最大值:"+max+",最小值:"+min);
}
}
posted @   TrumanPan  阅读(498)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示