Java 身份证号常见面试 / 练习题

题型 1:判断身份证号长度是否合法(15 位 / 18 位)
考点
字符串长度判断、基础条件判断
思路
1.去掉字符串前后空格
2.判断长度是否是 15 或 18
3.返回是否合法

代码

java

public class IdCardTest {
public static boolean checkLength(String idCard) {
// 1. 去空格
String card = idCard.trim();

// 2. 判断长度
return card.length() == 15 || card.length() == 18;
}

public static void main(String[] args) {
System.out.println(checkLength("11010119900307789X")); // true
System.out.println(checkLength("123456")); // false
}
}

题型 2:判断身份证号是否全是数字(18 位最后一位可以是 X)
考点
字符遍历、正则表达式、大小写兼容
思路
方式 1:遍历每个字符判断
方式 2:正则表达式最简单(推荐)
正则规则
[0-9]{15}$|[0-9]{17}[0-9Xx]$

15 位全数字
18 位:前 17 位数字,最后一位数字或 X/x

代码

java

public static boolean checkNumber(String idCard) {
if (idCard == null) return false;
// 正则匹配
return idCard.matches("[0-9]{15}$|[0-9]{17}[0-9Xx]$");
}

题型 3:从身份证号提取出生年月日(必考!)
考点
字符串截取 substring()、日期格式化
规则
18 位:第 7~14 位 → 出生年月日
15 位:第 7~12 位 → 出生年月日(前面补 19)

代码

java

public static String getBirthday(String idCard) {
if (!checkLength(idCard)) return "长度不合法";

String birthday;
if (idCard.length() == 18) {
birthday = idCard.substring(6, 14);
} else {
birthday = "19" + idCard.substring(6, 12);
}
// 格式化:19900307 → 1990-03-07
return birthday.substring(0,4) + "-" +
birthday.substring(4,6) + "-" +
birthday.substring(6,8);
}

题型 4:从身份证号提取性别(倒数第二位判断)
考点
取模运算 %、字符转数字
规则
18 位:倒数第 2 位
15 位:最后 1 位
奇数 = 男,偶数 = 女

代码

java

public static String getGender(String idCard) {
if (!checkLength(idCard)) return "长度错误";

int genderNum;
if (idCard.length() == 18) {
// 取倒数第二位
genderNum = idCard.charAt(16) - '0';
} else {
// 15位取最后一位
genderNum = idCard.charAt(14) - '0';
}

return genderNum % 2 == 0 ? "女" : "男";
}

题型 5:身份证号校验码验证(18 位最后一位 X 算法,高级题)
考点
加权求和、取模、真实身份证校验逻辑
公式(必须背)
前 17 位 × 权重:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
求和后 %11
余数对应结果:0→1 1→0 2→X 3→9 4→8 5→7 6→6 7→5 8→4 9→3 10→2

代码

java

public static boolean checkLastCode(String idCard) {
if (idCard.length() != 18) return false;

// 权重数组
int[] weight = {7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
// 校验码对应表
char[] code = {'1','0','X','9','8','7','6','5','4','3','2'};

int sum = 0;
for (int i = 0; i < 17; i++) {
sum += (idCard.charAt(i) - '0') * weight[i];
}

// 计算余数并获取校验码
int mod = sum % 11;
char last = idCard.charAt(17);

// 比较(大小写X都算对)
return Character.toUpperCase(last) == code[mod];
}

题型 6:综合验证(长度 + 格式 + 校验码 + 出生日期)
考点
综合前面所有知识点,企业面试最爱
逻辑
非空 & 长度 18/15
字符格式正确
出生日期合法
18 位校验码正确

代码

java

public static boolean checkIdCard(String idCard) {
if (idCard == null) return false;

// 1. 长度
if (!checkLength(idCard)) return false;

// 2. 格式
if (!checkNumber(idCard)) return false;

// 3. 18位校验码
if (idCard.length() == 18 && !checkLastCode(idCard)) return false;

// 4. 出生日期合法(可自己加日期判断)
return true;
}

6 大题型快速总结
1.长度判断:15 / 18 位
2.字符格式:数字 + 最后一位 X
3.提取生日:18 位 (7-14)、15 位 (7-12+19)
4.提取性别:倒数第二位奇偶
5.校验码:加权求和取模(面试加分项)
6.综合验证:把上面全部组合

posted on 2026-05-18 21:38  谢天佑  阅读(32)  评论(0)    收藏  举报