Lang:简体中文

面试题java小程序

日期:2025-09-08 / 来源:面试宝典

掌握面试必备的java小程序要点

在java面试中,小程序题目是检验候选人编程能力和思维逻辑的重要手段。以下将详细介绍几类常见的面试题java小程序。

基础语法类小程序

这类题目主要考察对java基础语法的掌握,比如变量声明、数据类型、运算符等。例如,编写一个小程序实现两个整数的交换。代码如下:

java

public class swapnumbers {

public static void main(string[] args) {

int a = 5;

int b = 10;

int temp = a;

a = b;

b = temp;

system.out.println("a = " + a + ", b = " + b);

}

}

在这个例子中,通过引入一个临时变量temp,实现了两个整数的交换。这道题虽然简单,但能反映出面试者对基础语法的熟练程度。

流程控制类小程序

流程控制语句如if - else、for、while等是java编程的重要组成部分。常见的题目是编写一个程序,判断一个数是否为素数。代码示例如下:

java

public class primenumber {

public static void main(string[] args) {

int num = 17;

boolean isprime = true;

for (int i = 2; i <= math.sqrt(num); i++) {

if (num % i == 0) {

isprime = false;

break;

}

}

if (isprime) {

system.out.println(num + " 是素数。");

} else {

system.out.println(num + " 不是素数。");

}

}

}

该程序利用for循环和if - else语句,通过判断一个数是否能被2到其平方根之间的数整除,来确定它是否为素数。

面向对象类小程序

面向对象编程是java的核心特性,包括类、对象、继承、多态等概念。例如,设计一个简单的动物类层次结构,包含父类animal和子类dog、cat。代码如下:

java

class animal {

void makesound() {

system.out.println("动物发出声音。");

}

}

class dog extends animal {

@override

void makesound() {

system.out.println("汪汪汪。");

}

}

class cat extends animal {

@override

void makesound() {

system.out.println("喵喵喵。");

}

}

public class animaltest {

public static void main(string[] args) {

animal dog = new dog();

animal cat = new cat();

dog.makesound();

cat.makesound();

}

}

此示例展示了继承和方法重写的使用,不同的子类重写了父类的makesound方法,体现了多态性。

异常处理类小程序

异常处理是保证程序健壮性的重要手段。编写一个程序,从文件中读取数据,如果文件不存在则捕获异常。代码如下:

java

import java.io.file;

import java.io.filenotfoundexception;

import java.util.scanner;

public class filereading {

public static void main(string[] args) {

try {

file file = new file("test.txt");

scanner scanner = new scanner(file);

while (scanner.hasnextline()) {

system.out.println(scanner.nextline());

}

scanner.close();

} catch (filenotfoundexception e) {

system.out.println("文件未找到:" + e.getmessage());

}

}

}

该程序使用try - catch块捕获文件未找到异常,并输出相应的错误信息。

集合类小程序

java集合框架提供了丰富的数据结构,如list、set、map等。常见的题目是编写一个程序,统计字符串中每个字符的出现次数。代码示例如下:

java

import java.util.hashmap;

import java.util.map;

public class charactercount {

public static void main(string[] args) {

string str = "hello world";

map charcountmap = new hashmap<>();

for (char c : str.tochararray()) {

if (charcountmap.containskey(c)) {

charcountmap.put(c, charcountmap.get(c) + 1);

} else {

charcountmap.put(c, 1);

}

}

for (map.entry entry : charcountmap.entryset()) {

system.out.println(entry.getkey() + ": " + entry.getvalue());

}

}

}

该程序使用hashmap来存储字符及其出现次数,通过遍历字符串中的每个字符,更新map中的计数。

以下为推荐内容

微信二维码