how can I return a String? - java

package book1;
import java.util.ArrayList;
public abstract class Book {
public String Book (String name, String ref_num, int owned_copies, int loaned_copies ){
return;
}
}
class Fiction extends Book{
public Fiction(String name, String ref_num, int owned_copies, String author) {
}
}
at the moment when i input values into the variable arguments and call them with this :
public static class BookTest {
public static void main(String[] args) {
ArrayList<Book> library = new ArrayList<Book>();
library.add(new Fiction("The Saga of An Aga","F001",3,"A.Stove"));
library.add(new Fiction("Dangerous Cliffs","F002",4,"Eileen Dover"));
for (Book b: library) System.out.println(b);
System.out.println();
}
}
i get a return value of this:
book1.Fiction#15db9742
book1.Fiction#6d06d69c
book1.NonFiction#7852e922
book1.ReferenceBook#4e25154f
how can i convert the classes to return a string value instead of the object value? I need to do this without changing BookTest class. I know i need to use to string to convert the values. but i don't know how to catch the return value with it. could someone please point me in the right direction on how to convert this output into a string value?

You need to overwrite the toString() Method of your Book class. In this class you can generate a String however you like. Example:
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.author).append(": ").append(this.title);
return sb.toString();
}

You need to override the toString() method in your Book or Fiction class. The method is actually declared in the Object class, which all classes inherit from.
#Override
public String toString(){
return ""; // Replace this String with the variables or String literals that you want to return and print.
}
This method is called by System.out.println() and System.out.print() when they receive an object in the parameter (as opposed to a primitive, such as int and float).
To reference the variables in the method, you'll need to declare them in the class and store them via the class's constructor.
For example:
public abstract class Book {
private String name;
private String reference;
private int ownedCopies;
private int loanedCopies;
public Book (String name, String reference, int ownedCopies, int loanedCopies) {
this.name = name;
this.reference = reference;
this.ownedCopies = ownedCopies;
this.loanedCopies = loanedCopies;
}
#Override
public String toString(){
return name + ", Ref:" + reference + ", OwnedCopies: " + ownedCopies + ", LoanedCopies: " + loanedCopies; // Replace this String with the variables or String literals that you want to return and print.
}
}

The classes you have defined, don't store any values. It is in other words useful to construct a new book. You need to provide fields:
public abstract class Book {
private String name;
private String ref_num;
private int owned_copies;
private int loaned_copies;
public String Book (String name, String ref_num, int owned_copies, int loaned_copies) {
this.name = name;
this.ref_num = ref_num;
this.owned_copies = owned_copies;
this.loaned_copies = loaned_copies;
}
public String getName () {
return name;
}
//other getters
}
Now an object is basically a set of fields. If you want to print something, you can access and print one of these fields, for instance:
for (Book b: library) System.out.println(b.getName());
In Java, you can also provide a default way to print an object by overriding the toString method:
#Override
public String toString () {
return ref_num+" "+name;
}
in the Book class.

Need to give your object Book a ToString() override.
http://www.javapractices.com/topic/TopicAction.do?Id=55
Example:
#Override public String toString()
{
return name;
}
Where name, is a string in the Class.

I am hoping that you have assigned the passed arguments to certain attributes of the classes. Now, once you are done with that, you can override the toString() method in Book to return your customized string for printing.

Related

String s1=new String("demo"); While printing why does it give output as the given string?

If we create a String like below and print the value:
String s=new String("demo");
System.out.println(s);
...the output is:
demo
Good. This is the expected output. But here String is a class. Remember that. Below is another example. For example, take a class like this:
class A
{
public static void main (String args[])
{
A a =new A();
A a1=new A("hi"); //we should create a Constructor like A(String name)
System.out.println(a1); //here O/P is address
}
}
My doubt is that I created the A instance in the same way I created the new String object, and I printed that object. So why does it not print the given String for the instance of A?
You need to override the Object#toString() in your class. By default, the toString() method of Object is called.
Also, to print the value, you just need to override the method as internally a call will be made to the toString() method when this statement is executed.
System.out.println(a1);
Sample overriden toString() method.
#Override
public String toString() {
// return a string value
return "The String representation of your class, as per your needs";
}
You have to override toString() method in your class the way you want to print something when call System.out.println();. In String class toString() method has override and you will get out put above due to that.
As pointed out already, you need to override the default toString() method inherited from the Object class. Every class automatically extends the Object class, which has a rather simple toString(), which can't know how to turn your particular object into a String. Why should it, especially if your class is arbitrarily complex? How is it supposed to know how to turn all your class's fields into a "sensible" string representation?
In the toString() of your class, you need to return the string that you want to represent your class with. Here is a simple example:
class A {
String foo;
public A(String foo) {
this.foo = foo;
}
public String toString() {
return foo;
}
}
public class sample {
public static void main(String[] args) {
A a = new A("Hello world!");
System.out.println(a);
}
}
String is a class whose purpose is to hold a string value and will return that value if referenced. When you use other classes, you will usually want to add other behavior. If you want to use the class to hold different values that you can set (on object creation or later in processing) you may want to use "setter" and "getter" methods for such values.
Here is an example:
public class Snippet {
private static final String C_DEFAULT_VALUE = "<default value>";
private String name;
private static Snippet mySnippet;
public Snippet() {
}
public Snippet(String value) {
setName(value);
}
/**
* #param args
*/
public static void main(String[] args) {
if (args != null && args.length > 0) {
mySnippet = new Snippet(args[0]);
} else {
mySnippet = new Snippet(C_DEFAULT_VALUE);
}
System.out.println(mySnippet.getName());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

A parameters' variable as parameter

I have an Object Human:
public class Human {
String name;
public Human(String name){
this.name = name;
}
}
In my main Class I have an instance of this human "John".
With a function called getVarOfObject() I want to get John's name:
public class Example {
public static Object getVarOfObject(Object obj, Object var){
return obj.var;
}
public static void main(String[] args) {
Human john = new Human("John");
String johnsName = getVarOfObject(john, name);
}
}
I know you could just type john.name but in my case I need to have a function which can do this.
You can use this code
Field field = <Your object>.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return (String) field.get(object);
You can't do this except reflectively.
Please note that this wizardry can lead to errors, subtle issues, exceptions, performance losses, asphyxiation, drowning, death, paralysis, or fire.
Object obj is the object, and String field is the name of the field.
Class clazz=Human.getClass(); //or for class-independence use `obj.getClass()`.
Field fd=clazz.getField(name);
fd.get(obj);
Why don't you use accessor methods (getters and setters)?
In Human:
public String getName() {
return name;
}
and in your main method:
Human john = new Human("John");
String johnsName = john.getName();

Java - Using Accessor and Mutator methods

I am working on a homework assignment. I am confused on how it should be done.
The question is:
Create a class called IDCard that contains a person's name, ID number,
and the name of a file containing the person's photogrpah. Write
accessor and mutator methods for each of these fields. Add the
following two overloaded constructors to the class:
public IDCard() public IDCard(String n, int ID, String filename)
Test your program by creating different ojbects using these two
constructors and printing out their values on the console using the
accessor and mutator methods.
I have re-written this so far:
public class IDCard {
String Name, FileName;
int ID;
public static void main(String[] args) {
}
public IDCard()
{
this.Name = getName();
this.FileName = getFileName();
this.ID = getID();
}
public IDCard(String n, int ID, String filename)
{
}
public String getName()
{
return "Jack Smith";
}
public String getFileName()
{
return "Jack.jpg";
}
public int getID()
{
return 555;
}
}
Let's go over the basics:
"Accessor" and "Mutator" are just fancy names fot a getter and a setter.
A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.
So first you need to set up a class with some variables to get/set:
public class IDCard
{
private String mName;
private String mFileName;
private int mID;
}
But oh no! If you instantiate this class the default values for these variables will be meaningless.
B.T.W. "instantiate" is a fancy word for doing:
IDCard test = new IDCard();
So - let's set up a default constructor, this is the method being called when you "instantiate" a class.
public IDCard()
{
mName = "";
mFileName = "";
mID = -1;
}
But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:
public IDCard(String name, int ID, String filename)
{
mName = name;
mID = ID;
mFileName = filename;
}
Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
Nice. Now we can access mName. Add the rest of the accessors and mutators and you're now a certified Java newbie.
Good luck.
You need to remove the static from your accessor methods - these methods need to be instance methods and access the instance variables
public class IDCard {
public String name, fileName;
public int id;
public IDCard(final String name, final String fileName, final int id) {
this.name = name;
this.fileName = fileName
this.id = id;
}
public String getName() {
return name;
}
}
You can the create an IDCard and use the accessor like this:
final IDCard card = new IDCard();
card.getName();
Each time you call new a new instance of the IDCard will be created and it will have it's own copies of the 3 variables.
If you use the static keyword then those variables are common across every instance of IDCard.
A couple of things to bear in mind:
don't add useless comments - they add code clutter and nothing else.
conform to naming conventions, use lower case of variable names - name not Name.

Return a string and int

How do i return a string and an integer? say i wanted to return
students name which is an string and their mark which is an integer.
I cant do mark=mark+element+(element2+name); that creates an incompatible type.
My suggestion in this type of situation is to create a new class that holds this information. Name it for example StudentMark.
class StudentMark {
private final String name;
private final int mark;
public StudentMark(String name, int mark) {
this.name = name;
this.mark = mark;
}
public String getName() { return name; }
public int getMark() { return mark; }
}
Then in your method that has both the name and mark where you want to return, just do like so.
return new StudentMark("Samuel", 3.2);
Here you can also add any other interesting methods that you might need.
Create a class Student and return a student
class Student{
private String name;
private int mark;
//assessor+ contructors
}
you'll need to define a class for it. the class should have two attributes: a string and an int
Define a class that contains both values and return an object of that class.
create A class with priavte variables for name and marks. and override toString() method.
public class Student{
private int marks;
private String name;
//provde setters and getters for marks and name
public String toString(){
return getName()+getMarks();
}
}
In your Student class, you can have a method:
public String printNameAndGrade() {
return "Name: " + this.getName() + "\n " + "Grade: " + this.getGrade();
}
and then call it with a Student object reference:
Student st1 = new Student("Gabe Logan", 97);
System.out.println(st1.printNameAndGrade()); //use `println` method to display it.
You can use a two element Array or List and put the values in there. Unfortunately this looses all type Information.
You can use a Map which keeps the type information, but might be confusing because you would expect an arbitrary number of entries.
The cleanest option is to create a simple class with the two elements.

How to use the toString method in Java?

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?
From the Object.toString docs:
Returns a string representation of the
object. In general, the toString
method returns a string that
"textually represents" this object.
The result should be a concise but
informative representation that is
easy for a person to read. It is
recommended that all subclasses
override this method.
The toString method for class Object
returns a string consisting of the
name of the class of which the object
is an instance, the at-sign character
`#', and the unsigned hexadecimal
representation of the hash code of the
object. In other words, this method
returns a string equal to the value
of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
Example:
String[] mystr ={"a","b","c"};
System.out.println("mystr.toString: " + mystr.toString());
output:- mystr.toString: [Ljava.lang.String;#13aaa14a
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<Bank> l = new LinkedList<Bank>();
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<Bank> 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...
The toString() method returns a textual representation of an object. A basic implementation is already included in java.lang.Object and so because all objects inherit from java.lang.Object it is guaranteed that every object in Java has this method.
Overriding the method is always a good idea, especially when it comes to debugging, because debuggers often show objects by the result of the toString() method. So use a meaningful implementation but use it for technical purposes. The application logic should use getters:
public class Contact {
private String firstName;
private String lastName;
public Contact (String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {return firstName;}
public String getLastName() {return lastName;}
public String getContact() {
return firstName + " " + lastName;
}
#Override
public String toString() {
return "["+getContact()+"]";
}
}
It may optionally have uses within the context of an application but far more often it is used for debugging purposes. For example, when you hit a breakpoint in an IDE, it's far easier to read a meaningful toString() of objects than it is to inspect their members.
There is no set requirement for what a toString() method should do. By convention, most often it will tell you the name of the class and the value of pertinent data members. More often than not, toString() methods are auto-generated in IDEs.
Relying on particular output from a toString() method or parsing it within a program is a bad idea. Whatever you do, don't go down that route.
toString() returns a string/textual representation of the object.
Commonly used for diagnostic purposes like debugging, logging etc., the toString() method is used to read meaningful details about the object.
It is automatically invoked when the object is passed to println, print, printf, String.format(), assert or the string concatenation operator.
The default implementation of toString() in class Object returns a string consisting of the class name of this object followed by # sign and the unsigned hexadecimal representation of the hash code of this object using the following logic,
getClass().getName() + "#" + Integer.toHexString(hashCode())
For example, the following
public final class Coordinates {
private final double x;
private final double y;
public Coordinates(double x, double y) {
this.x = x;
this.y = y;
}
public static void main(String[] args) {
Coordinates coordinates = new Coordinates(1, 2);
System.out.println("Bourne's current location - " + coordinates);
}
}
prints
Bourne's current location - Coordinates#addbf1 //concise, but not really useful to the reader
Now, overriding toString() in the Coordinates class as below,
#Override
public String toString() {
return "(" + x + ", " + y + ")";
}
results in
Bourne's current location - (1.0, 2.0) //concise and informative
The usefulness of overriding toString() becomes even more when the method is invoked on collections containing references to these objects. For example, the following
public static void main(String[] args) {
Coordinates bourneLocation = new Coordinates(90, 0);
Coordinates bondLocation = new Coordinates(45, 90);
Map<String, Coordinates> locations = new HashMap<String, Coordinates>();
locations.put("Jason Bourne", bourneLocation);
locations.put("James Bond", bondLocation);
System.out.println(locations);
}
prints
{James Bond=(45.0, 90.0), Jason Bourne=(90.0, 0.0)}
instead of this,
{James Bond=Coordinates#addbf1, Jason Bourne=Coordinates#42e816}
Few implementation pointers,
You should almost always override the toString() method. One of the cases where the override wouldn't be required is utility classes that group static utility methods, in the manner of java.util.Math. The case of override being not required is pretty intuitive; almost always you would know.
The string returned should be concise and informative, ideally self-explanatory.
At least, the fields used to establish equivalence between two different objects i.e. the fields used in the equals() method implementation should be spit out by the toString() method.
Provide accessors/getters for all of the instance fields that are contained in the string returned. For example, in the Coordinates class,
public double getX() {
return x;
}
public double getY() {
return y;
}
A comprehensive coverage of the toString() method is in Item 10 of the book, Effective Java™, Second Edition, By Josh Bloch.
Whenever you access an Object (not being a String) in a String context then the toString() is called under the covers by the compiler.
This is why
Map map = new HashMap();
System.out.println("map=" + map);
works, and by overriding the standard toString() from Object in your own classes, you can make your objects useful in String contexts too.
(and consider it a black box! Never, ever use the contents for anything else than presenting to a human)
Correctly overridden toString method can help in logging and debugging of Java.
Coding:
public class Test {
public static void main(String args[]) {
ArrayList<Student> a = new ArrayList<Student>();
a.add(new Student("Steve", 12, "Daniel"));
a.add(new Student("Sachin", 10, "Tendulkar"));
System.out.println(a);
display(a);
}
static void display(ArrayList<Student> stu) {
stu.add(new Student("Yuvi", 12, "Bhajji"));
System.out.println(stu);
}
}
Student.java:
public class Student {
public String name;
public int id;
public String email;
Student() {
}
Student(String name, int id, String email) {
this.name = name;
this.id = id;
this.email = email;
}
public String toString(){ //using these toString to avoid the output like this [com.steve.test.Student#6e1408, com.steve.test.Student#e53108]
return name+" "+id+" "+email;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email=email;
}
}
Output:
[Steve 12 Daniel, Sachin 10 Tendulkar]
[Steve 12 Daniel, Sachin 10 Tendulkar, Yuvi 12 Bhajji]
If you are not used toString() in Pojo(Student.java) class,you will get an output like [com.steve.test.Student#6e1408, com.steve.test.Student#e53108].To avoid these kind of issue we are using toString() method.
Apart from what cletus answered with regards to debugging, it is used whenever you output an object, like when you use
System.out.println(myObject);
or
System.out.println("text " + myObject);
The main purpose of toString is to generate a String representation of an object, means the return value is always a String. In most cases this simply is the object's class and package name, but on some cases like StringBuilder you will got actually a String-text.
/**
* This toString-Method works for every Class, where you want to display all the fields and its values
*/
public String toString() {
StringBuffer sb = new StringBuffer();
Field[] fields = getClass().getDeclaredFields(); //Get all fields incl. private ones
for (Field field : fields){
try {
field.setAccessible(true);
String key=field.getName();
String value;
try{
value = (String) field.get(this);
} catch (ClassCastException e){
value="";
}
sb.append(key).append(": ").append(value).append("\n");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return sb.toString();
}
If you learn Python first and then Java. I think it plays the same role as __str__() method in Python, it is a magic method like __dict__() and __init__() but to refer to a string representing the the object.
the toString() converts the specified object to a string value.

Categories

Resources