Java Basics – Arrays, ways to create objects, command line argument

Java Arrays

Generally, an array is a collection of the same type of elements that has a contiguous memory location. Java arrays are objects which contain the elements of similar data types. Moreover, all the elements of the array are stored in a contiguous memory location. In short, the array is a data structure where the programmers can store similar elements. However, we can only store a fixed set of elements in the array. These arrays are index-based so the first element of an array is always stored at the 0th index; the second element is stored on the first index and so on.

With the help of the length member, we can always get the length of the array. It is not the same with languages like C or C++. There we need to use the size of the operator. We can call arrays in Java as the object of a dynamically generated class. They inherit the object class and then implement the serializable and cloneable interfaces. We can store primitive values as well as objects in the array. In Java programming language, there are two types of arrays. One is a single-dimensional array and another is a multidimensional array.

Single Dimensional Array

Its syntax is –

dataType[] arr; (or)

dataType []arr; (or)

dataType arr[];

For instantiation –

arrayRefVar=new datatype[size];

Example is given below –

class Testarray{

public static void main(String args[]){

int a[]=new int[5];//declaration and instantiation

a[0]=10;//initialization

a[1]=20;

a[2]=70;

a[3]=40;

a[4]=50;

//traversing array

for(int i=0;i<a.length;i++)//length is the property of array

System.out.println(a[i]);

}}

Output –

10, 20, 30, 40, 50

Multidimensional Array

In this kind of arrays, the data is stored in the form of rows and columns that are based on index and are also known as matrix form arrays. Its syntax is –

dataType[][] arrayRefVar; (or)

dataType [][]arrayRefVar; (or)

dataType arrayRefVar[][]; (or)

dataType []arrayRefVar[];

For instantiating –

int[][] arr=new int[3][3];//3 row and 3 column

Example of a multidimensional array –

class Testarray3{

public static void main(String args[]){

//declaring and initializing 2D array

int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array

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

for(int j=0;j<3;j++){

System.out.print(arr[i][j]+” “);

}

System.out.println();

}

}}

Output –

1 2 3

2 4 5

4 4 5

Ways to create objects in Java

In Java, objects are a physical and logical entity. However, in Java class is always a logical entity only. Objects have three characteristics. First is the state that represents the data or value of the object, second is its behavior that represents the functionality of the object and last is the Identity that is implemented through a unique ID. There are five ways to create an object in Java they are as follows –

Java New Operator

This is a famous way to create a develop an object in Java. a new operator is followed by a call to a constructor that initializes that new object. It takes all the space in the heap while we are creating an object. Its Syntax is –

class_name object_name = new class_name()

Example-

public class A

{

String str=”hello”;

public static void main(String args[])

{

A obj=new A();  //creating object using new keyword

System.out.println(obj.str);

}

}

Output –

hello

Java Class.newInstance() method

This is the method of Class class. The Class class belongs to java.lang package. It has the responsibility of creating a new instance of a class that is represented by this Class object. After that, it returns the newly created instance of a particular class. Its Syntax is –

public T newInstance() throws IllegalAcccessException, InstantiationException

It throws an IllegalAccessException if the nullary constructor or the class is not accessible. It throws InstantiationException also if the class is representing an abstract class, array class, primitive type, or an interface.

Example –

public class NewInstanceExample

{

String str=”hello”;

public static void main(String args[])

{

try

{

//creating object of class

NewInstanceExample obj= NewInstanceExample.class.newInstance();

System.out.println(obj.str);

}

catch(Exception e)

{

e.printStackTrace();

}

}

}

Output –

Java NewInstanceExample

hello

Java newInstance() method of constructor

The Java constructor class has a method called newInstance() that is similar to the newInstance() method of the Class class. This method belongs to Java.lang.reflect.Constructor class. Both methods reflect two ways of creating an object. As a matter of fact, the Class class’s newInstance() method uses the method newInstance() of the constructor class. This method then returns a new object that is created by calling the constructor. Its syntax is –

public T newInstance(Objects…initargs)

Example –

import java.lang.reflect.Constructor;

public class NewInstanceExample1

{

String str=”hello”;

public static void main(String args[])

{

try

{

Constructor<NewInstanceExample1> obj =NewInstanceExample1.class.getConstructor();

NewInstanceExample1 obj1 = obj.newInstance();

System.out.println(obj1.str);

}

catch(Exception e)

{

e.printStackTrace();

}

}

}

Output – hello

Java Object.clone() method

The Java clone() method has the responsibility of creating a copy of an existing object. This method is defined in the object class. Then it returns the clone of this instance. Its Syntax is –

protected Object clone() throws CloneNotSupportedException

Example –

public class CloneExample implements Cloneable

{

//creates and returns a copy of this object

protected Object clone() throws CloneNotSupportedException

{

return super.clone();

}

String name = “Microprocessor”;

public static void main(String[] args)

{

CloneExample obj1 = new CloneExample();     //creating object of class

try

{

CloneExample obj2 = (CloneExample) obj1.clone();

System.out.println(obj1.name);

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

Output – Microprocessor

Java Object Serialization and Deserialization

A class should implement a serializable interface that belongs to the Java.io package. It does not have any field or method. They add special behavior to every class. In Java 8, the marker interface is not used.

Object Serialization – We can use the ObjectOutputStream class to serialize an object. It is the process of converting objects into a sequence of bytes. This method accepts objects as a parameter. The signature of the method is –

public final void writeObject(Object obj) throws IOException

Object Deserialization – Deserialization is the process of creating an object from a sequence or series of bytes. The method readObject() reason object from the class ObjectInputStream and then deserializes it. Its method is –

public final Object readObject() throws IOException

Command Line Argument

Jarv’s command-line argument is a kind of argument that is passed at the time of running a Java program. The arguments that are passed from the console can always be received in the Java program and then they can be used as input. Thus, it provides a better way to check the behavior of a program for various values. You can pass as many numbers of the arguments as you want from the command prompt. Let us understand the command-line argument in Java with the help of an example.

In the below example, we are getting only one argument and then printing it. In order to run the Java program, we must pass at least one argument from the command prompt.

class CommandLineExample{

public static void main(String args[]){

System. out.println(“Your first argument is: “+args[0]);

}  }

Output –

Your first argument is: sono

Leave a Comment