Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does using one "print" instead of three work?

Tags:

java

string

So I don't know much about java but I noticed this worked then according to my class notes I should be doing it a different way

Here's what my notes have

System.out.print("hello");
System.out.print(name);
System.out.print("\n");

However I tried this and it also does the same thing. It's shorter so is this an acceptable way to do it or will it break down the road?

System.out.print("hello"+name+"\n);

Also as long as the code runs right my teacher shouldn't care right? It's my first class and I'm not a computer science major.

like image 870
Laura Avatar asked Mar 12 '14 23:03

Laura


2 Answers

It will work and I'd argue that it's in fact a better way to do it.

Go for it, that's the hacker spirit!

If you want something even shorter and more descriptive, try

System.out.println("hello " + name);

The println will automatically print a line end ('\n') at the end of what you print.


Just to make this complete, let's assume name = "James Gosling";.

In the code written in your notes, you first print:

hello

Then, you print name, which leads to:

helloJames Gosling

It's printed like that because we're actually missing a space after "hello". To print it with a space, use "hello ". Finally, we print a newline.

In your (arguably better) piece of code, you print only once, but when you use the expression "hello"+name+"\n", you are creating a new character string which ends up being the same. This is because the + operator concatenates (that is, chains) two strings and creates a new string with the result.

So, when you print the resulting string, you get (plus the newline):

helloJames Gosling

like image 101
ArthurChamz Avatar answered Nov 05 '22 13:11

ArthurChamz


Others have weighed in on the specific example, but there are problems with trying to generalize this.

+ does addition when applied to primitive numeric values instead of doing concatenation when applied to a string, so

int x = 4;
int y = 2;
System.out.print(x);
System.out.print(y);
System.out.print("\n");

prints 42 while

int x = 4;
int y = 2;
System.out.println(x + y);

prints 6 followed by a line-break.

Since + associates left, you can use "" + ... to force + to mean string concatenation instead of addition

int x = 4;
int y = 2;
System.out.println("" + x + y);
like image 37
Mike Samuel Avatar answered Nov 05 '22 12:11

Mike Samuel