1.String 类型是否为数据的基本类型
回答:String类型不是基本的数据的类型,数据的基本类型(primitive Type)为:
- byte类型
- int类型
- long类型
- short类型
- char类型
- float类型
- double类型
- Boolean类型
除了基本的数据类型与引用的数据的类型(enumeration Type)之后,其他的都是引用的数据类型(reference Type)
2.int和Integer的区别?
int:基本的数据的类型
Integer:int数据类型的包装类(从jdk5开始有了自动的装箱和拆箱的机制)
其他基本数据类型的包装类分别是:
boolean Boolean
char Character
byte Byte
long Long
short Short
float Float
double Double
注意:Integer的一个valueOf的方法是在-128~127之间的基本的int数据进行了一个包装,如果是在这个范围内已经有一个相同大小的int类型的包装类,那么就不会再继续创建一个新的包装的对象
举例
public class Test03 {
public static void main(String[] args) {
Integer f1 = 100, f2 = 100, f3 = 150, f4 = 150;
System.out.println(f1 == f2);//此时的输出为true
System.out.println(f3 == f4);//此时的输出为false(范围已经超过了规定的范围)
}
}
valueOf的源码
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
IntegerCache的源码
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
例题:
class AutoUnboxingTest {
public static void main(String[] args) {
Integer a = new Integer(3);
Integer b = 3; // 将3自动装箱成Integer类型
int c = 3;
System.out.println(a == b); // false 两个引用没有引用同一对象
System.out.println(a == c); // true a自动拆箱成int类型再和c比较
}
}
3.&和&&的区别?
回答:
&:有两种的用法:(1)位与(2)逻辑与:条件1&条件2 会判断条件1是否成立,不管条件1成不成立,就还是会去判断条件2,成立的条件是两个条件都要成立
&&:短路与:条件1&&条件2 如果条件1不成立的话就会直接退出,停止判断,成立的条件就是;两个条都要成立
4.解释内存中的栈(stack)、堆(heap)和静态区(static area)方法区的用法。
回答:(1)栈:一个基本数据类型的变量,或者产生了一个对象的引用,一个线程对应的是一个栈区,每一个栈区的基本数据类型和对一个对象的引用都是私有的,其他的战旗 不可以来访问,栈区分为三个部分:执行环境的上下文,操作指令区,基本类型的变量区;
(2)堆:就是用来存储一些new关键字新创建的对象,只有一个堆区用来被所有的线程所共享,只能用来存储对象,特点是:堆区的速度是特别快的,但是很小
(3)静态区:位于方法区的,用来存储static的声明,静态成员变量
(4)方法区:是各个线程共享的内存区域,它用于存储class二进制文件,包含了虚拟机加载的类信息、常量、静态变量、即时编译后的代码等数据。它有个名字叫做Non-Heap(非堆),目的是与Java堆区分开。注意方法区是线程安全的
5.Math.round(11.5) 等于多少?Math.round(-11.5)等于多少?
Math.round(11.5) 答案为12
Math.round(-11.5)答案为11
注意Math.round()方法的原理是先给参数加上0.5,然后进行向下的四舍五入