Java/Data Types Variables and Arrays

From Meshplex

Jump to: navigation, search
Image:Java_programming.jpg
Introduction to Java
Overview of Java
How to Setup Java on your PC
Java Data Types, Variables,and Arrays
Operators
Java Packages, Classes, and Interfaces
Java Program
Java Modifiers
Java Control Statements
Java Exception Handling
Java Object Oriented Programming
Java Wrappers
Java Strings
Java Math
Java Arrays
Java Random Numbers
Java Date and Time
Java Regular Expressions
Java Java Collections
Java Generics
Java Thread and Multithreading
Java IO and file Handling
Java Network Programming
Java RMI
Java Image, Audio, Video
Java GUI
Java Applets
Java Internationalization
Java JDBC
Java and XML

Contents

[edit] Java Data Types

Java is termed as strongly typed Programming which means that every variable which is defined in any line code of java programming has to be properly well defined and assigned a data type and this again makes it possible for java to maintain such complex robustness and security to the code and the data.

If we broadly categorize and classify these data types we can define them as Eight primitive types of data types available to us in Java.

1. Four of them are integer types

2. Two are floating-point number types

3. One is the character type char, used for code units in the Unicode encoding scheme

4. One is a Boolean type for truth values .

In most situations, the int type is the most practical. If you want to represent the number of inhabitants of our planet, you'll need to resort to a long. The byte and short types are mainly intended for specialized applications, such as low-level file handling, or for large arrays when storage space is at a premium.

Let’s take these four categories in brief for our better understanding

[edit] Java Integers

Intergers can be defined as byte, short, int, and long, which are for whole- Valued signed numbers.

The int type is the most practical. If you want to represent the number of humans on earth you'll need to resort to a long. The byte and short types are mainly intended for specialized applications.

Image:Integer.jpg

[edit] Java Floating Point Numbers

Floating-point numbers basically is used when we have the situation of getting our result or output in the form of decimals and not whole numbers as mentioned in case of Integers Data Types. This group thus includes float and double.

Image:Float.jpg

[edit] Java Characters

Characters help defining the char, which represents symbols in a character Set, like letters and numbers.

Image:Escape_sequence.jpg

[edit] Java Boolean

Boolean data type is used to mention the variables which will only have the possibility of containing values either as True or False.


[edit] Java Variable

The variable is the basic unit of storage in a Java program. You declare a variable by placing the type first, followed by the name of the variable. Here are some examples:

double salary;

double _salary;

int holidays;

int $holidays;

long distanceFromMoonToEart;

boolean done;

Notice the semicolon at the end of each declaration. The semicolon is necessary because a declaration is a complete Java statement. In addition, all variables have a scope, which defines their visibility, and a lifetime. General form of declaring variables:


type identifier [ = value][, identifier [= value] ...] ;

Where type identifier could be byte, int, long, boolean, char, short, float, double. Variable name cannot start with numeric character or special characters except "$" and "_". For valid example please refer above variable names. Let us also see some invalid variable names:

double 1salary;      // invalid variable name

double %salary;      // invalid variable name

int #holidays;       // invalid variable name

After you declare a variable, you must explicitly initialize it by means of an assignment statement—you can never use the values of uninitialized variables. For example, the Java compiler flags the following sequence of statements as an error.

byte z = 22;

Although the preceding examples have used only constants as initializers, Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared.


float a = 10.0f

float b = 3.4f

float i = a / b;


[edit] JavaScope & Lifetime of Variables

Lifetime of a variable, that is, the time a variable is accessible during the execution, is determined by the context in which it is declared. We distinguish between lifetime of variables in three contexts:

Instance variables - members of a class and created for each object of the class. Every object of the class will have its own copies of these variables, which are local to the object. The values of these variables at any given time constitue the state of the object. Instance variables exist as long as the object they belong to exists.

Static variables - also members of a class, but not created for any object of the class and, therefore, belong only to the class. They are not associated with any object. They are created when the class is loaded at runtime, and exist as long as the class exists. Every object derived from the class will share static variables. In a multithreaded application static variables are discouraged because of their feature.

Local variable - declared in methods and in blocks and created for each execution of the method or block. After the execution of the method or block completes local variables are no longer accessible. Local variable should be initialized within the methods and blocks where they are created. Not doing so will cause java compilation error.


[edit] Java Arrays

An array is a data structure that defines an indexed collection of a fixed number of homogeneous data elements. In java arrays are objects that store multiple variables of the same type. Arrays can hold either primitives or object references, but the array itself will always be an object on the heap, even if the array is declared to hold primitive elements. A position in the array is indicated by a non negative integer value called index. An element at a given positionn in the array is accessed using the index. The size of an array is fixed and cannot be increased to accommodate more elements.


[edit] Declaring a Java Array

Arrays are declared by stating the type of elements the array will hold, which can be an object or primitive followed by square brackets to the left or right of the identifier.


<element type>[] <array name>;

or 

<element type> <array name>[];


Arrays can be single dimensional, two dimensional or multidimensional. Declaring a single dimensional array is very simple. The most common way to construct an array is to use the new keyword that allocates memory to any object. Remember arrays are treated as objects in Java. The following is an example of constructing a single dimensional array of type long:

long[] empSalaries = new long[10];

As you can see that the above statement will allocate memory to the array variable empSalaries and the size of the array would be 10. In java index begin from 0. That means in order to access the first element of an array you need to do something like

empSalaries[0];

public SingleDimensionalArray {
 
  long[] empSalaries = new long[] {10000, 20000, 30000, 40000};
 
  public static void main(String[] args) {
 
    System.out.println("Value of the first element in the array: " + empSalaries[0];
 
  }
 
}

An array can be initialized in many ways:

1) long[] empSalaries = {10000L, 20000L, 30000L, 40000L};

 // L means long value. It is required to distinguish between integer value and 
 // long value. By default it is integer always.

2) long[] empSalaries = new long[] {10000L, 20000L, 30000L, 40000L};

3) long[] empSalaries = new long[4];
   empSalaries[0] = 10000L;
   empSalaries[1] = 20000L;
   empSalaries[2] = 30000L;
   empSalaries[4] = 40000L;


Let us check out some invalid array declarations


String names[] = new String[];  // We have to mention the size of 
                                // the array when using new operator.

int ars[] = new int{1,2,3,4,5}; // square([]) brackets are missing.


int ars[] = new int[5]{1,2,3,4,5}; // size of the array should not be mentioned
                                   // when declaring an array like this.

int ars[4]; // it is invalid because memory can be
               allocated only using new operator.

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

[edit] Java Multidimensional Array

In Java multidimensional arrays are actually arrays of arrays. These as you might expect, look and act like regular multidimensional arrays. Multidimensional arrays use more than one index to access array elements. They are used for tables and other more complex arrangements. Let us take an example of two dimensional array which is a form of multidimensional array.

int matrix = new int[3][2];

This very much resembles to a 3 x 2 matrix. Where 3 represents rows and 2 represents columns.

Valid array declarations


Integer ars[][] = new Integer[4][3];  // Integer is a wrapper class for int.

int ars[][] = new int[][]{{1,2,3}, {2,4,6}, {3,4,7}, {5,6,7}};

It will be like a 4 x 3 matrix
 _        _
|  1  2  3 |
|  2  4  6 |
|  3  4  7 |
|  5  6  7 |
+-        -+ 

[edit] Iterate through a Java Multidimensional Array

public class MultiDimensionalArrayExample {
 
  public static void main(String[] args) {
 
    int ars[][] = new int[][]{{1,2,3}, {2,4,6}, {3,4,7}, {5,6,7}};
 
    for(int i = 0; i < 4; i++) {
      for(int j = 0; j < 3; j++) {
        System.out.println(ars[i][j]);
      }
    }
  }
}

Previous Next