javaobjectscopeobject-lifetimeobject-construction

The Scope of Creating an instance of a class inside a method in java


Can anyone explain to me the scope of creating an object from a class inside a method in java, is it a bad way and wasting the resources or it's normal? The program is running but I am not sure about this step:

/**
 * Sending Packets Method
 * @param message-the message we want to send to the client side
 * @param IP-in InetAddress format
 * @param Port-in integer format
 * @return Null
 */
public static void send(String message,InetAddress IP,int Port){
    byte [] buffer=message.getBytes();
    DatagramPacket datagrampacket=new DatagramPacket(buffer,buffer.length,IP,Port); 
    datagrampacket.setPort(20002);
    try {
        DatagramSocket datagramSocket=new DatagramSocket();
        datagramSocket.send(datagrampacket);
        datagramSocket.setReuseAddress(true);
        datagramSocket.close();
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

In this case, I create a new object of DatagramSocket every single time I call the function and wasting the resources or the object disappear when the function finishes?

Thanks


Solution

  • It is not wrong but it is sub-optimal, a DatagramSocket doesn't qualify as a lightweight class for the purposes of construction on demand. This question would probably receive better answers on SE Code Review.