Google+

Like Us On Facebook


Total Pageviews

270. Reducing the object creation statements









We can reduce the object creation statements as shown in the below examples -

Example1 -

Original -

File file1 = new File("abc.txt");

FileWriter fw = new FileWriter(file1);

We can reduce the above two sentences to the below single sentence -

FileWriter fw = new FileWriter(new File("abc.txt"));


Example2 -

Original -

File file1 = new File("abc.txt");

FileWriter fw = new FileWriter(file1);

We can reduce the above two sentences to the below single sentence -

FileWriter fw = new FileWriter("abc.txt");


Lets implement these examples on Eclipse IDE by editing the Java Classes created in our previous posts -

1. Launch Eclipse IDE, open the existing Java Class 'FileWriterDemo.java' from the 'Project 51' as shown below -



2. Reduce the above two lines in the program to a single line as shown below (i.e. by creating the File Class object inside the FileWriter Class object creation statement) -


3. Save & Run the program and observe that the 'How are you doing today?' text got added to the 'abc.txt' file in our project workspace as shown below -



4. Now lets modify the statement as shown below (i.e. by just mentioning the file path directly in the FileWriter Class object creation statement instead of creating a File Class object for the file)  -



5. Remove the text from the 'abc.txt' file in our project workspace as shown below -



6. Save & Run the program and observe that the text 'How are you doing today?' got added to the 'abc.txt' file in our project workspace as shown below -



Hence we can reduce the object creation statements to a single sentence in any of the above two methods (i.e. which ever is applicable for the situation). Some time, when need to perform operations on the File Class object, we may not be able to reduce the sentences. to one sentence.







Please comment below to feedback or ask questions.

Using PrintStream I/0 Class will be explained in the next post.





No comments:

Blog Index