Automatic use of toString() in println

Hi.
A novice here preparing for the Java 2 Programmer exam. Came across a question in one of the books and I'm left slightly confused about something which I can't get answered. Here goes...
class ToString
     public static void main( String[] args ) {
          MyClass[] arr = new MyClass[5];
          arr[0] = new MyClass();
          System.out.println(arr[0]);
          System.out.println(arr[0].toString());
          System.out.println(arr[1]);     // line 8
          System.out.println(arr[1].toString());     // line 9
class MyClass {
     public String toString() { return "my own implementation of toString"; }
When run produces...
my own implementation of toString
my own implementation of toString
null
java.lang.NullPointerException
     at ToString.main(ToString.java:9)
My question is why line 8 prints null, but line 9 does not. Well, the other way around really, I understand why line 9 produces an exception, but how does line 8 manage to produce null output?
I was under the impression that when an object is used in a println method that it's toString() method is invoked, if it doesn't have one then the toString() method on the Object class is invoked. If this is the case then surely line 8 is equivalent to line 9, unless java just sees the "." in line 9 against a null reference and throws it out because of that.
Thanks.

Because it actially calls String.valueOf(argument). Which is defined roughly as
public static String valueOf(Object object) {
    return object == null ? "null" : object.toString();

Similar Messages

  • Error using Arrays.toString()

    Hi there,
    I am getting the following error using Arrays.toString on a String Array. 'toString() in java.lang.Object cannot be applied to (java.lang.String[]).
    The line in question is at the bottom of the below code. It starts 'rtitem.appendText.....
    import lotus.domino.*;
    //import java.util.Arrays;
    public class JavaAgent extends AgentBase {
         Database curDb;
         String[] dbList;
         public void NotesMain() {
         int dbcount = 0;
              try {
                   Session session = getSession();
                   AgentContext agentContext = session.getAgentContext();
                   //get current database
                   Database curDb = agentContext.getCurrentDatabase();
                   //build a list of servers;
                   String[] servers = {"Norwich002/Norwich/MoneyCentre","Norwich003/MoneyCentre","Norwich004/MoneyCentre","Norwich005/MoneyCentre","Norwich007/Norwich/MoneyCentre","Norwich008/Norwich/MoneyCentre","Norwich010/Norwich/MoneyCentre","Norwich020/Norwich/MoneyCentre","Norwich021/Norwich/MoneyCentre"};
                   //loop through server list
                   int arraylen = servers.length;
                   for(int i=0;i <= arraylen;i++){
                        //create a notesdbdirectory collection for the current server iteration
                        DbDirectory dbdir = session.getDbDirectory(servers);
                        //get first database
                        Database db = dbdir.getFirstDatabase(DbDirectory.DATABASE);
                        //loop through databases in dbdir
                        while (db != null){
                             //add database details to our list
                             dbList[dbcount] = db.getTitle() + " - " + db.getFilePath();
                             dbcount++;     
              } catch(Exception e) {
                   e.printStackTrace();
              private boolean sendEmail(String subject){
                   try{
                        Document mailDoc = curDb.createDocument();
                        mailDoc.replaceItemValue("SendTo","Hayleigh S Mann/Norwich/MoneyCentre");
                        mailDoc.replaceItemValue("Subject",subject);
                        RichTextItem rtitem = mailDoc.createRichTextItem("Body");
                        rtitem.appendText(java.util.Arrays.toString(dbList));
                        mailDoc.send();
                        return true;
                   }catch(Exception e){
                        e.printStackTrace();
                        return false;

    No, that doesn't make any sense. Arrays.toString can take any array as an arg: [http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#toString(java.lang.Object[])]
    import java.util.*;
    public class A {
      public static void main(String[] args) {
        String str = Arrays.toString(args);
        System.out.println(str);
    :; java -cp . A abc 123 xxx
    [abc, 123, xxx]

  • How to use String toString?

    hey guys,
    I've 2-D array and i would like to printout using String toString method. I'v used that method to printout non-array values but I really don't know how to display 2-D array using the String toString method. Can someone please help me? thanks in advance!

    I do not understand your question. Please post
    whatever code you have and indicate where you are
    stuck.I'm sure you're aware of the String toString method which is often used to display the output in different classes without the main method.
    I've following code:
    public static int bingoCard [][] = new int[SIZE][SIZE]; 
    public BingoCard()   {
            Integer ran = 0;
            for (i = 0; i < SIZE; i ++) {
                 if (i == 0) {
                    min = 1;
                    max = 15;
                } else {
                    min = max + 1;
                    max += 15;
    //             System.out.println("Min: " + min + " " + "Max: " + max);
                // generate all 15 balls in this range
                for (j = min; j <= max; j++) {
                    bC.add(new Integer(j));               
    //             // randomize the 15 balls           
                for (j = 0; j < SIZE; j++) {
                    while (bingoCard[i][j] == 0) {
                        ran = (Integer)bC.removeRandom(); // get Integer object back
                        if (max <= 15 && (ran.intValue() >= 1 && ran.intValue() <= 15))
                            bingoCard[i][j] = ran.intValue();              
                        else if(max <= 30 && (ran.intValue() >= 16 && ran.intValue() <= 30))
                            bingoCard[i][j] = ran.intValue();           
                        else if(max <= 45 && (ran.intValue() >= 31 && ran.intValue() <= 45))
                            bingoCard[i][j] = ran.intValue();              
                        else if(max <= 60 && (ran.intValue() >= 46 && ran.intValue() <= 60))
                            bingoCard[i][j] = ran.intValue();             
                        else if(max <= 75 && (ran.intValue() >= 61 && ran.intValue() <= 75))
                            bingoCard[i][j] = ran.intValue();
    //                 System.out.println("Numbers in the card: " +  bingoCard[i][j]);
            bingoCard[2][2] = 0;       
    Now, i want to dipslay the bingoCard[][] using following method
    public String toString () { // return that array } instead of using following method which displays it for now
    public static void display () {
            for ( i = 0; i < SIZE; i++) {
                 System.out.print(" "+ columnTitles[i] +"   ");
            System.out.println(); 
            for (i = 0; i < SIZE; i++) {  
                for (j = 0; j < SIZE; j++) {               
                    System.out.print(" "+bingoCard[j] +" ");
    if (bingoCard[j][i] < 10)
    System.out.print(" ");
    System.out.println();
    Any help would be really apperciated. =]

  • I have an itunes gift card balance on my account however I want to use my credit card to pay for songs. It automatically uses my balance and doensn't give me the option of using my credit card. In detail how do I change it or must I use my balance first?

    I have an itunes gift card balance on my account however I would rather use my credit card to pay for my music downloads. I cannot find an option to choose credit card over my balance, it just automatically uses my gift card balance instead. Is there a way to change this? I have gone to account settings but cannot find a way to do this. Does anyone have any detailed information on how this could be achieved? Is it even possible? Thanks so much in advance!

    Sorry, but there's no way to force the iTunes Store to use your credit card. If there's a credit balance available, purchases will be deducted from that first.
    Regards.

  • Reporting Services will not automatically use a different replica for the report server databases when a failover occurs. How to overcome this issue

    Reporting Services offers limited support for using AlwaysOn Availability Groups with report server databases. The report server databases can be configured in AG to be part of a replica; however Reporting Services will not automatically use a different
    replica for the report server databases when a failover occurs. How to overcome this issue? is there any workaround for that..
    Rahul

    Hi.
    With the AlwaysOn listener you should have a single DNS name to connect to regardless of which cluster node is active. Are you using the listener service? If not, please refer to the link below.
    http://msdn.microsoft.com/en-us/library/hh213417.aspx#AGlisteners

  • How to change or Switch - scroll direction - automatic using registry keys

    how to change or Switch - scroll direction on TouchPad Synaptics - automatic using registry keys   ?

    Hi jrv
    How to explicitly take ownership of the subkey?
    System.Security.AccessControl.InheritanceFlags 
    I try use value
    "ContainerInherit、ObjectInherit、None", and It only take permission in root key.

  • Will a Pixma automatically use the alternate black cartridge?

    When the 220 black cartridge in my Pixma goes empty will the printer automatically use the 221 black instead? I now have three 221 blacks on the shelf and would just as soon use them up instead of buying a 220.

    Hi PRambler,
    The reason for the two different black ink tanks is for the different types of printing your unit is able to perform.  They are not intended as backups to each other. 
    The larger black tank is pigment based, and is primarily used for standard black text printing or output.  The smaller black ink tank is dye based like the color inks, and is used for photo and graphics output. 
    They are designed to complement each other, allowing the printer to produce the best possible black text output or photo quality as appropriate. 
    Did this answer your question? Please click the Accept as Solution button so that others may find the answer as well.

  • Can I create slides automatically using a master slide with text placeholders if I have a database of the content?

    I'm using Keynote, and I have a presentation that is over 100 slides all identical to the master slide. There are several placeholder text elements, and I have a database of all the text elements.
    Is there any way to do a "merge" to create the slides automatically using the master slide template?

    Sure, you can build in and out as many text boxes as you like -- just add a new text box, put in the text, and set the build for it. Do be aware, however, that the timing you get will not be very precise.
    If you specifically want to present song lyrics synched to audio, you might find that there are better alternatives than Keynote. Brian Peat, who contributes here regularly, has a comprehensive list of song presentation software. This list may have a better option for you.

  • Generate CSV automatically using excel macro

    Hi,
    We actually make dimension hierarchy in excel and then make a CSV file and then load it into planning application. The CSV file containing parent child relationship of dimension members and other properties are made manually.
    Can anyone help me regarding how can we generate CSV file automatically using excel macro and vba editor for dimension loading purpose???
    Thanks
    Agniva Chatterjee

    You would need to write the VBA code yourself to populate the spreadsheet, I am not sure what you are expecting the forum to provide.
    Cheers
    John
    http://john-goodwin.blogspot.com/

  • My MacBook Pro recognizes which of my three printers is plugged in (USB), but can it automatically use that printer or do I have to select that printer from the list each time I switch between printers?

    My MacBook Pro recognizes which of my three printers is plugged in (USB), but can it automatically use that printer or do I have to select that printer from the list each time I switch between printers?

    My MacBook Pro recognizes which of my three printers is plugged in (USB), but can it automatically use that printer or do I have to select that printer from the list each time I switch between printers?

  • I want to build a website that can send out email automatically using c#

    I want to build a website that can send out email automatically using c# and sql server when a date has reached. I have googled but nothing works.
    http://www.quartz-scheduler.net/documentation/quartz-2.x/tutorial/using-quartz.html
    I came across this, but I am still unsure what to do. 

    I came across this, but I am still unsure what to do
    http://forums.asp.net/

  • WPA2 does not allow “Automatically use my Windows logon name &password"

    I have setup WPA2 and I can logon to the domain but Windows XP SP2 still askes for user authentication.
    Even though I am using windows to pass the user name and password. i.e. The "Network Connections", "Wireless Properties", "Authentication", “Protected EAP Properties”, “EAP MSCHAPv2 Properties”, “Automatically use my Windows logon name and password (and domain if any)” checkbox is enabled.
    Has anyone seen this issue?
    Thanks

    Access ACS server using loop back address using JAVA enabled web browser and create a administrative user. After that try accessing ACS using Administrator username and password.

  • BODI and automatic use of table alias

    I have a problem with BODI's automatic use of table alias as the same as the table name, when the table name is a reserved word.
    I'm reading from an Informix database, where I've got a table named aggregate. This is a reserved word and gives me problems when BODI is generating the optimized SQL for my select statement.
    The generated SQl would look like this (simplified):
    SELECT  aggregate.aggr_id
    FROM informix.aggregate aggregate
    This will fail (I'm using an odbc connection), due to syntax error.
    Running this within Aqua Studio will also fail. Changing the table alias to aggr will work fine.
    My question is how I can prevent or owerride BODI's use of aggregate as the table alias in this case.

    Have you tried the Templates?
    1. Select Tools > General Options
    2. Expand Naming Standards and select Templates
    3. Set the template structure you want to use. I used abbreviation (table) or short name(entity) here. i.e use the "Add Variable button to see the options available and add as required. In this instance I'd suggest using the abbreviation e.g. for the primary key I have {table abbr}_PK. Note that you can use "substr" here too.
    4. Apply the change and go to the model.
    Now these template work in 3 different ways.
    1. When transforming or forward engineering the logical to relational models, the templates are applied to the key creation.
    2. In the Relational diagram when drawing new relationships between tables or adding new constraints.
    3. After the fact, if you apply the templates. Either 1 at a time or globally.
    a. To update a single table: To do this select any table and invoke the property palette. Select the Naming Rules button. Check the rules you want to update and click OK. The templates are now applied to your table, renaming the keys.
    b. To update multiple tables, select the relational model mode int he Browser, right-click for the context menu and select "Apply Naming Standards" This will update all the items in the model using the template structure set. Please note, regrettably this last (3b), does not work in the latest patch release, but if you are on the initial production release, then the tables are all updated. This has been bugged and fixed and so will be rectified in the next release.
    Regards
    Sue

  • HT201320 I have two email accounts. However, the iPad automatically uses the account that I only want to use for business. How can I change the account from which mail is sent and received?

    I have two email accounts. However, the iPad automatically uses the account that I only want to use for business. How can I change the account from which mail is sent and received?

    You are most welcome

  • Problem merging clips automatically using audio waveforms

    I am new to Premiere Pro CC and am trying to use CC's new audio synch feature. I'm following the steps outlined in this video http://tv.adobe.com/watch/learn-premiere-pro-cc/merge-clips-automatically-using-audio-wave forms/. Even though production used a slate, and camera has audio reference, I am unable to synch, and keep getting this message: "Could not synchronize one or more clips in the current selection because a match could not be found." Any thoughts?

    It doesn't seem to work when you include a stand alone audio file.  I'd consider it a bug.
    https://www.adobe.com/cfusion/mmform/index.cfm?name=wishform

Maybe you are looking for

  • Creating an instance of a class from within another class

    I am trying to create an instance of MCQ in the T class but I am getting this error: File: E:\JAVA PROGRAMS\assignment 1\T.java [line: 15] Error: cannot find symbol symbol : class MCQ location: class T here are the two classes: // class T import java

  • Used variable substitution to substiture the field 'date' in file name

    Hi gurus I have used variable substitution to substiture the field 'date' (dd/MM/yyyy/hh/mm/ss) in the file name so when empty payload (a valid xml ) is generated by Message mapping then the communication channel is failing by showing the following e

  • Imac+FCE+miniDVD=confusion

    Sorry to post such a newb question, but my old Super 8 is dead, so I bought a Sony MiniDVD assuming I could edit through a fire wire. Not so...how do I transfer video from the MiniDVD to the imac?

  • Sdo_util.getvertices not working

    I tried to run the sdo_util.getvertices on a simple table of points. Here is the sql and the error: SQL> select c.city_name, t.x, t.y 2 from cities c, table(SDO_UTIL.GETVERTICES (c.geometry)) t; from cities c, table(SDO_UTIL.GETVERTICES(c.geometry))

  • Can I use CallableStatement in JSTL?

    Is it possible to use CallableStatements in JSTL? I would like to be able to do something like this: <sql:update var="res" sql="{ ? = call rms.campaigns.s_code_update(?, ?, ?, ?) }" > <sql:param value="${item1}" /> <sql:param value="${item2}" /> <sql