0

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);
Kris
  • 14,426
  • 7
  • 55
  • 65
user1061354
  • 7
  • 1
  • 3
  • 8
  • Have a look at [Arrays](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) and [Control Flow Statements](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html) from Oracle's Java Tutorials. – Jesper Dec 06 '11 at 07:42
  • What have you tried? Have you looked at any of the thousands of Java tutorials available on the internet? – Cameron Skinner Dec 06 '11 at 07:43
  • possible duplicate of [Simplest way to print an array in Java](http://stackoverflow.com/questions/409784/simplest-way-to-print-an-array-in-java) – Esko Dec 06 '11 at 07:49
  • Google is our guru , certainly know a lot. – Its not blank Dec 06 '11 at 08:04

3 Answers3

2

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.

vidit
  • 6,293
  • 3
  • 32
  • 50
1

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};
dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
0

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.

Community
  • 1
  • 1
krammer
  • 2,598
  • 2
  • 25
  • 46