I need to gain a better understanding of methods and arrays.
This is what I've done but I don't think its right
String a = 1;
String b = 2;
String [] arr = String [a + b];
System.out.println(arr);
I need to gain a better understanding of methods and arrays.
This is what I've done but I don't think its right
String a = 1;
String b = 2;
String [] arr = String [a + b];
System.out.println(arr);
You need to come up with something.. We can only help if you try, if you help yourself. But here's something you can start with...
public void print(String[] args)
{
for(String s:args)
System.out.println(s);
}
Update: I dint get exactly what are you trying to do by ..
String[] arr= String[a+b];
Anyway, if you want to create an array of Strings using Strings.. here's how you do it..
String a="Hello ";
String b="World!!";
String[] arr={a,b};
And for printing the strings, refer to the the answer above. If you will pass it to println()
, it will call toString()
which will print it in a particular format.
Its always better to explore and learn before posting here. anyway use below code:
public void printString(String[] strings){
for(String string:strings)
System.out.println(string);
}
Your code should be changed to:
String a = "1";
String b = "2";
String[] arr = {a,b};
First you should understand what are arrays and methods and how they work.
Array:
Array is a systematic collection of objects or elements. You define an array to store elements of particular type. For Example:
String str[10];
would define an array of 10 string objects.
You also need to allocate memory for objects before using them.
Also have a look at Steps in the memory allocation process for Java objects for better understanding.
Methods:
A method is a subroutine associated with a class.
For a good basic understanding of methods look at Defining methods.
As far as your specific question is considered, you should read the control structures.
You are doing
String[a+b]
which doesn't seem to be doing at all what you intend.
While reading the control structures, do take a good look at for and while looping structures.