0

I am working on an exercise that consists of creating my own implementation of the String class, with some of the methods that exist in this class. I am having some trouble with creating a working method for returning a substring. So far my class implementation looks like this:

public class MyString2 {

    private String s;

    public MyString2(String s) {
        this.s = s;
    }

    public MyString2 substring(int begin) {

        String substring = "";

        for (int i = begin; i < s.length(); i++) {
            substring += s.charAt(i);
        }
        return new MyString2(substring);
    }

}

The idea behind the method is pretty simple;

Create a blank substring, and then concat each character from the input string beginning from a chosen index. Below is the main method for testing the class:

public static void main(String[] args) {

        MyString2 s1 = new MyString2("string");     
        MyString2 substring = s1.substring(3);

        System.out.println(substring);

    }

The program returns ch10.MyString2@2a139a55, can anyone please tell me what is wrong with my procedure?

Esben86
  • 483
  • 8
  • 21

1 Answers1

8

Currently, you are printing the object rather than it's contents. You can override toString() in your MyString2 class to change this behaviour:

@Override
public String toString() {
    return s;
}
nbokmans
  • 5,492
  • 4
  • 35
  • 59
  • Thanks alot, this worked like a charm! I should probably have thought of this by myself, but in the exercise description, a toString() method was not in the list of methods that the class should contain. – Esben86 Apr 21 '16 at 11:29
  • That is probably because it's not a method that you implement yourself, rather, every object in Java is a subclass of https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html which contains methods such as `toString()`, `hashCode()` and `equals()`, all of which you can override with your own implementation. – nbokmans Apr 21 '16 at 11:32