Java经典笔试题:
1.有一对兔子,从出生后第 3 个月起每个月都生一 对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问第n个月的兔子总数为多少? 1.程序分析: 兔子的规律为数列 1,1,2,3,5,8,13,21....
//递归
public class Demo11 {
public static void main(String[] args) {
int num = method(6);
System.out.println(num);
}
public static int method(int n) {//n月份
if (n==1||n==2) {
return 1;
}
return method(n-2)+method(n-1);
}
}
2.使用单循环打印9*9乘法表
public class Demo {
public static void main(String[] args) {
for (int i = 1, j = 1; i <= 9; j++) {
System.out.print(j + "*" + i + "=" + j * i+"\t");
if (j == i) {
j = 0;
i++;
System.out.println();
}
}
}
}
3.使用冒泡排序遍历数组
import java.util.Arrays;
public class Demo10 {
public static void main(String[] args) {
int[] arr = { 1, 8, 5, 9, 8, 4 };
for (int i = 0; i < arr.length - 1; i++) {//i控制比较数
for (int j = 0; j < arr.length - 1 - i; j++) {//j控制每次排序多少次
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.err.println(Arrays.toString(arr));
}
}
4.程序分析题:有无尽的水和一个三升和五升的杯子各一个(没有刻度),取出4升的水,写出方案
方案一:
3L的杯子取满水倒入5L的杯子,再将3L的杯子取满水将5L的杯子装满,此时3L的杯子里还剩1L的水
将5L的杯子的水倒掉,再将3L杯子里的一升水倒入5L的杯子,再用3L的杯子装满水倒入5L的杯子里,
此时5L的杯子里就有4L的水了方案二:
5L的杯子装满水将3L的杯子装满,此时还剩2L水将3L的杯子里的水倒掉,将5L杯子里的2L水倒入3L的杯子。
再取5L的水,将3L的杯子装满,此时5L的杯子还剩4L的水
5.单例模式
饿汉式:
//单例模式:保证一个类仅有一个对象
public class Test01_Singleton {
public static void main(String[] args) {
Person p1 = Person.getP();
Person p2 = Person.getP();
System.out.println(p1);
System.out.println(p2);
}
}
//饿汉式
class Person{
//1,私有化构造方法--不让外界随便new
private Person(){}
//2,在类的内部提供一个new好的对象
private static Person p=new Person();
//3.提供公共的访问方式
//加static为了解决无法通过对象.的方式调用,变成静态的直接用类名调用
public static Person getP(){
return p;
}
}
懒汉式:
public class Test01_Singleton2 {
public static void main(String[] args) {
Student s1 = Student.getS();
Student s2 = Student.getS();
System.out.println(s1==s2);
}
}
//懒汉式(面试重点)--延迟加载思想--线程安全
class Student {
//1,私有化构造方法--不让外界随便new
private Student() {
}
//2,给自己创建一个对象
private static Student s;
//3.提供对外访问方式
synchronized static public Student getS() {
//synchronized (Student.class) {//加同步锁,保证线程安全
if (s == null) {
s = new Student();
}
return s;
//}
}
}
堆和栈有什么区别:
- 栈内存用来存储局部变量和方法调用。而堆内存用来存储 Java 中的对象。无论是成员变量,局部变量,还是类变量,它们指向的对象都存储在堆内存中;
- 堆先进先出,栈先进后出;
- 功能方面:堆是用来存放对象的,栈是用来执行程序的。
- 共享性:堆是线程共享的,栈是线程私有的。
- 空间大小:堆大小远远大于栈。