Java Array:-
Array in java is used to store multiple values in a single variable instead of declaring separate variables i.e. it is a collection of the same type of elements with an adjacent memory location. It is a data structure where we can store similar elements with fixed sets in a java array. Each item in an array is called an element and each of them is accessed by its numerical index.
Example:
String [] cars; (cars is the name of array
String [] cars = {“Volvo”, “ford”, “bbt”, “Bmw”};
Java array is index-based i.e. the first element of the array is stored at the 0th index, 2nd element on 1st index and further go on. In the example “Volvo” has 0th index value, “ford ” has 1st index value and “bbt” has 2nd and so on. In java, array is an object of a dynamically generated class and it receives the object class and executes the serializable interfaces.
In java we can create a single dimensional array or multi-dimensional array. Multi-dimensional array can be declared as
Examples:
int [][] myValues = { {1,2,3,4}, {5,6,7} };
myValues is an array with two arrays as its element.
int[][]myValues = { {1,2,3,4}, {5,6,7}};
int x =myValues [1][2];
system.out.print(x);
The output of this program will be 7 because 7 has the 2nd index value of 1st array. Here 1,2,3,4 are the elements of the 0th array and 5,6,7 are the elements of 1st array and the system wants us to print 2nd elements of the first array which is defined as x in the second line of the code.
>>To access the elements of an array:
We can access elements by referring its index number such as
string[]cars = {“Volvo”, “BMW”, “Ford”}
System.out.print(cars[0]);
Output-> Volvo.
>> To change the array element:
We can change the element by referring to its index number such as
cars[0] = “opel”;
System.out.println(cars[0]);
Output-> opel.
>> To find the length (number of elements) of the array element we have to use length keyword such a way as described below:
string[] cars = {“volvo”, “MG”, “ford”};
System.out.println (cars.length);
Output-> 3
Jagged Array in java:
A multidimensional array size of member arrays are different in size. We can create a 2D array where the first array is of 2 elements, and another is of 3 elements.
Example:
public class Sab {
public static void main(String[] args){
int[][] twoDArray = new int[2][];
twoDArray[0] = new int[2];
twoDArray[1] = new int[3];
int counter = 0;
for (int row=0; row < twoDArray.length; row++){
for(col=0; col < twoDArray[row].length; col++){
twoDArray[row][col] = counter++;
}
}
for(int row=0; row<twoDArray.length; row++){
System.out.print();
for (int col=0; col<twoDArray[row].length; col++){
System.out.print(twoDArray[row].length; col++){
}
}
}
}
Output-> 0 1
Output-> 2 3 4
Loop through an array:-
You can loop through the array elements with the for loop and use length property to specify how many times the loop should run. It’s better to use length property to specify the number of times you want the loop to be in the action as it makes it readable and simple for the other user too.
String [] cars = {“Volvo”, “ford”, “bbt”, “bmw”};
For (int i=0; i<cars.length; i++) {
System.out.print(cars[i]); }
Output-> Volvo ford bbt bmw
We can also use for-each loop here like this,
String [] cars = {“volvo”, “ford”, “bbt”, “bmw”};
For( string I : cars) {
System.out.print(i);
}
Nested Loop:
Nested loop means a loop statement inside another loop statement. This is the reason nested loops are also known as loop inside loop. It is a simple algorithm that joins two sets by using two nested loops.
Syntax>>
for(initialization; condition; increment/decrement){ // inner loop
for (initialization; condition; increment/decrement){ // outer loop
}
}
public static void main(string [] args) {
int [][] myValues = {{ 1,2,3,4 }, {5,6,7}};
for(int i =0; i<myValues.length; i++){
for(int j=0; j<myValues; j++){
system.out.print(myValues[i][j]);
}
}
Advantages of array:
- Used to represent multiple data items of similar type using one name.
- It allocates memory in adjacent memory locations for all its elements.
- We can access elements of an array by using index number.
- Arrays are fast as compared to other primitive data types.
Disadvantages of array:
- Once declared, the size of the array cannot be changed and allocated memory also can’t be modified.
- The number of elements to be stored or fed in an array must be defined before.
- The operation of insertion and deletion is a bit tricky in an array as the elements are stored in successive memory locations and the shifting operation is difficult.
- In array, memory wastages can be more.
- While adding or removing items in the middle of the array affects the performance of the array.
Java Arraylist:-
Arraylist is also known as a resizable array, which can be found in the java util package. It provides us with dynamic arrays in java. Although it might be slower than the basic arrays, many manipulations can be done in the array as needed which can be very helpful in programs. We can also add and remove elements from an array list whenever we want.
Syntax🡪
import java.util.Arraylist;
Arraylist<string> cookies= new Arraylist<string>();
>>To add items in arraylist we have to use add () method such as,
import java.util.Arraylist;
public class Myclass{
public static void main(string[] args){
Arraylist<string> cookies= new Arraylist<string>();
cookies.add(“sun feast”);
cookies.add(“marie lite”);
cookies.add(“fab”);
System.out.print(cookies);
}
}
Output-> [sun feast, marie lite, fab]
>> To access an item we use get() method and refer to the index no. to access an item.
cookies.get(0);
Output-> sun feast
>> To change an item we use set() method and refer to the index no. to change the item. After adding the last element.
cookies.set(0, “good day”);
System.out.print(cookies);
Output-> [good day, marie lite, fab]
>> To remove an item we use remove() method and refer to the index no. to remove an item. And to remove all the elements we have to use the clear() method after adding the last element.
cookies.remove(1); System.out.print(cookies);
Output-> [good day, fab]
Loop through an Arraylist:-
Loop through the element of an arraylist with a for loop, and use size( ) method to specify the number of times the loop will iterate. Otherwise the looping is the same as that in the standard array.
for (int i=0; i<cookies.size(); i++) {
system.out.print(cookies.get(i));
}
Output-> good day, marie lite, fab
>>Sort an arraylist
Another useful class of the java.util package is collection class, which include sort() method for sorting list alphabetically or numerically.
import java.util.Arraylist;
import java.util.collection;
public class Myclass{
public static void main(string[] args){
Arraylist<string> cookies = new Arraylist<string>();
cookies.add(“ snacks”);
Collection.sort(cookies);
for(string i : cookies){
system.out.print(i);
}
}
}
Advantages of Arraylist:-
- Arraylist don’t have a definite memory allocation like standard arrays when they are declared, they can be appended upon runtime.
- The insertion, searching and deletion of arraylist are stronger than normal arrays.
- Size of the arraylist is not fixed.
Disadvantage of Arraylist:-
- Arraylist only supports object entries, not the primitive data types.
Difference between Array and Arraylist :-
ARRAY | ARRAYLIST |
Size must be defined at the time of declaration. | Size can be dynamically changed. |
Arrays are not type parameterized. | Arraylists are type parameterized. |
Arrays can contain primitive data types as well as objects. Cannot contains values of different data types. | Arraylists can contain only objects, no primitive data types are allowed. Can contain values of different data types. |
This keyword in java:-
We can use java this keyword in many ways; it’s actually a reference variable that refers to the current objects. This keyword tells us about the behaviour and state of an object or instance related to the class. This keyword refers to the current instance/object in a method or constructor. It’s most common use is to discard the confusion between class attributes and parameters with the same name i.e. if we are working with constructor overloading, we might have to invoke one constructor from another constructor. In such a case, we cannot call the constructor explicitly and here we must have to use this() keyword.
>> Some uses of java this keyword are as follows:
- This() can be used to invoke the current class constructor.
- This can be used to return the current class object/instance from the function/method
- This can be used to refer to the current class object variable.
- It can also be passed as an argument in the function/method call.
- This can be used to invoke current class method (implicitly).
>>Using This() to invoke current class constructor:
Class Abc
{
int p;
int q;
Abc(){
this(8, 10);
System.out.prinln(“ Inside default constructor\n”);
}
Abc (int p, int q);
{
this.p = p;
this.q = q;
System.out.println(“Inside parameterized constructor”);
}
Public static void main(string[] args)
{
Abc object = new Abc();
}
}
Output-> Inside parameterized constructor
Output-> Inside default constructor
>> Using ‘this’ keyword to return the current class instance:
class Abc
{
int p;
int q;
Abc()
{
p = 8;
q = 10;
}
Abc get()
{
return this;
}
void display()
{
System.out.println(“p = “ + p + “ q = “ + q);
}
public static void main(string[] args)
{
Abc object = new Abc();
Object.get().display();
}
}
Output-> p=8 q = 10
>> Using ‘this’ to invoke current class method:
If we don’t use this keyword, the compiler automatically adds this keyword while invoking the method.
class Me{
void k(){System.out.println(“hi k”);
}
Void h(){
System.out.println(“hey h”);
this.k();
}
}
class Test{
public static void main(string[]args){
Me m = new Me();
Me.h();
}
}
Output-> hey k
Output-> hi k
>> Using ‘this’ to pass as argument in the constructor call.
We can also pass this keyword in the constructor as well. We can take use of it even if we have to use one object in several classes.
class A{
B1 obj;
A(B4 obj){
this.obj = obj;
}
void display(){
System.out.print(obj.data);
}
}
class B1{
int data = 4;
B1(){
A a=new A(this);
a.display();
}
Public static void main(string[] args){
B1 b = new B1();
}
}
Output-> 4
>>Using ‘this’ keyword that you return as a statement from the function
class M{
M getM(){
Return this;
}
Void msg(){System.out.println(“Hello java”);
}
}
Class Test1{
Public static void main(string[] args){
newM().getM().msg();
}
}
Output-> hello java
Conclusion:-
Array— They are one of the core concepts in java. It would be a hike in your coding efficiency and great achievement if you are an expert in handling arrays and string. Arrays are not so complicated to understand, one just needs to remember some core concepts and some hands-on practice to stick it in mind. Once you grab it with full focus then you will never forget array implementation.
Arraylist— The arraylist class is very powerful as it minimizes the headache of the program developer, as you add data, objects of this class just expand automatically and in an efficient manner. The auto expansion helps to avoid issues such as exceeding the boundary of an array. But at the same time it has some issues regarding the efficiency as memory can be allocated behind the scenes. But compared to a standard array it has lots of advantages which I have already mentioned in the article above.
This keyword— this keyword in java is very helpful in getting the reference of the current instance/object. It is useful in accessing object attributes in case of variables. We can use it many numerous ways i.e. to call the current class constructors. It is mostly used to avoid the confusion between a class attribute and a parameter. But we cannot use this keyword in a static method and in a static initialization block even though we are referring to static members.