Can I print the string directly by initializing it inside the print statement? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can I print the string directly by initializing it inside the print statement?

ex: System.out.println(String s="Amazon"); //here, amaxon is value and s is variable && I'm guessing it wont work... or is there a way to input and print in the same line or there has to be initialization and output in seperate lines?

18th Aug 2016, 10:38 PM
Souparna Biswas
Souparna Biswas - avatar
3 Answers
+ 2
You can not initialize a variable inside a parameter which is what those parenthesis are. Those parenthesis take arguments to pass to the System class in order to print to the screen, an initialization isn't an argument, and the System class doesn't know what to do with such code, it only wants arguments in those parenthesis. As for inputting outputting at the same time without initializing a string variable you can do like so. Scanner reader = new Scanner(System.in); System.out.println(reader.nextLine()); This is still passing an argument though, it just passes the argument when you input it then prints it right back out. and @Kan String s = "Amazon"; is perfectly acceptable. In fact, is encouraged over excess object creation with new String("Amazon");
19th Aug 2016, 5:42 AM
James
James - avatar
0
if you already have Amazon as a string i think you just have to put it into println ex: (code i used for a program): import java.util.Scanner; class program{ public static void main(String[] args) { Scanner br = new Scanner(System.in); String input; System.out.println("Hi! Whats your name?"); input = br.nextLine(); System.out.println(input+" you are:"); //What was done here was i set input as string (yours will be Amazon). then you see the question (dont worry about that). After that line you see input = br. nextLine (); that line helps run the next line where you see the input (users name) which is now initalized. i hope i helped you... i feel like that didnt make sense... but if your confused still, ill try to explain it in another way. (if you want to see the full code goto codeplayground and lookup "MOTIVATION: DONT GIVE UP!")
19th Aug 2016, 12:28 AM
Aquarius
Aquarius - avatar
0
no it wont... String s = "Amazon" does not set the data of s as Amazon in java we do the following String s= new String("Amazon");
19th Aug 2016, 5:09 AM
Kanhaiya Mishra