EbraHim EbraHim - 7 months ago 8
Java Question

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

As far as I know,

new
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
    st1
    and
    st2
    ?

  2. Why we must pass the arguments of constructor in
    {}
    instead of
    ()
    , in the
    b2
    declaration line?

  3. Why I receive error for
    b5
    and
    b6
    ?


Answer
  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.