1

I'm into Java since a short time, and I was wondering: Strings are in fact objects, but I heard that in assigning them a value and retrieving it they act quite differently, almost as if they were primitive types... could someone make it more clear? What do I exactly have to care about when I declare/edit/access a string compared to other objects?

  • You cannot edit a string. They are _immutable_. Check [String is immutable. What exactly is the meaning?](http://stackoverflow.com/questions/8798403/string-is-immutable-what-exactly-is-the-meaning) – sam Nov 02 '15 at 23:50
  • That's the only thing I know for sure... but, for example, why can you directly assign a String its value by making something like: String s = "hello"; instead of something like String.content = "hello" –  Nov 02 '15 at 23:59
  • @JohnStrife based on what you just commented, I'm going to guess that you probably have a decent amount of experience in Python. A string in java isn't the sort of object I think you're imaging. or at least you don't interact with it in that way – Alex K Nov 03 '15 at 00:02
  • Yeah, I've used Python and I just don't exactly get how Java strings seem to be something in between objects and primitive types. –  Nov 03 '15 at 00:04

1 Answers1

1

First of all Java has string literals. That means you may write String foo = "bar";. String are immutible (once you create one, you can't change it) and it helps JVM to do one trick called "string pool". String literals are stored in pools, and in the following example both foo and bar may point to one instance of string. String foo = "baz"; String bar = "baz". You may even compare them with ==, but you should never do that. How ever, equals() method (which you use to compare strings in Java) may benefit from it since it does not need to compare strings if both vars point to the same string.

Please check this topic for more info What is the Java string pool and how is "s" different from new String("s")?

Community
  • 1
  • 1
user996142
  • 2,753
  • 3
  • 29
  • 48
  • I'll read that topic for sure, thank you. But what does exactly "string literals" mean? –  Nov 03 '15 at 00:06
  • @JohnStrife anything you write in double-quotes in your code, e.g. `"string literals"`. – Andy Turner Nov 03 '15 at 00:13
  • Ok, that's clear, and one thing that wasn't clarified on the post that @user996142 linked: is there any difference between saying String x = "bird"; and String x = new String("bird"); ? –  Nov 03 '15 at 00:16
  • I understood it: with String x = "bird"; if there's already a string which contains "bird", the pool system will link x to that. With: String x = new String("bird"); It creates a new one no matter if a string containing "bird" already exists. I hope this will help who has my same question. –  Nov 08 '15 at 17:54