After my last video I received a bunch of messages asking me to cover Java Arrays. So in this video I go over everything you’d ever want to know about Java Arrays.
I show you how to create arrays, numerous ways to populate them, tricks involving multidimensional arrays, the enhanced for loop, Array library methods and more.
If you missed part 1 of this series check it out first here Java Video Tutorial.
Like always heavily commented code follows the video.
If you like videos like this share it
Code from the Video
import java.util.Arrays; public class LessonNine { public static void main(String[] args){ // An array is a variable that can hold a bunch of values // Think of an array as a big box filled with other boxes // Each box has a number on it called an index that you use // to access its specific value /* Array Rules * An array can contain only values of the same type * An arrays size can't be changed once it is set * An array is an object */ // You declare an array with the dataType[] arrayName int[] randomArray; // You create an array with // dataType[] arrayName = new dataType[sizeOfArray]; int[] numberArray = new int[10]; // You can add values to the array in many ways // Individually // Most create array and define size first randomArray = new int[20]; randomArray[1] = 2; // You can also create the array and its values from the start String[] stringArray = {"Just", "Random", "Words"}; // You can add values with a loop // arrayName.length returns the number of elements in the array for(int i = 0; i < numberArray.length; i++) { numberArray[i] = i; } // Draws 41 lines on the screen int k = 1; while(k <= 41){ System.out.print('-'); k++; } System.out.println(); // Cycles through all of the boxes in the array and prints them for(int j = 0; j < numberArray.length; j++) { System.out.print("| " + j + " "); } System.out.println("|"); // Draws 41 lines on the screen k = 1; while(k <= 41){ System.out.print('-'); k++; } System.out.println(); // Multidimensional Array // To but arrays in an array just add another [] String[][] multiDArray = new String[10][10]; // Adding values to a multidimensional array for(int i = 0; i < multiDArray.length; i++) { // To get the length for the array in the array you must follow it // with brackets with the index between them like [i] for(int j = 0; j < multiDArray[i].length; j++) { multiDArray[i][j] = i + " " + j; } } // Draws 61 lines on the screen k = 1; while(k <= 61){ System.out.print('-'); k++; } System.out.println(); // Prints out a multidimensional array with the values being the indexes for(int i = 0; i < multiDArray.length; i++) { for(int j = 0; j < multiDArray[i].length; j++) { System.out.print("| " + multiDArray[i][j] + " "); } System.out.println("|"); } // Draws 61 lines on the screen k = 1; while(k <= 61){ System.out.print('-'); k++; } System.out.println(); // You can use the enhanced for loop to print out array values // for(itemDataType tempVariable : arrayName) for(int row : numberArray) { System.out.print(row); } System.out.println("\n"); // To use enhanced for for a multidimensional array you follow this formula // for(dataType[] varForRow : arrayName) for(String[] rows : multiDArray) { // for(elementDataType varForColumn : varForRow) for(String column : rows) { System.out.print("| " + column + " "); } System.out.println("|"); } // You can copy an array in a couple of ways // Arrays.copyOf(arrayToCopy, numberToCopyFromBeginning); int[] numberCopy = Arrays.copyOf(numberArray, 5); for(int num : numberCopy) { System.out.print(num); } System.out.println("\n"); // You can copy an array from one index to another with copyOfRange // int[] numberCopy = Arrays.copyOf(numberArray, 1, 5); // You can print out the whole array with toString System.out.println(Arrays.toString(numberCopy)); // Do define a default value for an array use fill // Arrays.fill(arrayName, valueToFill); // valueToFill must be the same for each element in the array int[] moreNumbers = new int[100]; Arrays.fill(moreNumbers, 2); // Filling a multidimensional array char[][] boardGame = new char[10][10]; for(char[] row : boardGame) { Arrays.fill(row, '*'); } // You can sort an array using sort() int[] numsToSort = new int[10]; // Generate array full of random numbers for(int i = 0; i < 10; i++) { numsToSort[i] = (int) (Math.random() * 100); } // Sort the array in ascending order Arrays.sort(numsToSort); System.out.println(Arrays.toString(numsToSort)); // binarySearch returns the index for the searched for value // If it doesn't find it it returns a negative number int whereIs50 = Arrays.binarySearch(numsToSort, 50); System.out.println(whereIs50); } }
Hi Derek, I am enjoying the java lessons. I was using Lynda.com but gave up on them. The instructor talked so fast in about 20% of the lessons I got frustrated and began looking on YouTube. I have a question on this lesson 9. On line 50 – 55 It looks like j is being assigned a value from the for() statement variable and not from an array. I don’t see a connecting between j and any array? Thank much Andy
I sent this on YouTube already, but I wanted to make sure you saw it
Yes j is beingο»Ώ assigned a temporary index from 0 to the last index in the array named numberArray. It is basically there to serve as a title bar listing of columns from 0 to 9. It doesn’t serve any other purpose. Thinking back, I didn’t love this example and I much improved on this tutorial as I progressed into part 11 and then on.
Ah, I sort of figured out something was a bit wrong there. Could you please edit it? Or atleast add a comment saying you’re just adding a mock value? Because this could be extremely misleading. Thanks, and nice tutorials.
Hi Derek,
I am using notepad++ to execute the java programs. I have two class files and i am trying to access methods in second files in the first file but I am getting error saying class not found. can you please suggest what I am missing here.
Are you certain that you are saving in the same file? I’m kind of confused, by what code you are using because I only have one class file for this tutorial
Actually installed Eclipse IDE and it worked fine …Thanks a lo Derek
You’re very welcome π
This is for Gaurang Tandon on YouTube
How to reverse sort an int array
import java.util.Arrays;
public class reverseSort {
public static void main(String[] args) {
int[] numArray = {1,2,3,4,9,7,6};
for(int i=0;i numArray[i])
{
int[] temp = new int[7];
temp[j]=numArray[j];
numArray[j]=numArray[i];
numArray[i]=temp[j];
}
}
}
System.out.println(Arrays.toString(numArray));
}
}
Thanks π
You’re very welcome π
Hey Derek for the 2 dimensional array example I think its better to fit everything in the first for loop, I believe it makes it less confusing:
String[][] multiDArray = new String[10][10];
int k = 1;
while(k <= 61){ System.out.print('-'); k++; }
System.out.println();
for(int i = 0; i < multiDArray.length; i++)
{
for(int j = 0; j < multiDArray[i].length; j++)
{
multiDArray[i][j] = i + " " + j;
System.out.print("| " + multiDArray[i][j] + " ");
}
System.out.println("|");
}
k = 1;
while(k <= 61){ System.out.print('-'); k++; }
System.out.println();
}
}
Thanks for the input π The code isn’t often optimized. I some times lean towards writing understandable code over optimizing. I also write a lot of this code out of my head, so that is another reason for it to not be optimized. Sorry about that, but that is what makes these videos fun for me to make. I hope that makes sense
Hi Derek,
it’s been a long time since i have worked on java. I am coming back to it after working on c++ for many years, and your videos are just perfect way for me to revise everything in no time !
Moreover, I would appreciate a lot if you can arrange a tutorial on how to debug java code in eclipse. Something like using breakpoints, how to start a java process while debugging .. !! It would be of great help !
Thanks
Kuldeep
Hi Kuldeep,
I plan on doing a big Java Debugging tutorial. To tell the truth I normally don’t have debugging issues because I plan everything out on paper in detail before I write code normally. You may find my Object Oriented design tutorial very useful. It is one of my favorite tutorials π
hello derek,
1)
How do i display ‘for all’ quantifier character inverted A of math in java?
For all n belongs N ….
2)
int[] values = new int[3];
This constructor type syntax, makes me ask, if int is class?
Again another c type syntax,
int[] values = {1,2,3};
Makes me ask, if int is primitive type?
Please help.
Sham
Hello,
I’m sorry but I don’t understand the first question. As per the second yes ints are primitive types and not objects. Sorry about the confusion.
Hi Derek,
Would you have an example of a character array? For instance if I had the user enter their name in a dialog box, and that data comes in as a string. That data will have to be converted to store the letter in a character array. Do you have any examples like that?
Hi Kim,
I cover arrays in detail in the first part of my Java Algorithms tutorial. I hope it helps π
Cool Lab… I can not say thank you enough, and how much it helps me to get back to Java so quickly. I got my SCJP 10 years ago… π
Just wonder, how I can code copied form here without the line tags?
Keep good work! Derek!
Thank you π If you put your mouse over the top right edge and click View Source you can eliminate the line numbers. Sorry about that.
Loving the tutorials, and I want to thank you for posting lessons for free, as I have no money to pay for lessons, and I’m trying to break into game development. I do have a question though: since my friends and I are starting our business with Android games, and I see that you have Android game development tutorials, do I need to learn Java first, or can I jump straight to Android development lessons? I’m more than willing to finish the rest of these if it’s something I’ll need right away, but I don’t want to waste my time if I don’t need it. And if additional lessons are necessary, would you recommend Java or another of Android’s compatible programming languages like Python? Also, can Java be used to power PC games as well? Thanks for taking the time to read this. π
Thank you π I’m glad you enjoy them. At the very end of the Java tutorial I actually make the game Asteroids. Much of what you need to know about games are covered there and translate into developing Android games.
As per what Java you need to know for Android, you need to understand parts 1 through 18 minus tutorials 8 and 10. You also should watch my Java MVC tutorial. You will better understand OOP with the first 2 parts of my Java design patterns tutorials.
I’m currently covering App Inventor which is a fun and easy way to learn Android. I’ll make a game with it very soon. I hope that helps
Derek
muy Buenos tus tuto,”Very Good Your Tuto”
Gracias
Gracias . Me alegra que te haya gustado π