File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes First post - Logic of a simpe java program Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "First post - Logic of a simpe java program" Watch "First post - Logic of a simpe java program" New topic
Author

First post - Logic of a simpe java program

Bashi Bazoo
Greenhorn

Joined: Mar 13, 2006
Posts: 3
Hi
I am new to programming, actually I just wrote my first hello world a few seconds ago (clap clap clap)

I have done some reading so I understand some of the syntax in java, my question, can anyone explain the logic behind this program and how they work please:

1. public class CommandArgsThree {
2. public static void main(String [] args) {
3. String [][] argCopy = new String[2][2];
4. int x;
5. argCopy[0] = args;
6. x = argCopy[0].length;
7. for (int y = 0; y < x; y++) {
8. System.out.print(" " + argCopy[0][y]);
9. }
10. }
11. }

When you compile and issue the below command
java CommandArgsThree 1 2 3
The output should be 1 2 3

I got confused with lines 5, 6, 7 & 8. Please can I have a detailed explanation?
thanks!
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Hi Bashi, welcome to JavaRanch!

This might be a bit involved to follow a Hello World program, but here's what's happening.

argCopy is a "2-dimensional" array, denoted by the double sets of braces, [][]. In Java, multi-dimensional arrays are really just arrays of arrays.

In line 2, argCopy is instantiated with lengths [2][2]. So argCopy[0] references a String array of length 2, and argCopy[1] references another String array of length 2.

Because no Strings have been assigned yet, the String arrays hold null references. So essentially, we have...

argCopy = { {null, null}, {null, null} };

Now, args references the String array that holds any command line arguments. So when you run the program with...

java CommandArgsThree 1 2 3

...then args is { "1", "2", "3" }.

In line 5, argCopy[0] = args reassigns argCopy[0] to reference the same String array as args, instead of referencing {null, null}. (Note: The length of these arrays is different, going from 2 to 3. But the dimension is still the same, because these are both single-dimension arrays.)

Next, x is set to the length of argCopy[0], which is now 3. The loop iterates through the elements of argCopy[0] (which are argCopy[0][0], argCopy[0][1], and argCopy[0][2]), printing the Strings "1", "2", and "3".

Note that argCopy[1] hasn't been touched. It's still a String array with null references.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Charles Lyons
Author
Ranch Hand

Joined: Mar 27, 2003
Posts: 836
This example seems overly complicated - it uses a two-dimensional array (that's one with [][] after the datatype, rather than a one-dimensional array which just has []) when a 1D array would do...

Let's break it down by lines, from 3 onwards:

(3) Here we declare a 2D array, with each dimension having capacity (length) 2. If you're familiar with linear algebra, this structure is in effect a matrix (actually a square 2x2 matrix). The 2D array initially has entries:

[0][0], [0][1]
[1][0], [1][1]

which are all 'null' to start with.

(4) Declare an int x - note that this must be initialised to some value before being used for the first time or we'll get a compilation error.

(5) In this step, we copy the array args (a 1D array) into the [0] entry of the argCopy array. What this does is replace the String[] of length 2 in the [0] entry with args (which could be of any length). This assignment is achieved using "argCopy[0] = args" as in line (4).

You see that argCopy[1] isn't modified, so its length stays at 2, which I think is the point of having the 2D array in the first place. We now have a "jagged" array, with the argCopy[0] entry containing a total of args.length entries, and the argCopy[1] entry containing 2 entries.

(6) We initialise 'x' to the length of the argCopy[0] array - this is the same as the length of the args array (since we declared them to be the same in line (5)).

(7-9) We loop through each entry in argCopy[0]; we're using y as a 'dummy variable', to simply maintain the counter on the loop. Our value of x is just the number of entries in argCopy[0] = number of entries in args (which given your example command-line arguments, will be 3). So we iterate in the loop starting at y=0, then y=1, then y=2 and finally terminate there because then y >= x since on the next iteration y==3 (assuming x==3, as is the case when there are 3 command-line arguments). So for "java CommandArgsThree 1 2 3", the actual loop does this:

y==0 : System.out.print(" " + argCopy[0][0]);
y==1 : System.out.print(" " + argCopy[0][1]);
y==2 : System.out.print(" " + argCopy[0][2]);

Note that since we copied args into argCopy[0] in line (5), this is actually the same thing as:

y==0 : System.out.print(" " + args[0]);
y==1 : System.out.print(" " + args[1]);
y==2 : System.out.print(" " + args[2]);


Given your input arguments are "1 2 3", then we have args[0] is "1", args[1] is "2" and args[3] is "3", so this loop will produce " 1 2 3" as the result. Hoorah, it works!


Having said that, I think this example is overly complicated. Where did you find it, in a beginner's book or on the Internet?

For a start, we declare a 2D array when only one dimension is actually ever used - I think this is supposed to show that the arrays can be "jagged" - i.e. each element in a dimension may have a different length sub-array, which is clear if we declare the type as String[][], then the entry String[0] may contain a String[] of any length as its value, and similarly for all other entries.

We also do unnecessary copying of args into argCopy[0] - there is no need for the copy, because we can just reference args directly later on if we wish. Then we store x = argCopy[0].length - but again, we needn't clutter the code with this extra variable x. Instead, we can just reference argCopy[0].length or even args.length directly in the loop's test condition.

If you try to simplify the code, you get something like this:



which you should see just iterates through the command-line arguments, and therefore using the arguments "1 2 3", as before, you'll get " 1 2 3" out again. This is exactly the same as your example, but much clearer.

Note that J2SE 5.0 introduces a more compact loop (the so-called "for each" loop) which does the iteration over an array for you, without having to worry about counters and 'dummy variables':



where line (3) is read as "for each String s in args", or alternatively "for each element in the array args, assign the variable s of type String for this iteration of the loop". We then print out the value of s for each iteration...

Hope that helps! Please post back with any further queries.


Charles Lyons (SCJP 1.4, April 2003; SCJP 5, Dec 2006; SCWCD 1.4b, April 2004)
Author of OCEJWCD Study Companion for Oracle Exam 1Z0-899 (ISBN 0955160340 / Amazon Amazon UK )
Bashi Bazoo
Greenhorn

Joined: Mar 13, 2006
Posts: 3
Marc & Charles;

I have to say wow, both your answers serves as a real eye opener. I am surely gonna save this and use it as a reference for any multi-dimensional I come accross.
I have done more reading than hands so I was able to follow your explanation very well.

Charles, I got the question from the Kathy Sierra 310-035 book, I tot it must be simple code and I must be a block head for not following. The book had touched on multi-dimension but not on jagged arrays (which is a new term for me).
And yes I see compiling the simplified script also gets same result, thanks so much guys, I really appreciate the help!!
Charles Lyons
Author
Ranch Hand

Joined: Mar 27, 2003
Posts: 836
Charles, I got the question from the Kathy Sierra 310-035 book, I tot it must be simple code and I must be a block head for not following.


Oh, if you got it from a 310-035 SCJP exam guide, then I'm not surprised the code was obfuscated a little. The SCJP exam itself tries to put forward code which could potentially have errors in lots of different places - only a careful examination of the code will show what's really happening and if there are any errors and where they are.

The purpose of exam guides is to try to cram as much detail into a short space as possible, and they aren't meant as a beginner's guide to the language - on the contrary, they are meant for people of novice/expert status who just need to brush up on their skills, or who need to prepare themselves for the style of the exam.

If you really want to understand Java, from the basics of objects and application modelling right up to building a Swing GUI, I can recommend Jacquie Barker's Beginning Java Objects: From Concepts to Code:

http://www.amazon.com/gp/product/1590594576

It consistently gets high reviews and is a great book - I learnt a lot from the first edition all those years ago...

The book had touched on multi-dimension but not on jagged arrays (which is a new term for me).


Well, you may not find the term "jagged arrays" in many Java references - I borrowed the term from C# (loosely, the Microsoft .NET equivalent of Java). A "jagged array" is simply an "array of arrays, each of which may have a different length"; this is contrasted to a "rectangular array", where each array has the same length - e.g. in String[2][3], there are exactly 2*3 = 6 components and we can lay it out in rectangular form:

[0][0] [0][1] [0][2]
[1][0] [1][1] [1][2]

A jagged array might be:

[0][0] [0][1]
[1][0] [1][1] [1][2]
[2][0]
[3][0] [3][1]

The terminology "rectangle" and "jagged" should be pretty obvious.

C# is a bit of an evil word round these parts, so I'll try to avoid mentioning it, and I certainly won't steer you towards it as a language (I'm sworn to Java before anyone asks!) But the contrast of rectangular and jagged arrays in C# is an interesting one, and C# has a special syntax for regtangular arrays which isn't found in Java; for an explanation, see this:

http://www.csharphelp.com/archives/archive93.html

Personally, I don't think the distinction is necessary, and I find that the Java way of just nesting arrays inside arrays is perfectly good enough - that way we can build rectangular or jagged arrays as we see fit, without having to worry about the distinction.

Good luck!
[ March 16, 2006: Message edited by: Charles Lyons ]
Bashi Bazoo
Greenhorn

Joined: Mar 13, 2006
Posts: 3
Hi Charles,
Thanks so much for the update on jagged arrays. I will go get the look and feel of the book you suggested this weekend @ the bookstore. It sure has a lot of postive review.
Thanks!

......
Bashi
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: First post - Logic of a simpe java program