๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_syntax.asp
Java Syntax
assert abstract boolean break byte case catch char class continue default do double else enum exports extends final finally float for if implements import instanceof int interface long module native new package private protected public return requires short static super switch synchronized this throw throws transient try var void volatile while Java String Methods

set of rules defining correctly structured programs

์ž๋ฐ” throwable
The syntax of Java is the set of rules defining how a Java program is written and interpreted. The syntax is mostly derived from C and C++. Unlike C++, Java has no โ€ฆ Wikipedia
๐ŸŒ
Wikipedia
en.wikipedia.org โ€บ wiki โ€บ Java_syntax
Java syntax - Wikipedia
November 10, 2025 - The Java syntax has been gradually extended in the course of numerous major JDK releases, and now supports abilities such as generic programming and anonymous functions (function literals, called lambda expressions in Java). Since 2017, a new JDK version is released twice a year, with each ...
๐ŸŒ
CodeGym
codegym.cc โ€บ quests โ€บ QUEST_JAVA_SYNTAX
New Java Syntax
You'll learn about classes, objects, methods, variables, data types, arrays, conditional operators, and loops. You'll take a quick look at collections and OOP, and you'll also start working in IntelliJ ...
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ specs โ€บ jls โ€บ se6 โ€บ html โ€บ syntax.html
Syntax
September 16, 2025 - ( class | ExplicitGenericInvocation | this | super Arguments | new [NonWildcardTypeArguments] InnerCreator ) ExplicitGenericInvocation: NonWildcardTypeArguments ExplicitGenericInvocationSuffix NonWildcardTypeArguments: < TypeList > ExplicitGenericInvocationSuffix: super SuperSuffix Identifier ...
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ java โ€บ java_basic_syntax.htm
Java - Basic Syntax
In Java, classes can be derived from classes. Basically, if you need to create a new class and here is already a class that has some of the code you require, then it is possible to derive your new class from the already existing code.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ new-operator-java
new operator in Java - GeeksforGeeks
May 30, 2018 - Syntax : class-name var-name; Example : // declare reference to an object of class Box Box mybox; A variable in this state, which currently references no object, can be illustrated as follows (the variable name, mybox, plus a reference pointing ...
๐ŸŒ
Javatpoint
javatpoint.com โ€บ new-keyword-in-java
Java new Keyword - Javatpoint
The Java new keyword is used to create an instance of the class. In other words, it instantiates a class by allocating memory for a new object and returning a reference to that memory. We can also use the new keyword to create the array object. - Learn basics of Java new Keyword
Find elsewhere
๐ŸŒ
Advanced Web Machinery
advancedweb.hu โ€บ new-language-features-since-java-8-to-21
New language features since Java 8 to 21 - Advanced Web Machinery
September 22, 2023 - Record Classes introduce a new type declaration to the language to define immutable data classes. Instead of the usual ceremony with private fields, getters and constructors, it allows us to use a compact syntax:
๐ŸŒ
Wikibooks
en.wikibooks.org โ€บ wiki โ€บ Java_Programming โ€บ Keywords โ€บ new
Java Programming/Keywords/new - Wikibooks, open books for an open world
new is a Java keyword. It creates a Java object and allocates memory for it on the heap. new is also used for array creation, as arrays are also objects. Syntax: <JavaType> <variable> = new <JavaObject>(); For example: See also: Java Programming/Creating Objects ยท
๐ŸŒ
DataFlair
data-flair.training โ€บ blogs โ€บ basic-java-syntax
Java Syntax - A Complete Guide to Master Java - DataFlair
April 5, 2024 - Once we define a class, we can create the object of a class by the following simple syntax. These are the instances of the class: < class - name > <object - name > =new < class - name of instance creation > ()
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ specs โ€บ jls โ€บ se7 โ€บ html โ€บ jls-18.html
Chapter 18. Syntax
September 16, 2025 - Identifier [Arguments] . ExplicitGenericInvocation . this . super SuperSuffix . new [NonWildcardTypeArguments] InnerCreator [ Expression ]
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?

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-basic-syntax
Java Syntax - GeeksforGeeks
July 10, 2025 - Java Syntax refers to a set of rules that define how Java programs are written and interpreted by the compiler. These rules ensure that your code is readable, logically correct, and error-free.
๐ŸŒ
CodeGym
codegym.cc โ€บ java blog โ€บ random โ€บ java syntax: introduction to programming language
Java Syntax
December 3, 2024 - In addition to primitive data types Java has such a type as enum or enumeration. Enumerations represent a collection of logically related constants. An enumeration is declared using the enum operator, followed by the name of the enumeration. Then comes a comma-separated list of enumeration elements: enum DayOfWeek { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } An enumeration actually represents a new type, so we can define a variable of that type and use it.
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ ref_keyword_new.asp
Java new Keyword
The new keyword creates new objects. Read more about objects in our Java Classes/Objects Tutorial.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ core java โ€บ introduction to basic syntax in java
Introduction to Basic Syntax in Java | Baeldung
June 4, 2025 - Keywords are reserved words that have special meaning in Java. For example, public, static, class, main, new, instanceof, are keywords in Java, and as such, we canโ€™t use them as identifiers (variable names).
๐ŸŒ
Oracle
docs.oracle.com โ€บ en โ€บ java โ€บ javase โ€บ 17 โ€บ language โ€บ java-language-changes.html
Java Language Updates
October 11, 2024 - In Java SE 9, you donโ€™t need to declare r1 and r2: // New and improved try-with-resources statement in Java SE 9 try (resource1; resource2) { ...