Yes, if you called myMethod() 10 times it will create 10 unique and separate objects.

The new keyword does exactly what it says on the tin, it creates a brand new object, irrespective of whether one already exists. It creates a new object and stuffs the reference to that object inside the variable it has been given, overwriting any previous value (object) the variable held.

Is the myObject variable reallocated every time?

Again, yes it would be re-allocated with a new object every time the method was called. An interesting note about this would be that the variable wouldn't "really" be re-allocated as you are defining the variable within the method body itself, so every time the method ends it will remove the variables that were defined within its' scope. So what it actually does is create 10 individual variables and assign 10 individual objects, although as I said the others should have been removed automatically so it wouldn't use any additional memory.

In a nutshell: should I write code like that only if I plan to invoke that method only once?

Well as I said, in the example above each object would be destroyed at the end of method execution (assuming you didn't assign the object reference to a variable outside the scope of the method) so in your example you could happily call the method as many times as you wanted but each time would in no way be connected to the previous calls.

I realise my way of writing can be confusing, so if you want me to clarify anything just ask.

Updated Answer to reflect edited question

'why not declare FileWriter, FileReader, BufferedReader and BufferedWriter at the top of the class as they did for the other variables?'

Okay, I assume you understand that the variables are not actually called FileWriter, FileReader, BufferedReader, and BufferedWriter, but rather this is the variable type. Their names are fw, fr, br, and bw. If you don't understand what I mean just ask. From now on I will refer to the variables by the names you did to make reading more easy, afterall fw just stands for FileWriter anyway so there should not be too much confusion.

The key to this question is hidden within the names of the variables themselves. Notice how they either end in Reader or Writer this can give us a subtle clue about their uses. Clearly FileWriter and BufferedWriter are to do with output in some way. By looking over the code we see that our suspicions were right and that at no point other than within the writeText(JTextArea area) method do these variables appear. So if the variable aren't used anywhere else within the code it would make logical sense to define and initialise them within the method that they are used in, not only does it make the code easier to read because we then "know" those variables are only related to that method, but also has the benefit of those variables being removed at the end of method execution, thereby not leaving variables in existence that were only used very briefly. By these rules we can say the same is true of FileReader and BufferedReader.

Observe this example about variable scope. (Look at the comments I added to the code)

public class DataBase {

private static String buf, retString = "\n"; // buf & retString - created
private static File file = new File("test.txt"); // file - created

public static void readText(JTextArea area) {   
    try {
        FileReader fr = new FileReader (file); // fr (FileReader) - created
        BufferedReader br = new BufferedReader(fr); // br (BufferedReader) - created
        while ((buf = br.readLine()) != null) {
            area.append(buf); 
            area.append(retString);
        }
        br.close();
        fr.close();
    } // fr (FileReader & br (BufferedReader) - destroyed
    catch (IOException e) {
        System.out.println("Exception: " + e);
    }
}

public static void writeText(JTextArea area) {
    try {
        FileWriter fw = new FileWriter (file); // fw (FileWriter) - created
        BufferedWriter bw = new BufferedWriter(fw); // bw (BufferedWriter) - created
        bw.write(area.getText());
        bw.close(); 
        fw.close();
    } // fw & bw - destroyed
    catch (IOException e) {
        System.out.println("Exception: " + e);
    }
}
} // buf, retString and file - Still exist as long as the object exists

From this example it becomes more clear as to why the variables are defined in the methods rather than as instance variables and initialised within the constructor. It allows for much cleaner code as well as being more readabe.

Why doing it every time the method is called rather than using maybe the same instance variable?

Well this question has to do with variable types. We couldn't reuse a single variable for all the information as the types would have needed to be different.

If we take all the variables from the code

private static String buf, retString = "\n"; // valid
private static File file = new File("test.txt"); // valid

FileReader fr = new FileReader (file); // valid
BufferedReader br = new BufferedReader(fr); // valid
FileWriter fw = new FileWriter (file); // valid
BufferedWriter bw = new BufferedWriter(fw); // valid

Now we know that we cannot place a value that is not of the same type as the variable into that variable so something like

FileReader fr = new BufferedReader(fr); // Is not valid!

Because the types simply don't match.

Make sense?

Answer from linuscash on Stack Overflow
Top answer
1 of 6
26

Yes, if you called myMethod() 10 times it will create 10 unique and separate objects.

The new keyword does exactly what it says on the tin, it creates a brand new object, irrespective of whether one already exists. It creates a new object and stuffs the reference to that object inside the variable it has been given, overwriting any previous value (object) the variable held.

Is the myObject variable reallocated every time?

Again, yes it would be re-allocated with a new object every time the method was called. An interesting note about this would be that the variable wouldn't "really" be re-allocated as you are defining the variable within the method body itself, so every time the method ends it will remove the variables that were defined within its' scope. So what it actually does is create 10 individual variables and assign 10 individual objects, although as I said the others should have been removed automatically so it wouldn't use any additional memory.

In a nutshell: should I write code like that only if I plan to invoke that method only once?

Well as I said, in the example above each object would be destroyed at the end of method execution (assuming you didn't assign the object reference to a variable outside the scope of the method) so in your example you could happily call the method as many times as you wanted but each time would in no way be connected to the previous calls.

I realise my way of writing can be confusing, so if you want me to clarify anything just ask.

Updated Answer to reflect edited question

'why not declare FileWriter, FileReader, BufferedReader and BufferedWriter at the top of the class as they did for the other variables?'

Okay, I assume you understand that the variables are not actually called FileWriter, FileReader, BufferedReader, and BufferedWriter, but rather this is the variable type. Their names are fw, fr, br, and bw. If you don't understand what I mean just ask. From now on I will refer to the variables by the names you did to make reading more easy, afterall fw just stands for FileWriter anyway so there should not be too much confusion.

The key to this question is hidden within the names of the variables themselves. Notice how they either end in Reader or Writer this can give us a subtle clue about their uses. Clearly FileWriter and BufferedWriter are to do with output in some way. By looking over the code we see that our suspicions were right and that at no point other than within the writeText(JTextArea area) method do these variables appear. So if the variable aren't used anywhere else within the code it would make logical sense to define and initialise them within the method that they are used in, not only does it make the code easier to read because we then "know" those variables are only related to that method, but also has the benefit of those variables being removed at the end of method execution, thereby not leaving variables in existence that were only used very briefly. By these rules we can say the same is true of FileReader and BufferedReader.

Observe this example about variable scope. (Look at the comments I added to the code)

public class DataBase {

private static String buf, retString = "\n"; // buf & retString - created
private static File file = new File("test.txt"); // file - created

public static void readText(JTextArea area) {   
    try {
        FileReader fr = new FileReader (file); // fr (FileReader) - created
        BufferedReader br = new BufferedReader(fr); // br (BufferedReader) - created
        while ((buf = br.readLine()) != null) {
            area.append(buf); 
            area.append(retString);
        }
        br.close();
        fr.close();
    } // fr (FileReader & br (BufferedReader) - destroyed
    catch (IOException e) {
        System.out.println("Exception: " + e);
    }
}

public static void writeText(JTextArea area) {
    try {
        FileWriter fw = new FileWriter (file); // fw (FileWriter) - created
        BufferedWriter bw = new BufferedWriter(fw); // bw (BufferedWriter) - created
        bw.write(area.getText());
        bw.close(); 
        fw.close();
    } // fw & bw - destroyed
    catch (IOException e) {
        System.out.println("Exception: " + e);
    }
}
} // buf, retString and file - Still exist as long as the object exists

From this example it becomes more clear as to why the variables are defined in the methods rather than as instance variables and initialised within the constructor. It allows for much cleaner code as well as being more readabe.

Why doing it every time the method is called rather than using maybe the same instance variable?

Well this question has to do with variable types. We couldn't reuse a single variable for all the information as the types would have needed to be different.

If we take all the variables from the code

private static String buf, retString = "\n"; // valid
private static File file = new File("test.txt"); // valid

FileReader fr = new FileReader (file); // valid
BufferedReader br = new BufferedReader(fr); // valid
FileWriter fw = new FileWriter (file); // valid
BufferedWriter bw = new BufferedWriter(fw); // valid

Now we know that we cannot place a value that is not of the same type as the variable into that variable so something like

FileReader fr = new BufferedReader(fr); // Is not valid!

Because the types simply don't match.

Make sense?

2 of 6
4

Yes, a new object is created every time. The reference to each myObject is allocated in the stack.

In a nutshell: should I write code like that only if I plan to invoke that method only once?

If you want myObject to disappear after the method execution is completed, then yes. If for some reason, you need to keep a reference to it, then you can declare it as a class member.

class MyClass {
    AnotherClass myObject;
    void myMethod() {
        myObject = new AnotherClass();
        myObject.doStuff();
    }
}

This way, it will still be created each time you call myMethod(), but it will still exist after myMethod completes. This can be handy, or not, depending on the situation.

Does the complier skip that like of code as it sees that the object has already been created and the variable myObject already been assigned to such object?

This won't happen when using new. It is guaranteed that it will create a fresh instance. It can be implemented using FactoryMethods (not the compiler skipping lines of code, but preventing the creation of a new object). For example, the Integer class implements this: If you try to get an integer between -128 and 127, it will always return the same instance (won't create a new object) when using its Factory Method valueOf

 Integer five = Integer.valueOf("5");//Will always return the same instance.
 Integer otherFive = Integer.valueOf("5");

 assert(five==otherFive);//true

Of course, using new won't return the same instance, but always a new one:

 Integer five = new Integer("5");//Will create a new object each time.
 Integer otherFive = new Integer("5");

 assert(five==otherFive);//false

After question update

There's really not much to say about the code you added. However, if you take a look, you'll notice two methods. Based on its names, once seems to write, the other one seems to read. That behaviour is specific to each method, so the method that writeFile doesn't care about objects used for reading. And the method readFile doesn't care about objects used to write. So there's no sense on making a fileReader available to the writeFile method, and so on.

Coming back to your original question, yes, this instantiates a new object each time the method is called. It's not important. It's preferable to having to ask yourself "why does the readFile method has access to a FileWriter instance?

🌐
DataCamp
datacamp.com › doc › java › new
new Keyword in Java: Usage & Examples
Java keywordsIntroduction To JavaJava File HandlingJava Language BasicsJava ArraysJava Object-Oriented Programming ... The new keyword in Java is a fundamental part of the language used to create new objects. It dynamically allocates memory for an object and returns a reference to that memory.
Discussions

[Java] What does the "new" keyword in java mean, in simple english?
Simply put, the new keyword creates a new object of the specified type. It does this by allocating memory for the object on the heap . So if you were to declare the following Scanner scanner1 = new Scanner(System.in); Scanner scanner2 = new Scanner(new File("some/path/to/file.txt"); You now have 2 different scanners that read input from different input streams. I don't understand why we have to use the new keyword and also Scanner after that. The reason why you have to use the keyword new followed by Scanner is you are telling Java to "create a new object of type Scanner, using the constructor Scanner(InputStream)" More on reddit.com
🌐 r/learnprogramming
34
107
October 10, 2017
Can someone help me understand the 'new' and 'this' keywords in java?
Tristan Gaebler is having issues with: How do I use 'new' and 'this' properly? There purposes really confuse me. How are they used in terms of OOP? More on teamtreehouse.com
🌐 teamtreehouse.com
2
March 21, 2016
Why did memory-managed languages like Java, Javascript, and C# retain the `new` keyword? - Software Engineering Stack Exchange
The new keyword in languages like Java, Javascript, and C# creates a new instance of a class. This syntax seems to have been inherited from C++, where new is used specifically to allocate a new in... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
Is using the "new"-keyword when creating a new object in JAVA redundant?
Because Java was heavily influenced by C++, especially early in its development. In C++, you use the new keyword to specify that you want to allocate an object (or array, or primitive data type) on the heap. C++ also gives you the option to allocate any data type, including built-in and user-defined objects, to the stack which is done without the use of the new keyword. Now Java does not allow for objects or arrays to be stack-allocated, so the use of the new keyword may seem redundant. But its inclusion was probably helpful for the first generation of Java developers, many of whom were probably C++ developers before that. More on reddit.com
🌐 r/learnprogramming
18
13
February 14, 2021
🌐
Reddit
reddit.com › r/learnprogramming › [java] what does the "new" keyword in java mean, in simple english?
r/learnprogramming on Reddit: [Java] What does the "new" keyword in java mean, in simple english?
October 10, 2017 -

I've just started learning java, and i'm not very familiar with the concepts of objects, i just started learning about taking in inputs in java and using scanner within the process. One thing I don't understand after I declare a variable and say it belongs in the class of a Scanner, why do i have to initialize it and type in "new Scanner(System.in)". I understand that the system.in used to get bytes from the keyboard but I don't understand why we have to use the new keyword and also Scanner after that.

EDIT : Thanks a lot for all the help everyone, i've now got pretty good understanding of the "new" keyword.

Top answer
1 of 5
66
Simply put, the new keyword creates a new object of the specified type. It does this by allocating memory for the object on the heap . So if you were to declare the following Scanner scanner1 = new Scanner(System.in); Scanner scanner2 = new Scanner(new File("some/path/to/file.txt"); You now have 2 different scanners that read input from different input streams. I don't understand why we have to use the new keyword and also Scanner after that. The reason why you have to use the keyword new followed by Scanner is you are telling Java to "create a new object of type Scanner, using the constructor Scanner(InputStream)"
2 of 5
16
Simple explanation: when you do int foo; there's no actual number in foo, you've created the variable, but not the value. Middle explanation: the new keyword actually creates the object and allocates memory for it. Deeper explanation: So you need to understand the concept of pointers. In Java you can't actually access pointers, but it's an important thing to understand. In languages like C a pointer is literally a number that's the memory address of something else. So your int* variable is a pointer, that tells you where in memory to find your int. This seems rather redundant at first, until you look at objects. The compiler has no idea how big your object is, or how big it might become. If you have an array in there it could be null or it could be a zillion items long. So, what does the compiler do? You do this: Image img; And the compiler says "OK, so we need to make sure we have enough space for one address (a handful of bytes), no problem". Then, later in the program, there's the line: img = open("vvvvvLargeImage.png"); And then the compiler can say "oh, that image is 100MB, let's allocate that much memory now". If the compiler had tried to allocate the memory before it knew what it was allocating it for it would be using more memory than needed, would need to free up that memory should the created object not fit in it and generally do stuff that's not needed.
🌐
NxtWave
ccbp.in › blog › articles › new-keyword-in-java
What is New Keyword in Java? | Learn Object Creation & Initialisation
The new keyword in Java is used to create objects, which are class instances. It has a role in allocating memory for the object and initialising it. When you use the new keyword, Java automatically calls the class's constructor.
🌐
W3Schools
w3schools.com › java › ref_keyword_new.asp
Java new Keyword
Java OOP Java Classes/Objects Java Class Attributes Java Class Methods Java Constructors Java this Keyword Java Modifiers · Access Modifiers Non-Access Modifiers Java Encapsulation Java Packages / API Java Inheritance Java Polymorphism Java super Keyword Java Inner Classes Java Abstraction Java Interface Java Anonymous Java Enum
Find elsewhere
🌐
PrepBytes
prepbytes.com › home › java › new keyword in java
new Keyword in Java
April 17, 2023 - The new keyword in Java is used to create an instance of a class, also known as an object.
🌐
GeeksforGeeks
geeksforgeeks.org › java › new-operator-java
new operator in Java - GeeksforGeeks
May 30, 2018 - The new operator instantiates a class by dynamically allocating(i.e, allocation at run time) memory for a new object and returning a reference to that memory. This reference is then stored in the variable.
🌐
W3Schools
w3schools.com › java › java_ref_keywords.asp
Java Keywords
Java OOP Java Classes/Objects Java Class Attributes Java Class Methods Java Constructors Java this Keyword Java Modifiers · Access Modifiers Non-Access Modifiers Java Encapsulation Java Packages / API Java Inheritance Java Polymorphism Java super Keyword Java Inner Classes Java Abstraction Java Interface Java Anonymous Java Enum
🌐
Quora
quora.com › How-does-the-keyword-New-works-in-Java
How does the keyword 'New' works in Java? - Quora
Answer (1 of 11): I guess you need some quick info about memory management in Java. The [code ]new[/code] keywoard indeed makes a number of things 1. allocates memory for the object 2. if a static initialiser exists for the class and this is the first time an object of that class is instantiate...
🌐
Scaler
scaler.com › topics › new-keyword-in-java
New Keyword in Java - Scaler Topics
May 13, 2022 - The new keyword in Java instantiates a class by allocating desired memory for an associated new object. It then returns a reference to that memory. Many times, the new keyword in Java is also used to create the array object.
🌐
Google
google.github.io › styleguide › javaguide.html
Google Java Style Guide
There is no fall-through in new-style switches. The Java language requires switch expressions and many kinds of switch statements to be exhaustive. That effectively means that every possible value that could be switched on will be matched by one of the switch labels.
🌐
Team Treehouse
teamtreehouse.com › community › can-someone-help-me-understand-the-new-and-this-keywords-in-java
Can someone help me understand the 'new' and 'this' keywords in java? (Example) | Treehouse Community
March 21, 2016 - When you create instances of the class (aka objects) you use those constructors. E.g., ... The first Student is the type, the s1 is the name you are giving the Student object that will be created, the = is the assignment operator, the new is the keyword that creates the object, the second Student is the constructor, and the ()s contain any parameters that need to be passed to the constructor to contract the object.
🌐
GeeksforGeeks
geeksforgeeks.org › java › classes-objects-java
Classes and Objects in Java - GeeksforGeeks
All instances of a class share structure and behavior while storing different state values. ... This only declares a reference. The object is not created and the reference holds null. ... The new operator allocates memory and invokes the constructor.
Published   3 weeks ago
Top answer
1 of 15
101

Your observations are correct. C++ is a complicated beast, and the new keyword was used to distinguish between something that needed delete later and something that would be automatically reclaimed. In Java and C#, they dropped the delete keyword because the garbage collector would take care of it for you.

The problem then is why did they keep the new keyword? Without talking to the people who wrote the language it's kind of difficult to answer. My best guesses are listed below:

  • It was semantically correct. If you were familiar with C++, you knew that the new keyword creates an object on the heap. So, why change expected behavior?
  • It calls attention to the fact that you are instantiating an object rather than calling a method. With Microsoft code style recommendations, method names start with capital letters so there can be confusion.

Ruby is somewhere in between Python and Java/C# in it's use of new. Basically you instantiate an object like this:

f = Foo.new()

It's not a keyword, it's a static method for the class. What that means is that if you want a singleton, you can override the default implementation of new() to return the same instance every time. It's not necessarily recommended, but it's possible.

2 of 15
91

In short, you are right. The new keyword is superfluous in languages like Java and C#. Here are some insights from Bruce Eckel who was a member of C++ Standard Committee in 1990s and later published books on Java:

[T]here needed to be some way to distinguish heap objects from stack objects. To solve this problem, the new keyword was appropriated from Smalltalk. To create a stack object, you simply declare it, as in Cat x; or, with arguments, Cat x("mittens");. To create a heap object, you use new, as in new Cat; or new Cat("mittens");. Given the constraints, this is an elegant and consistent solution.

Enter Java, after deciding that everything C++ is badly done and overly complex. The irony here is that Java could and did make the decision to throw away stack allocation (pointedly ignoring the debacle of primitives, which I've addressed elsewhere). And since all objects are allocated on the heap, there's no need to distinguish between stack and heap allocation. They could easily have said Cat x = Cat() or Cat x = Cat("mittens"). Or even better, incorporated type inference to eliminate the repetition (but that -- and other features like closures -- would have taken "too long" so we are stuck with the mediocre version of Java instead; type inference has been discussed but I will lay odds it won't happen. And shouldn't, given the problems in adding new features to Java).

🌐
Sololearn
sololearn.com › en › Discuss › 2824428 › what-is-purpose-of-new-keyword-in-java
What is purpose of new keyword in java? | Sololearn: Learn to code for FREE!
June 29, 2021 - in Java, with the exception of primitive types, all the others are dynamically allocated reference types, which is why they require the use of the new. Specifically, they are all objects, including arrays and to which the new is not necessary if an array literal is assigned, however, used to create an array object as happens for strings.
🌐
Medium
medium.com › codimis › understanding-the-new-keyword-in-java-be571dec090b
Understanding the new Keyword in Java
March 22, 2024 - So you use the new keyword, when you instantiate an object in Java. It serves as a directive to the Java Virtual Machine (JVM) to allocate memory for a new object.