I am learning about TCP and UDP socket programming with Java, one of the books i am reading for my networking class has the following line:
DatagramPacket receivedPacket = new DatagramPacket(receiveData, receiveData.length);
String modifiedSentence = new String(receivedPacket.getData());
Where receivedPacked is just a DatagramPacket type Object and modifiedSentence stores what was returned from the server. ReceivedPacket.getData() converts the packet from bytes to the string in this case before storing it.
My question is why create an object of a string and storing/passing the converted packet to it rather than using the following:
String modifiedSentence = receivedPacket.getData();
Would this not work? I thought in Java it was impractical to specifically create an object of the String class.
DatagramPacket.getData()returns a byte array not a string. Thus you need to convert it to a string to assign it to a string.