Creating our own String class?

Can we create our own string class? If so, can someone tell me how to do it? This is an Interview question. Does it mean can we create a class that is immutable like string or something else?

Thanks.

Be Humble... Be Nice.

Prasanna Venkatesh

Greenhorn

Posts: 11

posted 9 years ago

Hi Arjun , Ya , It should be possbile to create user defined Immutable classes as String . Please let me know what makes you to think , that it is not possible to create ?? ..We will analyze your thought process

Prasanna

Jigar Gandhi

Greenhorn

Posts: 20

posted 9 years ago

It might be possible to create a class with immutable objects but in java strings are stored in String constant pool if you may have heard of it how are you going to create such a thing

Joanne Neal

Rancher

Posts: 3742

16

posted 9 years ago

Originally posted by Arjun Reddy: Does it mean can we create a class that is immutable like string or something else?

You'd have to ask the interviewer what they meant. If I was asked a ambiguous question like that, then I'd ask for clarification before answering.

Joanne

Bill Cruise

Ranch Hand

Posts: 148

posted 9 years ago

It might be possible to create a class with immutable objects but in java strings are stored in String constant pool if you may have heard of it how are you going to create such a thing

A static map.

The only thing you wouldn't be able to implement by creating a new class is the standard syntax for the assignment of a constant.

MyString s = "some value";

Assuming you're not allowed to use regular Java Strings, you wouldn't even be able to do this:

MyString s = new MyString("some value");

You'd have to pass an array (or a collection) of characters to the constructor.

Guess the guy who was interviewing meant to write an Immutable class similar to String class. My Friend actually took the interview. He did not understand the question and neither did I so I was asking here. Balasubramaniyan, I was looking at the link ya gave .. and I was wondering how point 1 works in making a class immutable and what is point 3 from the sample below taken from that page,

Guidelines for writing immutable classes

Writing immutable classes is easy. A class will be immutable if all of the following are true:

1). All of its fields are final 2). The class is declared final 3). The this reference is not allowed to escape during construction 4). Any fields that contain references to mutable objects, such as arrays, collections, or mutable classes like Date: o Are private o Are never returned or otherwise exposed to callers o Are the only reference to the objects that they reference o Do not change the state of the referenced objects after construction

So what do you think java.lang.String should contain. If you are asked to develop similar code in C you would take a char[] and store each character.

Same can be done in Java also. you need to leverage the existing char data type.

and immutability is something implemented by Sun as a mistake so why do you want to do it again. Have a better version

And still if you want immutability, follow the instruction above.

May be a good idea is to download the Java Source code and have a look at the String.java and StringBuffer.java. You will get a better understanding of both kind of implementation. Thats the beauty of open source.

Originally posted by SachinJoshi Joshi: and immutability is something implemented by Sun as a mistake

What do you base that statement on ? Immutability can be a very useful feature. HashMap keys is one instance where using an immutable object can reduce the chance of having some hard to find bugs in your program.

Joanne

Ulf Dittmer

Rancher

Posts: 42972

73

posted 9 years ago

In addition to what Joanne said, immutability also has advantages in the presence of concurrency - an area that is rapidly becoming more important with the advent of multithreaded and multicore processors.

Charles McGuire

Ranch Hand

Posts: 99

posted 9 years ago

Is it possible to model/use database as immutable objects instead of JavaBeans? In a Javaworld article on idioms, the author says the following in promotion of immutable objects:

From a practical perspective, many widely-used frameworks require application programmers to use JavaBeans (or something similar) to model database records. This is deeply unfortunate, because it doesn't allow programmers to take advantage of the many positive qualities of immutable objects.John O'Hanley, Javaworld.com, 29 July 2008

So I've been searching (which led me to this thread) on how that could be done. I must be a victim of JavaBean thinking, because I don't know how you can change an object without using setters.

I understand the importance of immutability, and certainly is very important feature....

So are you trying to say that immutability of String class is by design? Why would that be so? How does it benefit? And why do we have StringBuffer class then? (One obvious reason I can think of is performance....what else?)

Originally posted by Sachin Joshi: So are you trying to say that immutability of String class is by design?

Yes. If you look inside the String class, you will see the char[] that stores the String's value is marked as final so its value cannot be changed. In fact, in many modern programming languages -- including Python, the .NET Framework, and Java -- Strings are immutable. So it is very much by design and not a mistake by Sun.

Originally posted by Sachin Joshi: Why would that be so? How does it benefit?

Immutable objects are often useful because some costly operations for copying and comparing can be omitted, simplifying the program code and speeding execution. .... Strings and other concrete objects are typically expressed as immutable objects to improve readability and runtime efficiency in object-oriented programming.

Given that it is very typical for Strings to be copied and compared a lot, making them immutable provides better performance.

And as it goes on to say, and as Ulf pointed out:

Immutable objects can be useful in multi-threaded applications. Multiple threads can act on data represented by immutable objects without concern of the data being changed by other threads. Immutable objects are therefore considered to be more thread-safe than mutable objects.

Imagine the hassles if you had to worry about thread safety with Strings.

Originally posted by Sachin Joshi: And why do we have StringBuffer class then? (One obvious reason I can think of is performance....what else?)

So that when you need a mutable String -- for performance or design reasons -- you can have access to one. While most of the time an immutable String offers performance advantages, there are time when a mutable String offers better performance (or better design). For example, when doing heavy concatenation. In such a case a StringBuilder or StringBuffer offers performance advantages.

Again, per the Wikipedia article:

Both Java and the .NET Framework have mutable versions of string. In Java these are StringBuffer and StringBuilder (mutable versions of Java String) and in .NET this is StringBuilder (mutable version of .Net String). Python 3 will have a mutable string (bytes) variant, named buffer.

Keep in mind, the StringBuffer class has been around since Java 1.0 just like the String class. It wasn't added later because Sun thought they made a mistake making String immutable. StringBuilder was added in Java 5.0 to improve performance when you don't need the Thread Safety (e.g. when being used in a Single Thread) that a StringBuffer provides. [ August 11, 2008: Message edited by: Mark Vedder ]

Originally posted by Charles McGuire: Is it possible to model/use database as immutable objects instead of JavaBeans? In a Javaworld article on idioms, the author says the following in promotion of immutable objects:

So I've been searching (which led me to this thread) on how that could be done. I must be a victim of JavaBean thinking, because I don't know how you can change an object without using setters.

First, to address: "I don't know how you can change an object without using setters."

The point of immutable objects is they can't be changed. So if you want an object that can be changes, JavaBeans are just fine.

But for this: "Is it possible to model/use database as immutable objects instead of JavaBeans?"

You would have to pass all the information into the Object using the Constructor, and it would be this parametrized constructor that would break the JavaBeans conventions (which requires a no-args constructor).

Or you could pass some portion of the information (like an ID) into the constructor and let the Object access the data back end to fill the rest of its properties.

In either case you don't need setters, just a parametrized Constructor which knows how to build itself based on the data you give it.

Originally posted by Gamini Sirisena: Is someone able to explain this a bit more?

"some costly operations for copying and comparing can be omitted"

If an object's contents can change, then the only way to make sure the object is consistent in a particular thread would be to make a copy of the object and work with that copy.

Let's say you had an address book, and one thread is adding values to the book, and another thread is displaying values from the book.

The display thread gets to the part where it wants to display John Smith's address, and displays some part of the address.

At the same time the other thread decides to change John Smith's address.

If the address for John Smith is mutable, then the display thread will display some mismatch of the old and new address and provide inconsistent data for display.

If The address for John Smith is immutable, then the thread changing it would remove the old address and add a new one. The displaying thread wouldn't care because it either received the old address before it was changed and displays it completely, or received the new address after it was changed and displays it completely, but can't get an inconsistent object.

To mimic this preferred behavior in the case you don't have immutable data, you would have to make a copy of the address book and give the copy to the display thread to display. This can take a lot of time and memory, depending on the size of the book.

For the comparison, this is situational. If your objects are immutable you can generate them in a Factory and use a Cache to return the Object reference you want. This will help save time and memory if the same object is required often. Think Integer.valuOf(int) which will Cache values from -128 to 127. Technically this allows you to use == to compare objects instead of .equals(). I wouldn't rely on the == operator outright, but you could use it as the first line in the .equals() method to prevent a field by field comparison. I do this for all my objects, but for Cached immutable objects the effectiveness is greater because you are more likely to reference the same object if you have the same values.

Steve

mahudees waran

Greenhorn

Posts: 28

posted 9 years ago

I do have a doubt about the question...

If there is no String class in java and we are supposed to create the same by our own then how the declaration like this are to be handled

MyString string = "Example String";

or

MyString stringexample = new MyString("Example String");

Assume the class

MyString

is the one which we create instead of the

String

class

Then what does the things inside the "" mean to the compiler if we don't explicitly say what it is?

Also in String class how that is implemented?

Campbell Ritchie

Marshal

Posts: 56546

172

posted 9 years ago

Read the thread again, particularly Bill Cruise's post.

Ilja Preuss

author
Sheriff

Posts: 14112

posted 9 years ago

Originally posted by mahudees waran:

Then what does the things inside the "" mean to the compiler if we don't explicitly say what it is?

Also in String class how that is implemented?

It isn't - it's hardcoded into the compiler.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus

Ilja Preuss

author
Sheriff

Posts: 14112

posted 9 years ago

Another reason might be security.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus