short 关键字

概述

short 是Java中的基本数据类型,表示16位有符号整数,取值范围为-32768到32767。

语法格式

short variableName;               // 声明short变量
short variableName = value;       // 声明并初始化

基本特性

public class ShortBasicsExample {
    public static void main(String[] args) {
        // 基本声明和初始化
        short s1 = 100;
        short s2 = -500;
        short s3 = 32767;   // 最大值
        short s4 = -32768;  // 最小值

        System.out.println("s1 = " + s1);
        System.out.println("s2 = " + s2);
        System.out.println("s3 = " + s3);
        System.out.println("s4 = " + s4);

        // 常量值
        System.out.println("short最小值: " + Short.MIN_VALUE);
        System.out.println("short最大值: " + Short.MAX_VALUE);
        System.out.println("short大小(位): " + Short.SIZE);
        System.out.println("short大小(字节): " + (Short.SIZE / 8));

        // 需要强制转换的情况
        short fromInt = (short) 1000;      // int字面量需要强制转换
        short fromByte = 50;               // byte可以自动转换

        System.out.println("从int强制转换: " + fromInt);
        System.out.println("从byte自动转换: " + fromByte);
    }
}

类型转换

public class ShortConversionExample {
    public static void main(String[] args) {
        // 自动类型转换(向上转换)
        short s = 1000;
        int i = s;      // short -> int
        long l = s;     // short -> long
        float f = s;    // short -> float
        double d = s;   // short -> double

        System.out.println("short: " + s);
        System.out.println("int: " + i);
        System.out.println("long: " + l);
        System.out.println("float: " + f);
        System.out.println("double: " + d);

        // 强制类型转换(向下转换)
        int largeInt = 40000;
        short shortFromInt = (short) largeInt; // 溢出
        System.out.println("40000转为short: " + shortFromInt); // -25536

        // 安全转换检查
        int value = 30000;
        if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) {
            short safeShort = (short) value;
            System.out.println("安全转换: " + safeShort);
        } else {
            System.out.println("值超出short范围: " + value);
        }

        // 字符串转换
        String str = "1500";
        short shortFromString = Short.parseShort(str);
        System.out.println("字符串转short: " + shortFromString);

        // short转字符串
        short s2 = 2500;
        String stringFromShort = Short.toString(s2);
        System.out.println("short转字符串: " + stringFromShort);

        // 进制转换
        short decimal = 255;
        System.out.println("十进制: " + decimal);
        System.out.println("二进制: " + Integer.toBinaryString(decimal));
        System.out.println("八进制: " + Integer.toOctalString(decimal));
        System.out.println("十六进制: " + Integer.toHexString(decimal));
    }
}

数组操作

import java.util.Arrays;

public class ShortArrayExample {
    public static void main(String[] args) {
        // 创建short数组
        short[] shorts1 = new short[5];                    // 默认值为0
        short[] shorts2 = {100, 200, 300, 400, 500};      // 初始化
        short[] shorts3 = new short[]{-100, -200, -300};  // 匿名数组

        System.out.println("默认数组: " + Arrays.toString(shorts1));
        System.out.println("初始化数组: " + Arrays.toString(shorts2));
        System.out.println("匿名数组: " + Arrays.toString(shorts3));

        // 数组操作
        shorts1[0] = 1000;
        shorts1[1] = 2000;
        System.out.println("修改后: " + Arrays.toString(shorts1));

        // 查找最大值和最小值
        short max = shorts2[0];
        short min = shorts2[0];
        for (short s : shorts2) {
            if (s > max) max = s;
            if (s < min) min = s;
        }
        System.out.println("最大值: " + max);
        System.out.println("最小值: " + min);

        // 数组排序
        short[] unsorted = {500, 100, 300, 200, 400};
        System.out.println("排序前: " + Arrays.toString(unsorted));
        Arrays.sort(unsorted);
        System.out.println("排序后: " + Arrays.toString(unsorted));

        // 数组搜索
        int index = Arrays.binarySearch(unsorted, (short) 300);
        System.out.println("值300的索引: " + index);
    }
}

算术运算

public class ShortArithmeticExample {
    public static void main(String[] args) {
        short a = 1000;
        short b = 500;

        // 注意:short运算结果自动提升为int
        int sum = a + b;        // 不能直接赋值给short
        int difference = a - b;
        int product = a * b;
        int quotient = a / b;
        int remainder = a % b;

        System.out.println(a + " + " + b + " = " + sum);
        System.out.println(a + " - " + b + " = " + difference);
        System.out.println(a + " * " + b + " = " + product);
        System.out.println(a + " / " + b + " = " + quotient);
        System.out.println(a + " % " + b + " = " + remainder);

        // 如果要保持short类型,需要强制转换
        short shortSum = (short) (a + b);
        System.out.println("强制转换为short: " + shortSum);

        // 复合赋值运算符(自动处理类型转换)
        short x = 100;
        x += 50;    // 等同于 x = (short)(x + 50)
        x -= 20;
        x *= 2;
        x /= 3;

        System.out.println("复合运算后的值: " + x);

        // 自增自减运算
        short counter = 10;
        System.out.println("初始值: " + counter);
        System.out.println("前缀自增: " + (++counter));
        System.out.println("后缀自增: " + (counter++));
        System.out.println("最终值: " + counter);
    }
}

实际应用示例

import java.nio.ByteBuffer;
import java.util.Random;

public class ShortApplicationExample {

    // 音频数据处理(16位音频样本)
    public static void audioProcessingExample() {
        System.out.println("=== 音频数据处理 ===");

        // 生成16位音频样本数据
        short[] audioSamples = new short[10];
        Random random = new Random();

        for (int i = 0; i < audioSamples.length; i++) {
            // 生成-32768到32767范围的音频样本
            audioSamples[i] = (short) (random.nextInt(65536) - 32768);
        }

        System.out.println("原始音频样本:");
        for (int i = 0; i < audioSamples.length; i++) {
            System.out.printf("  样本[%d]: %6d\n", i, audioSamples[i]);
        }

        // 音量调整(降低50%)
        short[] adjustedSamples = new short[audioSamples.length];
        for (int i = 0; i < audioSamples.length; i++) {
            adjustedSamples[i] = (short) (audioSamples[i] * 0.5);
        }

        System.out.println("音量调整后:");
        for (int i = 0; i < adjustedSamples.length; i++) {
            System.out.printf("  样本[%d]: %6d\n", i, adjustedSamples[i]);
        }
    }

    // 图像处理(RGB565格式)
    public static void imageProcessingExample() {
        System.out.println("\n=== 图像处理(RGB565) ===");

        // RGB565格式:5位红色,6位绿色,5位蓝色
        short red = 31;    // 最大红色值
        short green = 63;  // 最大绿色值
        short blue = 31;   // 最大蓝色值

        // 打包成RGB565格式
        short rgb565 = (short) ((red << 11) | (green << 5) | blue);

        System.out.println("RGB分量:");
        System.out.println("  红色: " + red + " (5位)");
        System.out.println("  绿色: " + green + " (6位)");
        System.out.println("  蓝色: " + blue + " (5位)");
        System.out.println("RGB565值: " + rgb565 + " (0x" + Integer.toHexString(rgb565 & 0xFFFF) + ")");

        // 解包RGB565格式
        short extractedRed = (short) ((rgb565 >> 11) & 0x1F);
        short extractedGreen = (short) ((rgb565 >> 5) & 0x3F);
        short extractedBlue = (short) (rgb565 & 0x1F);

        System.out.println("解包后的RGB分量:");
        System.out.println("  红色: " + extractedRed);
        System.out.println("  绿色: " + extractedGreen);
        System.out.println("  蓝色: " + extractedBlue);
    }

    // 网络协议头部
    public static void networkProtocolExample() {
        System.out.println("\n=== 网络协议示例 ===");

        // TCP头部的端口号(16位)
        short sourcePort = 8080;
        short destPort = 80;

        // UDP数据包长度(16位)
        short udpLength = 1024;

        // 校验和(16位)
        short checksum = 0x1234;

        System.out.println("TCP头部信息:");
        System.out.println("  源端口: " + sourcePort);
        System.out.println("  目标端口: " + destPort);

        System.out.println("UDP信息:");
        System.out.println("  数据包长度: " + udpLength + " 字节");
        System.out.println("  校验和: 0x" + Integer.toHexString(checksum & 0xFFFF));

        // 端口号范围检查
        if (isValidPort(sourcePort) && isValidPort(destPort)) {
            System.out.println("端口号有效");
        } else {
            System.out.println("端口号无效");
        }
    }

    private static boolean isValidPort(short port) {
        // 端口号范围:1-65535(0保留)
        return port > 0; // short范围内的正数都是有效端口
    }

    public static void main(String[] args) {
        audioProcessingExample();
        imageProcessingExample();
        networkProtocolExample();
    }
}

包装类Short

public class ShortWrapperExample {
    public static void main(String[] args) {
        // 创建Short对象
        Short shortObj1 = new Short((short) 1000);     // 已过时
        Short shortObj2 = Short.valueOf((short) 1000); // 推荐方式
        Short shortObj3 = 1000;                        // 自动装箱

        System.out.println("Short对象: " + shortObj2);

        // 自动装箱和拆箱
        short primitive = 500;
        Short wrapped = primitive;        // 自动装箱
        short unwrapped = wrapped;        // 自动拆箱

        System.out.println("装箱: " + wrapped);
        System.out.println("拆箱: " + unwrapped);

        // 比较
        Short s1 = 100;
        Short s2 = 100;
        Short s3 = new Short((short) 100);

        System.out.println("s1 == s2: " + (s1 == s2));       // true (缓存-128到127)
        System.out.println("s1 == s3: " + (s1 == s3));       // false
        System.out.println("s1.equals(s3): " + s1.equals(s3)); // true

        // 解析字符串
        try {
            short parsed1 = Short.parseShort("12345");
            short parsed2 = Short.parseShort("FF", 16);  // 十六进制
            short parsed3 = Short.parseShort("1010", 2); // 二进制

            System.out.println("解析 \"12345\": " + parsed1);
            System.out.println("解析 \"FF\"(16进制): " + parsed2);
            System.out.println("解析 \"1010\"(2进制): " + parsed3);
        } catch (NumberFormatException e) {
            System.out.println("解析失败: " + e.getMessage());
        }

        // 比较方法
        Short first = 200;
        Short second = 300;
        System.out.println("比较结果: " + first.compareTo(second));

        // 值转换
        short value = 1000;
        System.out.println("byte值: " + Short.valueOf(value).byteValue());
        System.out.println("int值: " + Short.valueOf(value).intValue());
        System.out.println("long值: " + Short.valueOf(value).longValue());
        System.out.println("float值: " + Short.valueOf(value).floatValue());
        System.out.println("double值: " + Short.valueOf(value).doubleValue());
    }
}

最佳实践

public class ShortBestPractices {

    // 1. 安全的类型转换
    public static short safeIntToShort(int value) {
        if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
            throw new IllegalArgumentException("值超出short范围: " + value);
        }
        return (short) value;
    }

    // 2. 无符号short处理
    public static int toUnsigned(short value) {
        return value & 0xFFFF;
    }

    // 3. 字节序转换
    public static short swapBytes(short value) {
        return Short.reverseBytes(value);
    }

    // 4. 范围验证
    public static boolean isInShortRange(long value) {
        return value >= Short.MIN_VALUE && value <= Short.MAX_VALUE;
    }

    // 5. 数组工具方法
    public static void printShortArray(short[] array, String description) {
        System.out.println(description + ":");
        for (int i = 0; i < array.length; i++) {
            System.out.printf("  [%d]: %6d (0x%04X)%n", i, array[i], array[i] & 0xFFFF);
        }
    }

    public static void main(String[] args) {
        System.out.println("=== 安全类型转换 ===");
        try {
            short safe = safeIntToShort(30000);
            System.out.println("安全转换: " + safe);

            short unsafe = safeIntToShort(40000); // 抛出异常
        } catch (IllegalArgumentException e) {
            System.out.println("转换失败: " + e.getMessage());
        }

        System.out.println("\n=== 无符号处理 ===");
        short negative = -1;
        System.out.println("有符号值: " + negative);
        System.out.println("无符号值: " + toUnsigned(negative));

        System.out.println("\n=== 字节序转换 ===");
        short original = 0x1234;
        short swapped = swapBytes(original);
        System.out.printf("原始值: 0x%04X%n", original);
        System.out.printf("交换后: 0x%04X%n", swapped & 0xFFFF);

        System.out.println("\n=== 范围验证 ===");
        long[] testValues = {0L, 32767L, -32768L, 40000L, -40000L};
        for (long value : testValues) {
            System.out.println(value + " 在short范围内: " + isInShortRange(value));
        }

        System.out.println("\n=== 数组打印 ===");
        short[] array = {1000, -2000, 30000, -32768, 32767};
        printShortArray(array, "示例数组");
    }
}

short类型适用于需要节省内存的场景,如大型数组、网络协议、音频处理等需要16位整数的应用。

powered by Gitbook© 2025 编外计划 | 最后修改: 2025-07-28 16:25:54

results matching ""

    No results matching ""