KamelK
KamelK

Reputation: 71

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

Upvotes: 2

Views: 1953

Answers (3)

Martin Spamer
Martin Spamer

Reputation: 5585

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.

  • Make the datagramSocket a property of the class.
  • Remove the static from the method.
  • Instantiate the socket in either constructor of this class, or the calling class and pass to the constructor.
  • Your parameter variable 'Port' should be 'port'.
  • Your code ignores the Port parameter and hard codes a socket to 20002.
  • Learn the distinction between variable lifetime and scope.

Upvotes: 2

hipposay
hipposay

Reputation: 62

since you are not returning the object to any instance variable, when the methd ends there are no variable pointing to the object so it can be garbage collected. you can not know when the gb will run or if it will. this is just to say you can not assume the object will disappear as soon as the method ends

Upvotes: 0

Dinesh
Dinesh

Reputation: 1086

The scope will be the declaration of the object. To create a object in a function, it depends upon yourrequirement, if you want to reuse the object, then you can declare the object at the class level and make the class as singleton (like using the Database repository) and initilize it in the constructor or some init method. And if you require every method call should have new object, then you should create in method level.

Upvotes: 0

Related Questions