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 7 of 7

Thread: Some Theory based questions

  1. #1
    Junior Member
    Join Date
    Aug 2010
    Location
    UK
    Posts
    19
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Some Theory based questions

    I've been studying I/O recently, using the Sun tutorials mainly as my primary resoucre and I've come across I few syntactical issues that I don't quite understand and would appreciate any light at all you guys could shine on them.

     BufferedReader inputStream = 
                new BufferedReader(new FileReader("xanadu.txt"));

    I realise in the above that a BufferedReader class is being declared and instantiated, with the argument being passed to it being a FileReader. This I believe is an example of chaining right? But I guess the big question I find myself asking is why isn't there a reference being made for the FileReader class? why just the instantiation by itself?

    And secondly, am I right in thinking that the FileReader class is a high level stream? Which thus means it requires a low level one to even be operating. Where is this if this is the case - is it just assumed within Java?

    Thanks for any help.


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Some Theory based questions

    This I believe is an example of chaining right? But I guess the big question I find myself asking is why isn't there a reference being made for the FileReader class? why just the instantiation by itself?
    This is something called Creating an Anonymous Object (or at least that is what my compiler seems to call it). Basically, in JAVA you can create Objects Anonymously (without giving them variable names), provided you will only use it once. Since you never plan on ever using the FileReader Object initalized with the statement
    new FileReader("xanadu.txt")
    ever again, it is perfectly fine to do this. Essentially, you are just using this Object to initialize another Object (the BufferedReader in this example) so it, in a way, gets immediately garbage collected after use. If, however, you ever wanted to access that Anonymous Object, there would be no possible way of doing so; unless the Object you initialized it with has backwards referencing (like JFrames and getting Content Panels) or if you have stored the Anonymous Object in a Data Structure (like an ArrayList).

    So, some more examples of Anonymous Declaration are:
    Sometimes you want to add an Object, like a JLabel for example, to an ArrayList (type of Data Structure). If we wanted to initalize 5 JLabels, all with the default text of "Test", and store them all in an ArrayList, here are two ways:
    ArrayList<JLabel> list = new ArrayList<JLabel>();
     
    //Without Anonymous Declarations
    for(int i=0;i<5;i++)
    {
    	JLabel label = new JLabel("Test");
    	list.add(label);
    }
     
    //With Anonymous Declaration
    for(int i=0;i<5;i++)
    {
    	list.add(new JLabel("Test"));
    }
    Both of these ways will do the same. So, what are the disadvantages of Anonymous Declaration? Well, you cannot directly set an Object's Variables or call an Object's Methods if it is Anonymous. For example, if we wanted to create our ArrayList of JLabels again, but this time we wanted to initalize the JLabel, but then set its text, we would have to do this:
    ArrayList<JLabel> list = new ArrayList<JLabel>();
     
    //Without Anonymous Declarations
    for(int i=0;i<5;i++)
    {
    	JLabel label = new JLabel();
    	label.setText("Test");
    	list.add(label);
    }
     
    //With Anonymous Declaration
    for(int i=0;i<5;i++)
    {
    	list.add(new JLabel());
    	list.get(list.size()-1).setText("Test");
    }
    The first way of doing it (without Anonymous Declaration) is pretty straight forward. But the second one takes a little bit more work. Since we cannot directly reference the JLabel when it is declared Anonymously, we have to reference it from the ArrayList we added it to. So, since the ArrayList.add() method adds the element to the end of the ArrayList, we need to call the last element in the ArrayList and then set the text. Once again, both ways end with the same result, but for this example, the first way is much more efficient.


    You can also Anonymously Declare Classes. This is a much more advanced topic, and I have really only found this relevant for GUI stuff. When you add Listeners to GUI Objects, the JAVA Listeners are Interfaces. So, every time you add a Listener to a GUI Object, you need to create a new Class that implements the Interface (or extends the Abstract Adapter if one is provided for that Listener). Here is an example of doing this (from code I wrote today actually, but edited for your understanding and relevance):
    JButton loadData = new JButton("Load File");
    loadData.addActionListener(new ActionListener(){
        		public void actionPerformed(ActionEvent e)
        		{
        			//Action When Button is Pressed
        		}
        	});
    As you can see, I created a new ActionListener. But since ActionListener is an Interface, I had to also Anonymously create the Class I needed to make that extends ActionListener. It is sort of confusing to understand, especially when you are a JAVA beginner. Until you get into a more advance JAVA that involves GUIs, keep the concept of Anonymous Classes on your back-burner.

    And secondly, am I right in thinking that the FileReader class is a high level stream? Which thus means it requires a low level one to even be operating. Where is this if this is the case - is it just assumed within Java?
    FileReader's description is:
    Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.

    FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream.
    FileReader, and most other Classes, will be accessed by importing them in JAVA. JAVA has a rich library of Standard Classes and Objects, but most have to be imported. For your example, you would have to import BufferedReader AND FileReader. NOTE: It is important to know that a compiler will sometimes send you a "Symbol Not Found" or "Variable Not Found" Exception for an Anonymous Object instead of the expected "Symbol Class Not Found" Exception. To import those, you have to locate them in the API. If your IDE doesnt automatically import, you can find the location of the Object by doing the following Google Search:
    java+[Object You Are Looking For]+6
    So, to find FileReader, I just searched:
    java+FileReader+6
    And it was the first link.
    From JAVA Docs, look toward the top of the page and you should see something like:
    java.io
    Class FileReader

    java.lang.Object
    extended by java.io.Reader
    extended by java.io.InputStreamReader
    extended by java.io.FileReader
    So, we now know that the FileReader class can be found in the java.io library, under the name FileReader. So when we import, we want to say:
    import java.io.FileReader;


    That should answer your questions. Tell me if you have any more questions or if something needs to be clarified.
    Last edited by aussiemcgr; September 30th, 2010 at 09:12 PM.

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

    Bacon n' Logic (October 1st, 2010)

  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: Some Theory based questions

    Look at this from a memory point of view:

    In Java, all non-primitive variables are essentially pointers (i.e. they point to a spot in memory). At that spot in memory, you will find a chunk of data which represents an object of that type. What the new keyword does is allocate memory for a new object of a certain type, and the constructor initializes this memory chunk. The memory address of where that chunk of data resides is then returned from the new operation.

    From this point, you have a few choices on what to do with that memory address:
    1. Assign it to a variable of that type.
    2. Nothing (It will eventually be garbage collected)
    3. access fields/methods of the object located at that memory address.
    4. Pass it as an argument of a method.

    Case 4 is what's being done here (in fact, this is basically what's done when you pass a regular object variable, it just passes the memory address).

    FileReader has some lower-level implementation, as do many portions of the Java API (possibly via JNI, the exact details aren't too important to the Java programmer).

  5. #4
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Some Theory based questions

    Quote Originally Posted by helloworld922 View Post
    2. Nothing (It will eventually be garbage collected)
    In most cases, yes,but this can't be stated categorically.
    public class Something {
      private List list = new ArrayList();
     
      public static void main(String[] args) {
        new MyClass(list);
        System.out.println(list.get(0));
      }
    }
     
    class MyClass {
     
      private static int count;
     
      public MyClass(List list) {
        list.add(this);
        count++;
      }
     
      @Override
      public String toString() {
        return "MyClass " + count;
      }
    }
    Note:code typed here, may have typos or other bugs. I just wanted to demonstrate a scenario in which a constructor may have a side effect of creating a reference to the newly created object via a parameter.

    db
    Last edited by Darryl.Burke; October 1st, 2010 at 01:09 AM.

  6. #5
    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: Some Theory based questions

    Quote Originally Posted by Darryl.Burke View Post
    In most cases, yes,but this can't be stated categorically.
    public class Something {
      private List list = new ArrayList();
     
      public static void main(String[] args) {
        new MyClass(list);
        System.out.println(list.get(0));
      }
    }
     
    class MyClass {
     
      private static int count;
     
      public MyClass(List list) {
        list.add(this);
        count++;
      }
     
      @Override
      public String toString() {
        return "MyClass " + count;
      }
    }
    Note:code typed here, may have typos or other bugs. I just wanted to demonstrate a scenario in which a constructor may have a side effect of creating a reference to the newly created object via a parameter.

    db
    touche I didn't consider this when writing that.

  7. #6
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Some Theory based questions

    Quote Originally Posted by Bacon n' Logic View Post
     BufferedReader inputStream = 
                new BufferedReader(new FileReader("xanadu.txt"));

    This I believe is an example of chaining right?
    To add to those that probably already answered your primary question, I'll just allude to the sentence quote above: this is a good example of the Decorator Pattern. Its a design pattern to add functionality and behavior to an object dynamically. See Decorator pattern - Wikipedia, the free encyclopedia

  8. #7
    Junior Member
    Join Date
    Aug 2010
    Location
    UK
    Posts
    19
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Some Theory based questions

    Can I just say I big thanks to everyone who has posted on here; I think I've gained some understanding on the topic from all the responses made. And the examples in particular have been great btw aussie, cheers!

Similar Threads

  1. Problem with loop theory
    By Lord eMO in forum Loops & Control Statements
    Replies: 1
    Last Post: October 27th, 2017, 07:46 PM
  2. Theory Inquiry
    By b_jones10634 in forum JavaServer Pages: JSP & JSTL
    Replies: 2
    Last Post: August 19th, 2010, 08:21 AM
  3. [SOLVED] theory behind testing each element of an array.
    By etidd in forum Java Theory & Questions
    Replies: 2
    Last Post: February 5th, 2010, 09:04 AM
  4. Theory behind 2d Game making?
    By DarrenReeder in forum Java Theory & Questions
    Replies: 3
    Last Post: January 28th, 2010, 02:54 AM
  5. type substitution - whats the theory behind it
    By mds1256 in forum Java Theory & Questions
    Replies: 0
    Last Post: January 20th, 2010, 07:40 PM