Can i create an array that prints when called without having to do the println() method? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can i create an array that prints when called without having to do the println() method?

/*i thought this might work but it dosent*/ public class Program { static void message([]){"hi","hello"}{System.out.println(message[]);} public static void main(String[] args) { message[0]; } }

26th Aug 2017, 6:48 PM
D_Stark
D_Stark - avatar
11 Answers
+ 5
static void message(String[] args){ for(int i = 0; i < args.length; i++) System.out.println(args[i]); } Then call it: message(new String[]{"Hello", "World!"});
26th Aug 2017, 6:52 PM
Rrestoring faith
Rrestoring faith - avatar
+ 4
ye
26th Aug 2017, 9:54 PM
Rrestoring faith
Rrestoring faith - avatar
+ 4
You can also shorten System.out to just the letter o: import java.io.PrintStream; public class Program { public static void main(String[] args) { PrintStream o = System.out; o.println("Hello"); o.print("GoodBye"); } }
26th Aug 2017, 10:10 PM
ChaoticDawg
ChaoticDawg - avatar
+ 3
You're gonna need to use the println() method somewhere. What you could do is create a class that does what you want in the constructor or in a static method of that class and then create an array or arraylist of those objects. If the println() method is used in the constructor then the output would occur when the array/arraylist is initialized. If you use a static method of your new class then you would need to call that method on each element of the array/arraylist when you want it to run.
26th Aug 2017, 8:08 PM
ChaoticDawg
ChaoticDawg - avatar
+ 3
Do you want something like this? static void print(String msg){ System.out.println(msg); } Then call it: print(message[1]); // Assuming message is an array
26th Aug 2017, 9:18 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
cant i create a static void string array in class and call it from main that prints automatically using the variable and array box?
26th Aug 2017, 7:49 PM
D_Stark
D_Stark - avatar
+ 1
just want to shorten my code down
26th Aug 2017, 7:50 PM
D_Stark
D_Stark - avatar
0
ok thanks guys
26th Aug 2017, 8:10 PM
D_Stark
D_Stark - avatar
0
yes please, would (message[1]) be from an array ?
26th Aug 2017, 9:22 PM
D_Stark
D_Stark - avatar
0
thank you faith 👍
26th Aug 2017, 9:55 PM
D_Stark
D_Stark - avatar
0
oh thats cool thnx @chaotic.
26th Aug 2017, 10:21 PM
D_Stark
D_Stark - avatar