EbraHim EbraHim - 1 year ago 50
Java Question

When we are allowed to use "new" keyword in Java and how to use it?

As far as I know,

keyword is used to instantiate classes. And I think we need to call the class constructor and pass its arguments after this keyword. Right?

Okay, Here is a code snippet:

public class JavaApp{

public static void main(String[] args) {
String st1 = "Test";
String st2 = new String("Test");

byte[] b1 = {'a', 'b'};
byte[] b2 = new byte[]{'a', 'b'};
byte[] b3 = new byte[]('a','b'); //Error

byte b4 = 3;
byte b5 = new byte{3}; //Error
byte b6 = new byte(3); //Error



My questions:

  1. What's the difference between

  2. Why we must pass the arguments of constructor in
    instead of
    , in the
    declaration line?

  3. Why I receive error for

Answer Source
  1. st1 and st2 are two different object; first one reside inside String-Pool and second one as normal java object locates at Heap memory.

  2. {} is not calling constructor, its just a syntax to initialize array.

  3. byte is not a class; its a primitive type so there is no constructor for byte.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download