Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Data Types and Array in Java

Here in this article we are going to learn about data types and array that we use in our java programming.

DataTypes:

Concept of programming is incomplete without data types. Data types help the programming language deal with variable, methods & classes. Data types indicate which type of variable or any other method or object is going to be handled and how much memory this will occupy.

Java is an object oriented programming language and java is incomplete without data types. Java has rich set of data types. There are some basic (primitives) data types which are defined in Java. A data type specifies the size & the type of value that we are going to store in an identifier. Using different kind of data types you can handle your application to store different values to supportrequirement.

Data types in java categorized in two different ways:

  1. Primitive data types:-(Ccharacter, integer, boolean, and floating point)
  2. Non-primitive: (classes,arrays, and interfaces)

Primitive Data Types:

Java has the following primary data types.

1. Integer

Integer can store any number whether number is negative or positive. It is used to hold only numeric values. We cannot store any character or symbol in integer type.

Example:

int variable1=18;

Or

int variable2=-11;

Above both declarations of the variable are valid.

Different data types have different storing capacity. The size of value depends on its type which is given below.

Type

Size

Range

Byte

1byte

-128 to 127

Short

2bytes

-32768 to 32767

Int

4bytes

-2,147,483,648 to 2,147,483,647

Long

8bytes

-9,223,372,036,854,775,808 to
9,223,372,036,854,755,807

Table 1: Description of Integer Data types and their Size.

Above table shows various kinds of data types that are used for storing numeric values. All above listed data types have their own storage capacity. Smallest data type we seen in above table is byte which stores only 1 byte.

2. Floating Point

Floating point data type is another form of primitive data types.

This data type used to represent the fraction part of the number. We can store numeric values with fraction part that’s not possible in integer type. There are two subtypes of floating points.

Type

Size

Range

Float

4bytes

3.4e−038 to 3.4e+038

Double

8bytes

1.7e−308 to 1.7e+038

Table 2: Describe Floating Point Data Types with Their Values.

3. Character

We can also store character values in java not only numeric. For storing character value java provide Character type. It’s a primitive data type. It stores the character constant in to the memory. It will occupy 2 bytes but it can allow only 1 character.

4. Boolean

These data types are used to store values with two states: true or false which indicate 0 for false or 1 for true.

You can use these data types to construct array and build own class type. This are the variety of data types to store different kinds of value in java.

Variables :

Variables in java mean Identifier. It is defined by the combination of data types, identifier & initialization. You can give them the scope. Scope means visibility through some block & its life time. We can give name for storing particular data.

It can be local variable means it can be used unless the given block is over.

You can declare global variable,which can be used in whole program at any scope.

When variable scope is over then automatically it is destroyed by using garbage collector.

In java you can declare variables as below.

Syntax:

Data Type identifiername; // only creation of variable.

OR

Data type identifiername = value; // variable creation and initialization.

Here, Data Type is your datatype in which type of data you want to store.

Identifier can be anything from A-Z,a-z or underscore,it’s your variable name it must need to be unique.

Value is the variable initialization. It is not compulsory to use. You can give at declare time or not as required your application.

There are some rules to create Variable.

  1. Variable name must not start with a number. If you provide variable name with starting letter as number then it will show you error at compile time.
  2. First letter must need to be either from A-Z or a-z or an underscore.
  3. Any keyword that java has or we can say any java reserved word not allowed as a variable name.
  4. Your variable name must need to be unique. One variable name with different type of data type is not allowed.

So these are the common rules that we should have to keep in mind during declaring variable in java.

Example of Data Types and Variable is given below.

Listing 1: DataTypesAndvariableExample.java

  public class DataTypesAndvariableExample 
  {
  public static void main (String[] args) 
  {
      System.out.println("This Example Demostrate the Use Of Data types and Variable..");
                                
      intintegerTypeVariable;
       // here we define Integer variable without initializing it.
                                 
      floatfloatTypeVariable = 25.25f; 
      // here we define float type variable with initializing value 25.25.
                                 
      double  doubleTypeVariable= 1258.152f; 
      // we create and initialize double type of variable..
                                 
      charcharTypeVariable; 
       // we only create character type variable not initialized it.
                                 
       integerTypeVariable= 10; 
       // initializing integer type variable with value 10..
       charTypeVariable= 'J'; 
       // Initializing Character type variable with value Z..
                                 
       System.out.println("\n\t Value Of Integer Type Variable is:-  "+ integerTypeVariable);
                                 
                                 
      System.out.println("\n\t Value Of Character Type Variable is:-  "+ charTypeVariable);
                                 
                                 
      System.out.println("\n\t Value Of Floating Type Variable is:-  "+ floatTypeVariable);
                                 
                                 
      System.out.println("\n\t Value Of Double Type Variable is:-  "+ doubleTypeVariable);
                                 
                                 
      System.out.println("\n\t Bit Size of Different Data Types ...");
                                 
                                 
       System.out.println("\n\t Size of Integer is:-  "+ Integer.SIZE);
                                  
                                 
       System.out.println("\n\t Size of Character is:-  "+ Character.SIZE);
                                 
                                 
       System.out.println("\n\t Size of Floating is:-  "+ Float.SIZE);
                                 
                                 
       System.out.println("\n\t Size of Double is:-  "+ Double.SIZE);
                                                 
    }
  }

Output Listing 1: DataTypesAndvariableExample

This Example Demostrate the Use Of Data types and Variable..

Value Of Integer Type Variable is:- 10

Value Of Character Type Variable is:- J

Value Of Floating Type Variable is:- 25.25

Value Of Double Type Variable is:- 1258.1519775390625

Size of Different Data Types ...

Size of Integer is:- 32

Size of Character is:- 16

Size of Floating is:- 32

Size of Double is:- 64

Type Conversion and Type Casting in Data type:

In java we can assign one type of value to another type of variable. If both variables’ types are compatible or we can say both variable have similarity in data type then java automatically convert one type of variable into the another type.This concept is commonly known as type conversion. For an example it is possible in java to assign integer type of value to long type variable or floating type variable. But there are some situations where both variable types are not compatible and at that time java will not automatically convert one type of variable to the another one. But instead of automatic conversion we can convert one type of variable to the other compatible type manually. The manually conversion of one type to another type is known as Type Casting. It is also known as explicit conversion.

Type Conversion:

Type conversion is possible in java if following conditions are satisfied.

  1. Both variables type need to be compatible.
  2. Source type variable size is needed to be smaller than the destination variable type.

If this condition satisfied then type conversion takes place. Type conversion is also known as widening conversion. Java cannot perform automatic conversion between numeric type and char and Boolean type. And Boolean type and character type are not compatible.

If above listed condition is not satisfied then there is need to converting type manually.

Type Casting:

We can perform conversion of type manually if variable type is not compatible.

We would not assign integer type value to byte automatically as it does not satisfy the condition. But we can do this by using manually converting type. This type of conversion is also known as narrowing conversion.

Syntax:

(target-type)yourValue;

Here target type is the type of variable that you want to store.

Example Of Type casting and Type Conversion is given below.

Listing 1:TypeCastAndConversionExample.java

  public class TypeCastAndConversionExample
  {
   
     public static void main (String[] args) 
      {
           intintegerVariable=10; // integer variable with initial value 10..
                                 
           floatfloatVariable=25.5f; // float variable with initial value 25.5..
                                 
           bytebyteVariable; // byte variable without initialization...
                                 
           System.out.println("\n\t Automatic Type Conversion..");
                                 
            floatVariable=integerVariable; // here floatvariable size is larger than integer so java will make automatic type conversion..
                                 
            System.out.println("\n\t Float Variable after Automatic type conversion..:- " + floatVariable);
                                 
                                 
            System.out.println("\n\t Manually Type casting Of integer to byte..");
                                 
            byteVariable=(byte)integerVariable; // here we manualy casting. as both variable is not compitible... we use (byte) to cast it into byte.
                                 
                                 
             System.out.println("\n\t Byte Variable after Manually Type Casting..:- " + byteVariable);
   }
}

Output Listing 1: TypeCastAndConversionExample.java

Automatic Type Conversion..

Float Variable after Automatic type conversion..:- 10.0

Manually Type casting Of integer to byte..

Byte Variable after Manually Type Casting..:- 10

In the above example we saw the automatic type conversion and manually type casting of two variables. This example simply demonstrates how to perform manually type casting if its required in our programming.

Array:

Array is one type of variable which store multiple value with same data type. It has many dimensions such as one dimension, two dimension, or multidimensional. Array is non-primitive data type.

One Dimensional Array:

It is simple form of an array, which list the value of same type. All rules of variable also assign to array because it is one type of variable. So you must have to declare array before use with its data type. The general form to declare Array is.

Datatypearray_variable_name[ ];

Here data type can be any data type upon which we want to store values. You can use any of them as per your application’s requirement.

Example:

intarray_variable_name[ ];

Here we declare array of integer type. You can define it just like this. Here the size of array is null. It means the array has no value.

To allocate any size to your array to store the value you have to use new keyword, which is the operator of Java. new operator allocates memory to the variable or any object or instance of class.

Variable_array_name = new Datatype[size];

Here you can define size within the square brackets.

Same data types you can use as you’re required.

Size must be defined using int (integer) whatever data type you are using for the array elements. .

Example of Declare Different Kind of Array in java:

intintArry[]; // to create an integer type of array.

Or

int [] intArry;

charcharArry[]; // to create character type array.

or

char [] charArry;

longlngArry[]; // to create long type array.

or

long [] lngArry;

String strArray[]; // To create String type of array.

Or

String [] strArray;

You can dynamic allocate the memory or you can also allocate the memory at declaration time.

Array_variable[0]=18;

Array_variable[1]=11;

Array_variable[2]=19;

Array_variable[3]=28;

Like this you can declare array by using its index in between square brackets. So that Compiler knows that which value is contained in which position. In bracket you specify index position.

We understand two step of array declaration, first array declare with data type and then using new keyword, defining its type. Here we can also specify the size of an array during the declaration time .

intarray_Variable = new int[10];

here we create array_variable of integer type with size of 10.

As we know Array is a one type of variable, so you can initialize at declaration time. You can declare its value within the curly braces and by comma separated. Here there is no need to use new key word because it automatically takes the size of array.

Example:

intarray_variable_of_integer = {19,18,11,17,9,29,21,24};

Same as index starts with 0, 1st element starts with 0 index. So here position of value 19 in array is 0(zero).

You must have to access the array and its value between the given size and its range. If you go out of the range of an array then Java will throw one run time exception that is ArrayIndexOutOfBounds and your program will terminate.

Example of Simple array is given below.

Listing 2: SimpleExampleOfArray.java

  public class SimpleExampleOfArray
  {
   
  public static void main(String[] args) 
      {
  double [] dblArry=new double []{200,500,300,700,800,900,1000};
  double [] dblArry1={200,500,300,700,800,900,1000};
   
  for(int i=0;i<7;i++)
          {
                 System.out.println("dblArry : " + i +" :"+dblArry[i]);
                 System.out.println("dblArry : " + i +" :"+dblArry1[i]);
          }
      }
  }

Output Listing 2: SimpleExampleOfArray.java

dblArry : 0 :200.0

dblArry : 0 :200.0

dblArry : 1 :500.0

dblArry : 1 :500.0

dblArry : 2 :300.0

dblArry : 2 :300.0

dblArry : 3 :700.0

dblArry : 3 :700.0

dblArry : 4 :800.0

dblArry : 4 :800.0

dblArry : 5 :900.0

dblArry : 5 :900.0

dblArry : 6 :1000.0

dblArry : 6 :1000.0

Multidimensional Array

Multidimensional array displays the value of array in the form of rows and columns. Just like table.

In which you have to specified the size of both row as well as column at declaration time. It is also known as an array of array.

Examples:

int[][]multidimension_array_variable = new int[2][3]

Here we declare variable multidimension_array_variable with specifying rows and columns. In the above example first index is 2 that shows row of an array and another one is column that is 3. So array created by this syntax has 2 rows and 3 columns.

Below is the way that multidimention array has.

0 1 2

3 4 5

àin which positon of 0 is [0][0]

Same as,

multidimention_array_variable[0][1]=1;

multidimention_array_variable[0][2]=2;

multidimention_array_variable[1][0]=3;

multidimention_array_variable[1][1]=4;

multidimention_array_variable[1][2]=5;

In this manner data value will be stored in multidimension array.

Example of Multidimension array is given Below.

Listing 3: SimpleExampleOfMultiDimensionArray.java

  public class SimpleExampleOfMultiDimensionArray
  {
    public static void main(String[] args) 
     {
        String[][] names = 
         {
            {"BajraRotla", "wheat Rotli", "Nan"},
            {"with butter", "Withoht Butter"}
          };
          System.out.println(names[0][0] + "  " + names[1][0]);
          System.out.println(names[0][2] + "  " + names[1][1]);
     }
  }

Output Listing 3:SimpleExampleOfMultiDimensionArray.java

BajraRotla with butter

Nan Withoht Butter

This example demonstrates the use of multi-dimensional array to store value in multiple forms.

We can directly assign one array variable to the other one. Java provides built-in method to do this type of work.

Example of copying one array variable to another without using arraycopy() method.

Listing 4: SimpleExampleOfArray.java

/* In this example we copy one array to another array. It is primitive type of array.
   * Directly assigning the one variable to the another variable.
   */
  public class SimpleExampleOfArray
  {      
  publicSimpleExampleOfArray() {             }
   
  public static void main(String[] args) 
   {
      intfirstArray[]=new int[]{20,30,40,50,60,70,80};
      intsecondArray[];
                 
       // Simple assigning the variable to the another variable.
       secondArray=firstArray;
                 
       System.out.println(" : Copy int Type of Value :");
       System.out.println("---------------------------\n");
       for(int i=0;i<firstArray.length;i++)
       {
          System.out.println("first Array Value is : "+i+":"+firstArray[i]);
          System.out.println("second Array Value is : "+i+":"+secondArray[i]);
       }
                 
       char[] chrFirstArray = new char[]{ 'G', 'o', 'o', 'D', 'M', 'O', 'o',
                                                     'r', 'n', 'i', 'n', 'g', '.','!','!' };
                                                                
       char[] chrSecondArray;
   
       // Simple assigning the variable to the another variable.
      chrSecondArray=chrFirstArray;
      System.out.println("\n\n : Copy char Type of Value :");
      System.out.println("---------------------------\n");
      System.out.println("Value of Array First is  :" + chrFirstArray) ;
      System.out.println("Value of Array First is  :" + chrSecondArray);
    
   }    
}

Output Listing 4: SimpleExampleOfArray.java

: Copy int Type of Value :

---------------------------

first Array Value is : 0:20

second Array Value is : 0:20

first Array Value is : 1:30

second Array Value is : 1:30

first Array Value is : 2:40

second Array Value is : 2:40

first Array Value is : 3:50

second Array Value is : 3:50

first Array Value is : 4:60

second Array Value is : 4:60

first Array Value is : 5:70

second Array Value is : 5:70

first Array Value is : 6:80

second Array Value is : 6:80

: Copy char Type of Value :

---------------------------

Value of Array First is :GooDMOorning.!!

Value of Array First is :GooDMOorning.!!

This example demonstrates how to copy one array from another using simple assigning.

Copy one array from another array using the method arraycopy() of System class.

arraycopy() Method :

arraycopy() is the method of final Class System. arraycopy() method is static method so we can directly call arraycopy() method by using class name System.return type of arraycopy() method is void. Syntax of this method is given below.

Syntax:

public staticvoidarraycopy(Object src,intsrcPos, Objectdest,intdestPos,intlength);

Here src is a Source object from which array we want to copy. srcPos is the position where to start a copy from source. dest is the destination of array where it is copy. destPosition is the position of the destination array. Length is the total number of value we want to copy.

Example of arraycopy() method is given below.

Listing 5: SimpleExampleOfArray.java

  public class SimpleExampleOfArray
  {
   
  publicSimpleExampleOfArray() {      }
   
  public static void main(String[] args) 
      {
              intfirstArray[]=new int[]{20,30,40,50,60,70,80};
              intsecondArray[]=new int[3];
              
              // Simple assigning the variable to the another variable.
              System.arraycopy(firstArray,3,secondArray,0,3);
              
              System.out.println(" : Copy int Type of Value :");
              System.out.println("---------------------------\n");
              System.out.println("first Array Value is : ");
              for(int i=0;i<firstArray.length;i++)
              {
                         System.out.print(" "+firstArray[i]);
              }
              
              System.out.println("\n\nSecond Array Value is : ");
              
              for(int i=0;i<secondArray.length;i++)
              {
                         System.out.print(" "+firstArray[i]);
              }
              
          char[] chrFirstArray = new char[]{ 'G', 'o', 'o', 'D', 'M', 'O', 'o',
                                         'r', 'n', 'i', 'n', 'g', '.','!','!' };
                                     
                         
  char[] chrSecondArray=new char[20];
   
          // Simple assigning the variable to the another variable.
  System.arraycopy(chrFirstArray,4,chrSecondArray,0,5);
   
  System.out.println("\n : Copy char Type of Value :");
              System.out.println("---------------------------\n");
  System.out.println("Value of Array First is  :" + new  String(chrFirstArray)) ;
  System.out.println("Value of Array First is  :" + new String(chrSecondArray));
   
      }    
  }

Output Listing 5: SimpleExampleOfArray.java

: Copy int Type of Value :

---------------------------

first Array Value is :

20 30 40 50 60 70 80

Second Array Value is :

20 30 40

: Copy char Type of Value :

---------------------------

Value of Array First is :GooDMOorning.!!

Value of Array First is :MOorn

Above example demonstrates the use of arraycopy() method of System class to copy one array to another one.

Conclusion

Here in this tutorial we learned about data types and array. We also got the idea how to use array in our programming. We learn type conversion and type casting of data type. We examine arraycopy() method of array to understand arrays.



Computer system engineer who has 4 year of experience in the field our web-development ,FPGA, and java programming.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login