How to use the toString method in Java?

前端 未结 13 929
说谎
说谎 2020-11-21 06:26

Can anybody explain to me the concept of the toString() method, defined in the Object class? How is it used, and what is its purpose?

13条回答
  •  猫巷女王i
    2020-11-21 06:56

    Use of the String.toString:

    Whenever you require to explore the constructor called value in the String form, you can simply use String.toString... for an example...

    package pack1;
    
    import java.util.*;
    
    class Bank {
    
        String n;
        String add;
        int an;
        int bal;
        int dep;
    
        public Bank(String n, String add, int an, int bal) {
    
            this.add = add;
            this.bal = bal;
            this.an = an;
            this.n = n;
    
        }
    
        public String toString() {
            return "Name of the customer.:" + this.n + ",, "
                    + "Address of the customer.:" + this.add + ",, " + "A/c no..:"
                    + this.an + ",, " + "Balance in A/c..:" + this.bal;
        }
    }
    
    public class Demo2 {
    
        public static void main(String[] args) {
    
            List l = new LinkedList();
    
            Bank b1 = new Bank("naseem1", "Darbhanga,bihar", 123, 1000);
            Bank b2 = new Bank("naseem2", "patna,bihar", 124, 1500);
            Bank b3 = new Bank("naseem3", "madhubani,bihar", 125, 1600);
            Bank b4 = new Bank("naseem4", "samastipur,bihar", 126, 1700);
            Bank b5 = new Bank("naseem5", "muzafferpur,bihar", 127, 1800);
            l.add(b1);
            l.add(b2);
            l.add(b3);
            l.add(b4);
            l.add(b5);
            Iterator i = l.iterator();
            while (i.hasNext()) {
                System.out.println(i.next());
            }
        }
    
    }
    

    ... copy this program into your Eclipse, and run it... you will get the ideas about String.toString...

提交回复
热议问题