• Post Reply Bookmark Topic Watch Topic
  • New Topic

Concatenation in println()?  RSS feed

 
Nicole Strawn
Greenhorn
Posts: 8
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know this is probably way to simple a question, but I'm genuinely confused about it and google isn't helping.

If I have a line


I know how it will work, where the whole thing gives a sentence and I get the actual value of var1 instead of the word var1... but what do I call that? It's not concatenation, right? because in this case, var1 was an integer and concatenation is supposed to be between 2 strings.

But also, Java doesn't have string as a data type? But then, at the same time println() is a method that "accepts a string parameter." And the plus sign doesn't mean actual addition.

The textbook I'm reading doesn't go into it, and I think I'm getting more confused as I try to google it. The way I understand it is:
the string data type really does exist, but in a special complicated way when it comes to Java which makes it different from other data types like int. In this case, everything inside a pair of quotation marks is a string. var1 gets replaced by the value assigned to it, and then, because the value or var1 is inside the parameter of print()/println() which only takes strings as a rule, it gets treated like a string and is concatenated with the actual string that was inside the quotation mark.


Is that correct? Is it really obvious and I'm not getting something simple, or am I over-complicating it? I don't mean to be pedantic if that's what this is, but I'm really pure noob when it comes to programming and I really want to not get it wrong in Chapter 1. (I'm using Java - A Beginner's Guide )
 
Knute Snortum
Sheriff
Posts: 4276
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You haven't said what type var1 is.

The plus sign (+) is overloaded in Java so that it is a concatenation operator.  In the case that var1 is a String, everything is clear cut (I think).  When var1 is another type of object, its toString() method is called to get the String to concatenate.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Don't be scared of being pedantic; the computer will assume you are pedantic, so you have to counter that with pedantry.
Yes, it is called String concatenation. You can read the gory details in the Java® Language Specification (=JLS). Briefly, what happens is that whenever the + operator is applied to two operands one of which has the type of a String and the other is something different, the other operand is converted to a String. In the example you showed, one operatnd is the String literal "Var1 is a variable that has been assigned a value of " and the other operand is var1; I don't know what its type is, but that doesn't matter. The conversion to a String is via one of the methods of String, valueOf(...). If you go through that link and scroll down to V, you will see that valueOf is heavily overloaded and it can accept anything you can throw at it as an argument, even nulls, and produce some sort of String as its output. Then the + operator joins the two Strings together to form one String.

I am going to challenge you with the opposite problem. Look at this String concatenation:-Work out what it will display, then run that code, then see whether you were right. If you weren't right,
  • 1: Work out why.
  • 2: Find out why I used lineSeparator() and not \n.
  • 3: Don't look for the original of that song.
  •  
    Campbell Ritchie
    Marshal
    Posts: 56536
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    A few minutes ago, I wrote:. . . I am going to challenge you with the opposite problem. . . .
    I put the quotes in the wrong place: sorry. This is the corrected version:-
     
    Knute Snortum
    Sheriff
    Posts: 4276
    127
    Chrome Eclipse IDE Java Postgres Database VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    the string data type really does exist...

    This is a confusing quote for me.  Why would anyone think the String (not string) type doesn't exist?  Is it trying to say that a String is not a primitive type?  That's true, but...
    and are doing the same thing, that is, printing a String object.  Yes, "this text" is a String object and you can prove it to yourself by typing
     
    Nicole Strawn
    Greenhorn
    Posts: 8
    Eclipse IDE Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Knute Snortum wrote:
    the string data type really does exist...

    This is a confusing quote for me.  Why would anyone think the String (not string) type doesn't exist?  Is it trying to say that a String is not a primitive type?  That's true, but...
    and are doing the same thing, that is, printing a String object.  Yes, "this text" is a String object and you can prove it to yourself by typing


    String values as a reference class is not the easiest thing to get right out the gate. But taking string existence as granted despite my general confusion as to how reference classes work, (I'm just assuming I'll get to this as I progress), my real issue was with how the concatenation would work since it is said that concatenation was a string data only operation and var1 wasn't a string.

    Briefly, what happens is that whenever the + operator is applied to two operands one of which has the type of a String and the other is something different, the other operand is converted to a String. In the example you showed, one operatnd is the String literal "Var1 is a variable that has been assigned a value of " and the other operand is var1; I don't know what its type is, but that doesn't matter. The conversion to a String is via one of the methods of String, valueOf(...). If you go through that link and scroll down to V, you will see that valueOf is heavily overloaded and it can accept anything you can throw at it as an argument, even nulls, and produce some sort of String as its output. Then the + operator joins the two Strings together to form one String. 


    This was the part I couldn't figure out, and

    The plus sign (+) is overloaded in Java so that it is a concatenation operator.
      It was one of those "I vaguely know that I don't know something vital" moments. I didn't know that I didn't know overloading.

    Pure week 1 noob here  but if I try to "just accept that it is so" it bothers me to the point where I struggle to move forward so I try to understand as much of what I'm doing up front going in. So now, I still don't know overloading, or the "methods of String", but I have enough information now to put a sticky on it - "check this out in the future" and move one without feeling overwhelmed by the unknown. I'm 30, the opposite of a young at heart, open minded student, and not in anyway tech resourceful. I just figured out how to do github with eclipse last night.   

    Much thanks to everyone
     
    Nicole Strawn
    Greenhorn
    Posts: 8
    Eclipse IDE Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:


    76 trombones led the parade
    110 comets were close at hand
    ...

    Assuming that the + operator will function as an addition operating on all available data types that can be added regularly (as if there are brackets around the integer values) before overloading activates and it goes to a concatenation operator?
  • methods first, so it divides everything into three lines (assuming that either methods are most important or cannot be converting into string))
  • Then assuming "leave data as is and do your normal stuff" happens, so that the numbers get added in the lines above the line separation so that there's "76 trombones ..." on the first line, "110 comets..." on the second line and "..." on the last line


  • But I sense wrongness and since you said the opposite problem, it's that it doesn't concatenate?  I'll try again with further research into something along the lines of "bodmas for computer programming." It's an "order of operations" problem? I'll try it when I get home to my computer. (I spent my day at work investigating this problem.  )


     
    Junilu Lacar
    Sheriff
    Posts: 11485
    180
    Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Strings have a bit of a special status in Java. They are part of the standard Java library and reside in the implicitly imported java.lang package, along with the primitive wrapper classes like  Integer, Float, Double, Character, Boolean, etc.

    You quoted this:
    ...the parameter of print()/println() which only takes strings as a rule

    This isn't true. If you look at the API JavaDocs for java.io.PrintStream, which is what System.out is, you'll see that the print() and println() methods are overloaded for all the primitive types and for Object in general and String specifically.

    Under the covers, print() and println() will end up calling String.valueOf() on anything that isn't a String. String.valueOf() in turn calls the argument's toString() method.  This is why you should take extra care about calling valueOf() from inside a toString() that you are overriding or you could create an infinitely recursive loop.

    Campbell has already provided a link and explanation of what happens when an expression uses the "+" operator on operands that have mixed types. I'll reiterate: The "+" operator can be seen as an arithmetic addition operation or a String concatenation operation. Evaluation goes from left to right. If both of the operands involved are numeric, the + operator functions as arithmetic addition. When one of the operands is a String and the other isn't, + becomes concatenation and the non-String operand is implicitly converted to a String via string conversion (that's a link to the JLS so buckle up when you follow it).

    In case you're wondering, the + operator can only be used when the operands are all numeric or at least one of them is a String. When neither of these are true, the + operator will cause a compile-time error, "bad operand types for binary operator '+'"

    An important point to note is that evaluation goes from left to right. So, 7 + 5 + " blah " is going to be very different from " blah " + 7 + 5.  I'll leave that to you to experiment with and figure out.
     
    Campbell Ritchie
    Marshal
    Posts: 56536
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Nicole Strawn wrote:. . . it's that it doesn't concatenate? . . .
    Don't guess. Try it out.
     
    Campbell Ritchie
    Marshal
    Posts: 56536
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Junilu Lacar wrote:. . . 7 + 5 + " blah " is going to be very different from " blah " + 7 + 5. . . .
    That is similar to seventy‑six trombones. I think there is an example in the JLS link I posted yesterday showing the same phenomenon.
     
    Campbell Ritchie
    Marshal
    Posts: 56536
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I also think Junilu has provided enough explanation that you can work your way through this minefield of conflicting information:-
  • 1: I said String#valueOf yesterday
  • 2: Knute said Object#toString
  • 3: Both are correct
  •  
    Tim Holloway
    Saloon Keeper
    Posts: 18792
    74
    Android Eclipse IDE Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Given an option to choose "toString()" versus "String.valueOf()" I recommend that you consider using valueOf.

    Firstly, because toString() requires a class object instance as its basis, so it cannot be applied to primitives. That is, "1.toString()" is syntactically invalid in Java - although some other languages have a different opinion.

    Secondly, because the default behavior of toString()  inherited from class java.lang.Object reflects its internal representation in the JVM and not necessarily either the value you want to print or the value in the format you'd like it to print. toString() on the other hand, usually at least gives you something worth looking at. Although since it's also a favorite formatter for serialization, the format of the basic "valueOf" may be more suited for a deserializer's parsing than the way you'd like to read it.

    Also note that null.toString() throws an Exception, but String.valueOf(null) prints "null".

    And since this is Pedantry Week:
    The Music Man wrote:
    There were 76 trombones in the Big Parade
    With 110 cornets close at hand
    There were a Thousand reeds springing up like weeds
    There were horns of every shape and kind...


    Actually, I forget if it's "close at hand" or "right behind", but I'm too lazy to check. And incidentally, the opening credits for the movie were done in a spectacularly interesting way.
     
    Campbell Ritchie
    Marshal
    Posts: 56536
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    It has even cornier lines than that.
     
    Knute Snortum
    Sheriff
    Posts: 4276
    127
    Chrome Eclipse IDE Java Postgres Database VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    So now, I still don't know overloading, or the "methods of String"

    Just to hone in on these questions:

    * Overloading in this situation means "it can do more than one thing," but more specifically in Java, you can overload a method so that it can be called in more than one way.  So say you had a method like this:
    You could then write another plus method like this:
    Now you can call the method two ways and Java "knows" which one is which:

    * The String class (with a capital "S") has methods, just like an "ordinary" class.  You can look up those methods in the Java API document.  The thing that is confusing about strings in Java is that "Hello, World" is as much an object as String str = new String("Hello, World").  Just as you can call methods on str, you can call them on "Hello, World".
     
    Tim Holloway
    Saloon Keeper
    Posts: 18792
    74
    Android Eclipse IDE Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Actually, if you reference a literal string like "Hello, World!", the system will automatically manufacture a String object out of it, either by doing an internal new String() or by finding an existing instance in the String pool.

    You can't say "1.toString()" in Java, but "abcde".substr(1,2) is quite valid. String literals are not primitives. "abcde".getClass().getName() returns "java.lang.String", and "abcde" instanceOf java.lang.String returns "true".
     
    Campbell Ritchie
    Marshal
    Posts: 56536
    172
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Anybody heard from OP whether we have scared her off or how many cornets she found?
     
    Nicole Strawn
    Greenhorn
    Posts: 8
    Eclipse IDE Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote:Anybody heard from OP whether we have scared her off or how many cornets she found?


    Lol, not scared off. I appreciate all the information and the willingness to help. I think, though that you guys are underestimating my level of noob. I spent most of last night and today trying to figure out an initialization error in a loop example from the textbook. (why isn't there a line in textbooks explaining the rules of this), but now that I've "solved that" I see that it's in Chapter 2... So less scared and more frustrated with myself. I've not even reached the chapter on classes and methods and all that, I'm day three and a lot of stuff is just over my head right now. I have to spend about two hours googling for every paragraph I read, so progress is slowly. People have apparently finished the book in a month and I'm taking a week on the first chapter?

    I studied med till I was 27 and absolutely nothing at all for the past three years, (I'm coming off about 3 years of Netflix). I was good at maths, but like, waaaaaay back in my teenage years and it's like the practical parts of my brain are still on a go slow or dead altogether. I had to google factorial numbers, that's how far I've fallen.

    Registration fees have already been paid, so I literally can't afford to be scared off, but I'm starting to feel like "Well, children can do it, so how complicated can it be?" was a very wrong attitude to come in with. Programming is much harder than enthusiasts on YouTube make it out to be. I'm moving through it with the pacing of a drunk person putting one foot in front of the other to avoid a DUI charge - unsure, very wobbly and thoroughly disoriented. I'm probably weeks away from getting use out of the Java API specification info.

    I just finished chapter 1.
     
    Junilu Lacar
    Sheriff
    Posts: 11485
    180
    Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Some children can do it, many can't. Likewise, some adults can do it, many can't. And if we're being honest, even some paid professionals... well, maybe that's best left for another time...

    The thing with programming is that it doesn't matter how young or how old you are. Rather, it's the kind of viewpoint you're able to take as you're learning to converse with computers.

    I remember the very first time I sat in front of a computer with only this staring back at me:

    A>_

    the little blinking underscore that I later learned was called a "cursor" quietly egging me on to type in a command and hit ENTER. (See https://commons.wikimedia.org/wiki/Category:CP/M#/media/File:CPM_2-2.jpg)

    I remember feeling overwhelmed by the apparent vastness of what I didn't know. That uncomfortable feeling of trepidation and cluelessness only grew with each second that the blinking cursor sat there unanswered, waiting for me to type in something that the computer actually understood. Thinking about all the things you don't know is exactly the wrong way to approach this. You have to turn it around and celebrate every time you learn how to tell the computer to do something. This is the viewpoint you're taking when you write the proverbial "Hello, World!" program. Learn one simple command to make the computer do something. Then build on that.

    You'll take the same approach to familiarizing yourself with the API JavaDocs. Since your first program used the System object, start your exploration of the standard Java library there (https://docs.oracle.com/javase/8/docs/api/java/lang/System.html). Looking around that page, you should find the link to the out field. Read about that, then follow the link to PrintStream, the type of the System.out field. Then look around the page at other things a PrintStream object can do. Maybe you'll see the print() method and decide to play around with that, comparing what it does with the println() method you already tried out before. When you learn more about the print() and println() methods, maybe you'll see the printf() method and wonder what that method can do that's different from the other two you've already played around with. It just keeps going from there.

    If you just keep taking one baby step after another, before you know it you'll have a whole repertoire of commands in your Java bag that you can mix and match to do exponentially more and more things.
     
    Campbell Ritchie
    Marshal
    Posts: 56536
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Nicole Strawn wrote:. . . "Well, children can do it, so how complicated can it be?" . . .
    We've all been there, done that, got the tee‑shirt and been told earnestly that programming is the most difficult activity known. So, yes, it can be hard.
    Believe it or not, plan what you are going to do and then let your brain go into neutral when you write the actual code. That is supposed to be counter‑lintuitive. But also, we know what it feels like. Which is why we are prepared to take the  time to explain things, in Junilu's baby steps, to people who are prepared to put in the effort. After chapter 1 you can expect to know chapter 1 stuff, and you move in baby steps as Junilu said (again). We have been at it long enough to know that sort of thing.

    Anyway, did you get seventy‑six trombones, or a different number?
     
    Nicole Strawn
    Greenhorn
    Posts: 8
    Eclipse IDE Java
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Junilu Lacar wrote:

    An important point to note is that evaluation goes from left to right. So, 7 + 5 + " blah " is going to be very different from " blah " + 7 + 5.


    This was the important thing I wasn't taking note of. Got stumped by the 10010. 

    I'm that type of person who has to fake write in the air to know right from left... Much shame.
     
    Campbell Ritchie
    Marshal
    Posts: 56536
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Did you go through the JLS link I posted last week? Did you find the bit about fiddlers three which doesn't print three at all?

    Remember Java® evaluation goes from left to right, but respecting operator precedences. Now, in the bit about seventy‑six trombones, the only operator in the whole expression is +, so there are no precedence issues to take into consideration, but it is a left‑associative operator,a dn goes from left to right.
  • 1: 70 + 6: added together to make the number 76.
  • 2: + "trombones..." Since the right operand is a String, the left operand is converted to a String with the String#valueOf method converting it from 76 to "76" and then the two are concatenated.
  • 3: ... + lineSeparator. Since the line separator is already a String, that is concatenated to the existing String operand.
  • 4: ... + 100. Again, since one of the operands is already a String, the number 100 is converted to the String "100" and that is concatenated.
  • 5: ... + 10. As before the 10 is converted to "10" and the left operand is a String ending "...100". So the "10" is concatenated to that, creating a String ending "...10010"
  • 6, 7, 8: Continue concatenating to the end of the expression.
  • Probably, the easiest way to sort that out is to change
    100 + 10
    to
    (100 + 10)
     
    Campbell Ritchie
    Marshal
    Posts: 56536
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Nicole Strawn wrote:. . . Having great difficulty with "Instance creation", . . .
    That sounds like a different problem which merits a discussion of its own.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!