Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 18 of 18

Thread: The 'new' Keyword

  1. #1
    Junior Member
    Join Date
    Aug 2012
    Posts
    10
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default The 'new' Keyword

    Hi, this is my first time posting on this forum so I'm sorry if this isn't the right place for this topic. If it isn't the right place, please tell me where a better place might have been. Also, if this topic has been done before, I'm sorry, I didn't see it.

    Anyways, I have many questions on the 'new' keyword. I googled it to try to understand more and I learned that it is used to create a new instance of a class (which I pretty much already knew) as well as it allocates memory for the object to be stored in (which I didn't know, but I now understand).

    So now to get to the questions. What would you have if you created a variable to store an object, but never used the 'new' keyword to set aside memory for it? For instance:
    public class Example {
        public static void main (String[] args) {
            Object object;
        }
    }
    I suppose what I'm asking is what could that variable do, or is it useless? Could it be used in a method or is it just a useless line of code giving a name to reference that technically references nothing? Sorry if this is kind of vague or hard to understand. I'm just trying to figure out what this all means so I can better understand what it is I'm doing.

    Thanks in advance for any help.
    Last edited by helloworld922; August 2nd, 2012 at 11:03 PM.


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,620
    Thanks
    25
    Thanked 322 Times in 300 Posts

    Default Re: The 'new' Keyword

    The variable would be set to null, meaning it has not been initialized. If you attempted to invoke any methods on the variable (such as the toString() method), a Null Pointer Exception will be thrown at runtime and, if you do not explicitly handle the exception, your entire program will crash. You will probably become very intimate with Null Pointer Exceptions, we all get them on a regular basis.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. The Following User Says Thank You to aussiemcgr For This Useful Post:

    TheSlowLearner (August 3rd, 2012)

  4. #3
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: The 'new' Keyword

    To clarify aussiemcgr's answer, the variable is kind of set to null. The java compiler is smart enough to recognize here that object has never been initialized and will by default throw a compile error. You can specify more strictly that you do intend to have the variable initialized to the default value (null).

    Object object = null;

    Note that explicit initialization is not required for non-local variables (for example object fields or static class fields).

  5. The Following 2 Users Say Thank You to helloworld922 For This Useful Post:

    aussiemcgr (August 3rd, 2012), TheSlowLearner (August 3rd, 2012)

  6. #4
    Member
    Join Date
    Jul 2012
    Posts
    69
    My Mood
    Relaxed
    Thanks
    1
    Thanked 6 Times in 6 Posts

    Default Re: The 'new' Keyword

    So there is no difference between Object object; and Object object = null?

  7. #5
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,620
    Thanks
    25
    Thanked 322 Times in 300 Posts

    Default Re: The 'new' Keyword

    nope, it's the same thing, but that's only because Objects are set to null when not initialized. The same is not true for primitives like ints and doubles. For ints, these two are the same:
    //this:
    int variable;
    //is the same as:
    int variable = 0;
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  8. #6
    Junior Member
    Join Date
    Aug 2012
    Posts
    10
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: The 'new' Keyword

    Thanks for all the answers everyone.
    So, just to be sure I understand: without initializing the object it has a 'null' value and any attempt to call methods on it will result in a 'null pointer error' which could crash your program.
    Just a couple more questions. Does the object exist before it is initialized? Or does declaring it just create a reference or something without creating the object itself?

  9. #7
    Junior Member
    Join Date
    Aug 2012
    Posts
    10
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: The 'new' Keyword

    Quote Originally Posted by helloworld922 View Post
    Note that explicit initialization is not required for non-local variables (for example object fields or static class fields).
    Just wondering, what does this mean exactly? Could you give an example? For some reason I just can't picture what you're saying.

  10. #8
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: The 'new' Keyword

    So, just to be sure I understand: without initializing the object it has a 'null' value and any attempt to call methods on it will result in a 'null pointer error' which could crash your program.
    Just a couple more questions. Does the object exist before it is initialized? Or does declaring it just create a reference or something without creating the object itself?
    No object is created, it is simply a floating reference.

    Just wondering, what does this mean exactly? Could you give an example? For some reason I just can't picture what you're saying.
    public class Test
    {
        public Object o1;
        public static Object o2;
     
        public static void main(String[] args)
        {
            Object o3 = null;
     
        }
    }

    Neither o1 or o2 need to explicitly initialized to null before being used. However, o3 does need to be explicitly set to null before use.

  11. #9
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    939
    Thanks
    6
    Thanked 202 Times in 178 Posts

    Default Re: The 'new' Keyword

    Think of variables as like road signs that point somewhere.

    If and when you say "o3=new Object();" the assignment with = is like banging that sign into the ground so that it points towards the newly created object.

    null is a special value that signs have when they don't point anywhere. (They are still in the truck.) o1 and o2 are like that: they are assumed to be "still in the truck" - they have the value null.

    o3 which appears in a method is different. The compiler demands you say where it is pointing. For example you can say "o3=new Object();" but you are also allowed to say "o3=null" if you really mean to say "not pointing anywhere yet". I think Java adopts this rule to keep you from making the mistake of thinking a variable points somewhere when it really doesn't.

  12. #10
    Junior Member
    Join Date
    Jul 2012
    Posts
    16
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: The 'new' Keyword

    All you have done is declared a local variable (which ought to point to something but doesnt). I disagree with a previous answer stating it is set to null. Because your reference is local it does not receive a default value. What is it set to? Well probably garbage but we dont really know because any attempt to read its
    contents will result in a compiler errorl


    Any attempt to read it or call a method on it it will probably result in some kind of "may not have been initalized" error.

    Say instead you had a call like:

    Object o = new Object();

    This will give you two constructs: One a reference called o (think of it as a very small thing , basically an address), but you will also get a much larger object (which is anonymous). Imagine a small marble (the reference pointing to a globe) the object.
    Last edited by wrightkevin; August 4th, 2012 at 08:04 AM.

  13. #11
    Junior Member
    Join Date
    Aug 2012
    Posts
    10
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: The 'new' Keyword

    Ok, I hope these are my last questions. I just want to be sure I understand fully.

    Why would you ever WANT an object to be set to null? Would you set an object to null if you wanted it to be initialized later based on the results of a method or something?

    Also, why is it different declaring objects within the main method like that? Is there a reason for that or did the makers of Java want to help avoid a specific problem by forcing you to actually specify 'null'? If so, what problem were they trying to avoid?

  14. #12
    Junior Member
    Join Date
    Aug 2012
    Posts
    10
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: The 'new' Keyword

    public class ObjectInitialization {
    	Object object1;
    	static Object object2;
     
    	public static void main(String[] args) {
    		Object object3;
    	}
    }

    I tried this in Eclipse. I got no errors. I thought it wasn't supposed to work. <_<

  15. #13
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    939
    Thanks
    6
    Thanked 202 Times in 178 Posts

    Default Re: The 'new' Keyword

    This is a new question with nothing to do with the keyword.

    Start a new thread to ask it.

  16. #14
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,620
    Thanks
    25
    Thanked 322 Times in 300 Posts

    Default Re: The 'new' Keyword

    What errors?

    You would want to set an object to null, for example, if you wanted to be accessible by the entire class, but only initialized after a certain event or something occurs. You could have a check to see if it has been initialized or not by check if the object is null.

    As a rather silly and impractical example, something like this can show what null can do:
    public static void main(String[] args) {
    	Object obj = null;
    	int result = 0;
    	//Loop 10 times
    	for(int i=0;i<10;i++) {
    		//From the fifth iteration and after, obj will be initalized 
    		if(i==4)
    			obj = new Object();
    		//Only increment result if obj is not null
    		if(obj!=null)
    			result++;
    	}
    	System.out.println("Result: "+result); //Would return "Result: 6"
    }

    That is obviously pretty pointless code, and that sort of behavior should probably be done with a boolean instead of an object, but it does show how having an object set to null can change how a program works.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  17. #15
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: The 'new' Keyword

    Quote Originally Posted by TheSlowLearner View Post
    public class ObjectInitialization {
    	Object object1;
    	static Object object2;
     
    	public static void main(String[] args) {
    		Object object3;
    	}
    }

    I tried this in Eclipse. I got no errors. I thought it wasn't supposed to work. <_<
    That's to be expected. The reasoning is this:

    If you create a variable and never use it, it's not necessarily a problem. It's not exactly useful, but there are uses for allowing this to happen. For example, some people like to incrementally program/debug their program so they may declare all the variables they are expecting to use but not use them yet.

    ex.:

    public static void main(String[] args)
    {
        Scanner reader = new Scanner(System.in);
        // ask for name
        String name;
        System.out.println("what's your name?");
        name = reader.nextLine();
     
        System.out.println("hello, " + name);
        // ask or age
        int age;
    }

    While simplistic, this example should run and the programmer can test to ensure that the code works.

    However, let's say now continue to implement the code.

    public static void main(String[] args)
    {
        Scanner reader = new Scanner(System.in);
        // ask for name
        String name;
        System.out.println("what's your name?");
        name = reader.nextLine();
     
        System.out.println("hello, " + name);
        // ask or age
        int age;
        System.out.println("what's your age?");
        if(age > 80)
        {
            System.out.println("you're an octagenarian.")
        }
        else
        {
            System.out.println("you're still a young'n.")
        }
    }

    This code will cause the compiler to complain. In this case, the programmer had forgotten to actually ask the user for their age. The compiler can catch this and will tell you.

  18. #16
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: The 'new' Keyword

    Quote Originally Posted by TheSlowLearner View Post
    public class ObjectInitialization {
    	Object object1;
    	static Object object2;
     
    	public static void main(String[] args) {
    		Object object3;
    	}
    }

    I tried this in Eclipse. I got no errors. I thought it wasn't supposed to work. <_<
    That is because there is nothing wrong with the code, AS IS. Do like helloworld922 said, and try to USE the object3, and that is a different story. Code below.

    Quote Originally Posted by pbrockway2 View Post
    This is a new question with nothing to do with the keyword.

    Start a new thread to ask it.
    This has everything to do with this thread, as it is a headbutt with a reply.

    public class ObjectInitialization {
    	Object object1;
    	static Object object2;
     
    	public static void main(String[] args) {
    		Object object3;
     
                    if(object1 == null){}//compile error:
                    	//Cannot make a static reference to the non-static field object1
                    if(object2 == null){}//ok, but see notes below..
                    if(object3 == null){}//compile error:
                    	//The local variable object3 may not have been initialized
    	}
    }

    Simply declaring a variable is like walking into a store and grabbing an empty shopping cart. You now have a place to store something.
    When you use the new keyword it is like putting something in the cart.
    Try walking up to the cashier with an empty basket and ask what you owe. If you want to access the price of an item (or any other field) you have to put an object in the box first.

    While you may be able to avoid initialization, as in object2, you shouldn't. There are times you could forget to init a variable, (or just skip it), and just as luck would have it, what ever garbage in that memory location turns out to be suitable your code's needs. Now you have a bug you did not find, and will see eventually. (usually after your assignment is turned in)
    If you initialize all of your variables you remove the possibility of ever having the error, and you always know what is inside. If you want to check vs null, assign a null value on init. If you need an object later, assign it later. There is no rule that says you can not initialize all of your variables, so why not make sure to overwrite any memory garbage with a definition as you declare each variable. ....keep in mind primitive types (including String) have their own defaults...

  19. The Following User Says Thank You to jps For This Useful Post:

    TheSlowLearner (August 7th, 2012)

  20. #17
    Junior Member
    Join Date
    Aug 2012
    Posts
    10
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: The 'new' Keyword

    Quote Originally Posted by jps View Post
    That is because there is nothing wrong with the code, AS IS. Do like helloworld922 said, and try to USE the object3, and that is a different story. Code below.

    This has everything to do with this thread, as it is a headbutt with a reply.

    public class ObjectInitialization {
    	Object object1;
    	static Object object2;
     
    	public static void main(String[] args) {
    		Object object3;
     
                    if(object1 == null){}//compile error:
                    	//Cannot make a static reference to the non-static field object1
                    if(object2 == null){}//ok, but see notes below..
                    if(object3 == null){}//compile error:
                    	//The local variable object3 may not have been initialized
    	}
    }

    Simply declaring a variable is like walking into a store and grabbing an empty shopping cart. You now have a place to store something.
    When you use the new keyword it is like putting something in the cart.
    Try walking up to the cashier with an empty basket and ask what you owe. If you want to access the price of an item (or any other field) you have to put an object in the box first.

    While you may be able to avoid initialization, as in object2, you shouldn't. There are times you could forget to init a variable, (or just skip it), and just as luck would have it, what ever garbage in that memory location turns out to be suitable your code's needs. Now you have a bug you did not find, and will see eventually. (usually after your assignment is turned in)
    If you initialize all of your variables you remove the possibility of ever having the error, and you always know what is inside. If you want to check vs null, assign a null value on init. If you need an object later, assign it later. There is no rule that says you can not initialize all of your variables, so why not make sure to overwrite any memory garbage with a definition as you declare each variable. ....keep in mind primitive types (including String) have their own defaults...
    Thanks. This helped me understand.

  21. #18
    Junior Member
    Join Date
    Aug 2012
    Posts
    10
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: The 'new' Keyword

    Thanks to everyone who helped. This is now a solved question.

Similar Threads

  1. Super Keyword
    By shruthi in forum Java Theory & Questions
    Replies: 12
    Last Post: October 13th, 2011, 03:31 PM
  2. Java classes and the 'new' word
    By Scotty in forum Java Theory & Questions
    Replies: 1
    Last Post: March 27th, 2011, 11:05 AM
  3. quick question - new keyword
    By bbr201 in forum Java Theory & Questions
    Replies: 2
    Last Post: July 18th, 2010, 09:43 PM
  4. keyword Extends
    By chronoz13 in forum Object Oriented Programming
    Replies: 3
    Last Post: November 27th, 2009, 06:30 AM
  5. How to highlight search keyword in text?
    By Mohd in forum JavaServer Pages: JSP & JSTL
    Replies: 4
    Last Post: February 1st, 2009, 05:35 AM