Skip to main content

Java Programming Basics to Brilliance Part 3

This post is a progression to previous post Java Programming Basics to Brilliance Part 2.



Before we make things complicated lets first get to know what is an array and how we can use it.

Quoting from Google,
array
əˈreɪ/
noun
  1. 1.
    an impressive display or range of a particular type of thing.
    "there is a vast array of literature on the topic"
verb
  1. 1.
    display or arrange (things) in a particular way.


In Java, an array is an object which holds a specified number of similar number, strings or objects. This depends on the type of array you are making.
The size of an array is set when it is initialized.
For e.g.
 int listOfNumbers[] = {1,2,3,12,2};

This is one way of making an array with values in it.
Now recall how everything in Java is nothing but an object. Considering that you can also make a blank array as follows:

String myHeroes[] = new String[5];

Now the above line of code initialized a blank array of String type of length 5.
Note that this array is of type String, so you cannot feed values other than String into it.
Let's feed some values into this array.

myHeroes[0] = "Lanaya";
myHeroes[1] = "Lina";
myHeroes[2] = "Rylai";
myHeroes[3] = "Mercurial";
myHeroes[4] = "Lyralei";

Now that we have an array of numbers listOfNumbers and an array of string myHeroes now obviously if we want to make use of this array we need a way to access these values. 
To do that we loop through the array and do whatever we want accordingly.
But before we loop through an array take note of how the length of array myHeroes is 5 but we added values up to myHeroes[4] only. This is simply because array index starts from 0 not 1 and that makes the size of array as 5.

To further clear up the confusion you can use 
arrayName.length; to find out the length of the array.

For e.g.

         System.out.println(myHeroes.length);


Now back to looping.
The simplest and easy to understand form of loop is a for loop. And once you understand for loop there another version of it called foreach loop which is really handy and saves lots of confusion.

for loop

for(int i=0; i<10; i++){
            System.out.println(i);
}

This simple loop will print numbers 1 to 9. How?

You can see the above for loop defined as follows

for(initial values; condition checking; update){
//loop body that executes if condition check is true
}

Now the update part of for loop need not necessarily be increment only. You can instead decrease the values, divide, multiply etc.
Rest should be pretty much self explanatory.
Lets use this loop to print the list of heroes we made.

         for(int i=0; i<myHeroes.length; i++){
            System.out.println(myHeroes[i]);
}

Notice how we ran the loop for values starting with to to just less than the length of array. Explained above.

Now a rather simplified version of for which is foreach loop.
For the array myHeroes[]
we can print the array values using for each as follows:

 for(String i: myHeroes){
            System.out.println(i);
        }

Think of foreach loop as defining a variable i that will be holding values from the array one by one.

To better understand this looping consider following lines of code

for(typeOfValuesInArray variableName: arrayName){
variableName; //this will access all of the values inside the array one by one in the order
}
Having done all that lets move to a fairly complex yet very useful part of Java called Collection.

Collection.

Collection are a way for storing objects in Java.
Collection provide necessary features which help in ordered storage of data and easier manipulation of the same.
There are various collection interfaces in Java predefined and you can create you own collection as well.
Namely, there is
List,
ArrayList, Vector,
Queue,
LinkedList, PriorityQueue,
Set,
Sorted Set, TreeSet, HashSet, LinkedHashSet,
Map,
HashTable, HashMap, LinkedHashMap, and TreeMap.

Various Collections

Various Map Collection

Unless you are giving some exam there is no absolute need for remembering all the names.
For the sake of this tutorial and get going with Java Programming I will be using just the ArrayList with reference of List collection and might cover others in future.

Consider the program below:

import java.util.ArrayList;
import java.util.List;

public class ListExample {




public static void main(String[] args) {

List<Dog> dogsList = new ArrayList<Dog>();

String dogName;

int dogId;

for(int i=0; i<10; i++){

dogName = "Dog"+Integer.toString(i);

dogId = i;

dogsList.add(new Dog(dogId, dogName));

}

for (Dog dog : dogsList) {

System.out.println(dog.getDogId());
System.out.println(dog.getDogName());

}

}

}





Different type of collection have different properties and usefulness in their domain. Deciding the right collection depending on the requirement is something that affects your application thoroughly. I will leave that you as it requires research depending on the requirement and even I'm not all aware of all of the collections. 

That's all for now. If you go through these 3 tutorials on Java you are likely to get through anything. I'm not entirely sure what will be next in this but in case I do write it will be updated here.
Keep Coding...

Comments

Popular posts from this blog

Unity Mobile Game Optimization Checklist

- On Image and Text components that aren’t interacted with you can uncheck “Raycast Target” on it, as it will remove them from any Raycast calculus. - Click on your textures in your “Project” window. Click on the “Advanced” arrow, and now check “Generate Mip Maps”, Unity especially recommends it for faster texture loading time and a lower rendering time. - Set the “Shadow Cascades” to “No Cascades” (Quality settings) - If you have dynamic UI elements like a Scroll Rect with a lot of elements to visualize, a good practice is to turn off the pixel perfect check box on the canvas that contains the list and disable the items that aren’t visible on the screen. - Set all non moving objects to "Static" - Above Unity3d 2017.2 you should turn off "autoSyncTransforms" on the Physics tab - Always use Crunch Compression Low on textures - Try to keep the “Collision Detection Mode” on “Discrete” if possible, as “Dynamic” demands more performance. - You can go to the TimeManager w...

How to make download file button in react js

To create a download file button in React.js, follow these steps: Import the necessary dependencies: javascript Copy code import React from 'react' ; import { saveAs } from 'file-saver' ; Create a function that handles the download action: javascript Copy code const handleDownload = ( ) => { // Create a new Blob object with the desired content const fileContent = 'This is the content of the file you want to download.' ; const blob = new Blob ([fileContent], { type : 'text/plain;charset=utf-8' }); // Use the saveAs function from the file-saver library to initiate the download saveAs (blob, 'download.txt' ); }; Create a button component and attach the handleDownload function to the button's onClick event: javascript Copy code const DownloadButton = ( ) => { return ( < button onClick = {handleDownload} > Download File </ button > ); }; Use the DownloadButton component wherever ...

How to Convert Unreal Engine 5.1 Blueprint Project to C++ Project

To begin, open your project in the Unreal Engine 5 or a newer version of the editor.  Next, access the New C++ Class Dialog by selecting Tools and then New C++ Class .  From there, create a new "None" class and press "Create Class."  You might receive a warning message regarding the game module compilation, but you can disregard it and choose "No."  After closing any pop-ups, warnings, or success notifications, exit the Editor.  Proceed to your project's folder, right-click on the .uproject file, and select "Generate Visual Studio project files."  Double-click your project's .sln file to open it in Visual Studio.  In Visual Studio's Solution Explorer, find and choose your project.  Select "Development Editor" in the build configuration drop-down menu.  Right-click on your project and select "Build" to compile it without any errors.  Afterward, set the build configuration drop-down menu to "Development" ...