# Java practise exam question

Doing practise questions for a Java exam which have no answers (useful) I have been asked to do the following:

Write a class called Person with the following features:

• a private int called age;
• a private String called name;
• a constructor with a String argument, which initialises name to the received value and age to 0;
• a public method toString(boolean full). If full is true, then the method returns a string consisting of the person’s name followed by their age in brackets; if full is false, the method returns a string consisting of just the name. For example, a returned string could be Sue (21) or Sue;
• a public method incrementAge(), which increments age and returns the new age;
• a public method canVote() which returns true if age is 18 or more and false otherwise.

My code is as follows can someone point out any errors?

public class Person
{
private int age;
private String name;

public Person(String st)
{
name = st;
age = 0;
}

public String toString(boolean full)
{
if(full == true)
{
return name + "(" + age + ")";
}
else
{
return name;
}
}

public int incrementAge()
{
age++;
return age;
}

public boolean canVote()
{
if(age >= 18)
{
return true;
}
else
{
return false;
}
}
}

• I don't see any errors :)
– Cata
May 30 '11 at 14:27

if(full == true)


use

if (full)


if(age >= 18)
{
return true;
}
else
{
return false;
}


use:

return age >= 18

• Thank you both for your answers, just wee small minor things i need to keep an eye on then.
– user445714
May 30 '11 at 14:31
 return name + "(" + age + ")";


to

return name + " (" + age + ")";


That's fine, but I would have written the last method as return (age >= 18);

I don't think it's a good idea to write toString method with arguments - doing so you will not override the default Object.toString and will have no benefits from using it outside your code. For example, when outputting elements of a collection which contain Person won't display neither age nor name, but something like Person@a3f33f (default implementation). At least provide toString with no arguments as well

• Denisk that actually moves onto my next question, Does the Person class overload or override any methods? Briefly explain your answer.
– user445714
May 30 '11 at 14:34
• I was going with override until i seen your comment and would go with overload the Object.toString?
– user445714
May 30 '11 at 14:35
• Currently you have toString method overloaded - thus, you actually have 2 toString methods - one inherited from Object (default no-arg method), and one with boolean argument. If you declared your toString with no arguments it would override Object.toString, and you would end up with 1 toString method (which, as I have mentioned, can be widely used by many things outside your own code)
– denisk
May 30 '11 at 14:38
• I agree with denisk, and want to point out that flags like full in method arguments are a code smell: A method should do one and only one thing (Single Responsibility Principle), and a method with a flag does at least two things. Uncle Bob agrees as well (Clean Code: amazon.de/Clean-Code-Handbook-Software-Craftsmanship/dp/… ) Mar 3 '12 at 13:44
• The toString(boolean) method is part of the assignment requirements. But normally, this is good advice.
– Eva
Jan 16 '13 at 12:04

In addition to the other comments, on your constructor, having an argument called "st" isn't particularly useful to the reader as it doesn't tell them what it's for. From a code style perspective might be better to have an argument called name, and explicitly set this.name = name in the body.

• To add on, at this moment of learning it may seem not to matter, but when you're developing, these little things that make the usage more intuitive (especially when you're using auto-completion) will reduce your (and others') pain.
– blizpasta
May 30 '11 at 14:44

Your code is almost fine. I would change two things:

The following is a little shorter :)

public boolean canVote()
{
return age >= 18;
}


Your toString(true) would return "Sue(21)" rather than the "Sue (21)" (with space) which is asked for. My toString would look like this:

public String toString(boolean full)
{
String str = name;
if(full) {
str += " (" + age + ")";
}

return str;
}


If the age is implemented as a primitive integer there is no need to initialize it to 0 because all primitive number instance variables are initialized to 0 by default. Anyway if you had used a wrapper instead (Integer) the initialization to 0 is required.

Take a look at the "Default Values" section:

And:

return name + (full ? " (" + age + ")" : "");


• +1 for only the constant. (I agree, the ternary operator is not too readable and harder to maintain.) Jul 7 '12 at 15:56

Looks fine, only canVote is maybe a bit clumsy:

   public boolean canVote()
{
return age >= 18;
}


I would see if you can make the code less verbose.

public boolean canVote() {
return age >= 18;
}


This is also less verbose

public int incrementAge() {
return ++age;
}

• I worry that a student might be docked points for readability if they put that answer. Otherwise, I would write it like that too.
– Eva
Jan 16 '13 at 12:07

Use String.format instead of string concatenation:
return name + "(" + age + ")"; becomes

return String.format("%s (%s)", name, age);

• It's a Java question ;) Jul 7 '12 at 22:09
1. The name field could be final. Making a variable final relieves the programmer of excess mental juggling - he/she doesn't have to scan through the code to see if the variable has changed. (From @nerdytenor's answers.)

2. You should check the argument in the constructor. Does it make sense to create a Person object with a name which is null or an empty String? If not, check it and throw a NullPointerException or an IllegalArgumentException. (Effective Java, Second Edition, Item 38: Check parameters for validity)

3. A note about the specification:

Flag arguments are ugly. Passing a boolean into a function is a truly terrible practice. It immediately complicates the signature of the method, loudly proclaiming that this function does more than one thing. It does one thing if the flag is true and another if the flag is false!

Source: Clean Code by Robert C. Martin, Chapter 3: Functions.

This should be two methods: toString() and toFullString(), for example, without any parameter.

public Person(String st)
{
name = st;
age = 0;
}


st is not a good name for a variable or parameter, because it does not tell you what it contains. It implies that it means "string", but even that is not clear. Call it name instead. Use this.name = name to distinguish member and parameter names.

Put the opening brackets on the first line of the block, not at the beginning of the next line, since it is common practise in Java (even though I find it prettier if it is on the next line, since I code C# more than Java). Other Java developers reading your code will be used to it.

Others have already pointed it out: Write if (full) instead of if (full == true). That is clearer and easier to read. You can use the ternary operator for a one liner:

return full ? name + "(" + age + ")" : name;.

Your incrementAge() looks fine.

   public boolean canVote()
{
if(age >= 18)
{
return true;
}
else
{
return false;
}
}


Your indentation is weird. Use 4 spaces (less common tabs with width of 4 spaces) for indentation. You have sometimes 3 spaces, sometimes 2.

Since age >= 18 is a boolean expression, you can return the result just like this:

return age >= 18;

Use spaces after if and for (also while and similar) keywords. That makes the code clearer and more readable:

if (someCondition) {
doThis();
}


My version of Person class would be,

public class Person
{
private int age;
private String name;

public Person(String st)
{
this.name = st;
this.age = 0;
}
public String toString(boolean full)
{
return full?name + "(" + this.age + ")":name;
}

public int incrementAge()
{
return ++this.age;
}

public boolean canVote()
{
return (this.age >= 18);
}
}

• No StringBuilder in the toString method? Jul 6 '12 at 16:21
• This is not a valid answer, as it is just a new version without any explaination or recommendations. Furthermore it contains many of the same mistakes as the original code. Jan 19 '18 at 9:37