Java Check a Valid TCP Port Number

Tags: PortUtils

In this Java tutorial, we learn how to implement a Java utility class to valid whether a port number is a valid TCP port or not in Java programming language.

How to validate TCP port number in Java

At this first step, create a new Java class named PortUtils, and implement the isValidPort(int portNumber) static method to check valid TCP port as Java code below.

PortUtils.java

public class PortUtils {
    
    /**
     * This method to check if a TCP port number is valid or not.
     * @param portNumber port number
     * @return true if the port number is valid otherwise return false.
     */
    public static boolean isValidPort(int portNumber) {
        return portNumber >= 0 && portNumber <= 65535;
    }
}

In this following example Java code, we learn how to use the above PortUtils.isValidPort(int portNumber) static method in Java program.

PortUtilsValidPortExample.java

public class PortUtilsValidPortExample {
    public static void main(String... args) {
        int port1 = -100;
        int port2 = 80;
        int port3 = 8080;
        int port4 = 700000;

        // Check a Valid TCP Port Number
        boolean result1 = PortUtils.isValidPort(port1);
        boolean result2 = PortUtils.isValidPort(port2);
        boolean result3 = PortUtils.isValidPort(port3);
        boolean result4 = PortUtils.isValidPort(port4);

        System.out.println(port1 + " is a valid port or not: " + result1);
        System.out.println(port2 + " is a valid port or not: " + result2);
        System.out.println(port3 + " is a valid port or not: " + result3);
        System.out.println(port4 + " is a valid port or not: " + result4);
    }
}
The output as below.
-100 is a valid port or not: false
80 is a valid port or not: true
8080 is a valid port or not: true
700000 is a valid port or not: false

Happy Coding 😊

Java Convert Hex String to Byte Array

Java Convert Byte Array to Hex String

How to Convert Object to Map in Java

Java How to Concatenate two Arrays