0% found this document useful (0 votes)
204 views7 pages

Java Variables and Array Data Types

HTML

Uploaded by

pubcse24th
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
204 views7 pages

Java Variables and Array Data Types

HTML

Uploaded by

pubcse24th
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Variables and Data Types with EXAMPLE

What is a Variable in Java?


Variable in Java is a data container that stores the data values during Java program execution. Every variable is assigned
data type which designates the type and quantity of value it can hold. Variable is a memory location name of the data.
The Java variables have mainly three types : Local, Instance and Static.
In order to use a variable in a program you to need to perform 2 steps
1. Variable Declaration
2. Variable Initialization
In this section, you will learn-
• Variable Declaration
• Variable Initialization
• Types of variables
• Data Types in Java
• Type Conversion & Type Casting
Variable Declaration:
To declare a variable, you must specify the data type & give the variable a unique name.

Examples of other Valid Declarations are


int a,b,c;
float pi;
double d;
char a;
Variable Initialization:
To initialize a variable, you must assign it a valid value.

Example of other Valid Initializations are


pi =3.14f;
do =20.22d;
a=’v’;
You can combine variable declaration and initialization.

Page 1
Example :
int a=2,b=4,c=6;
float pi=3.14f;
double do=20.22d;
char a=’v’;
Types of variables
In Java, there are three types of variables:
1. Local Variables
2. Instance Variables
3. Static Variables
1) Local Variables
Local Variables are a variable that are declared inside the body of a method.
2) Instance Variables
Instance variables are defined without the STATIC keyword .They are defined Outside a method declaration. They are
Object specific and are known as instance variables.
3) Static Variables
Static variables are initialized only once, at the start of the program execution. These variables should be initialized first,
before the initialization of any instance variables.
Example: Types of Variables in Java
class Guru99 {
static int a = 1; //static variable
int data = 99; //instance variable
void method() {
int b = 90; //local variable
}
}
What is Data Types in Java?
Data Types in Java are defined as specifiers that allocate different sizes and types of values that can be stored in the
variable or an identifier. Java has a rich set of data types. Data types in Java can be divided into two parts :
1. Primitive Data Types :- which include integer, character, boolean, and float
2. Non-primitive Data Types :- which include classes, arrays and interfaces.

Page 2
Primitive Data Types
Primitive Data Types are predefined and available within the Java language. Primitive values do not share state with
other primitive values.
There are 8 primitive types: byte, short, int, long, char, float, double, and boolean
Integer data types
byte (1 byte)
short (2 bytes)
int (4 bytes)
long (8 bytes)
Floating Data Type
float (4 bytes)
double (8 bytes)
Textual Data Type
char (2 bytes)
Logical
boolean (1 byte) (true/false)

Java Data Types


Data Type Default Value Default size
byte 0 1 byte
short 0 2 bytes
int 0 4 bytes
long 0L 8 bytes
float 0.0f 4 bytes
double 0.0d 8 bytes
boolean false 1 bit
char ‘\u0000’ 2 bytes
Points to Remember:
• All numeric data types are signed(+/-).
• The size of data types remain the same on all platforms (standardized)
Page 3
• char data type in Java is 2 bytes because it uses UNICODE character set. By virtue of it, Java supports
internationalization. UNICODE is a character set which covers all known scripts and language in the world
Java Variable Type Conversion & Type Casting
A variable of one type can receive the value of another type. Here there are 2 cases –
Case 1) Variable of smaller capacity is be assigned to another variable of bigger capacity.

This process is Automatic, and non-explicit is known as Conversion


Case 2) Variable of larger capacity is be assigned to another variable of smaller capacity

In such cases, you have to explicitly specify the type cast operator. This process is known as Type Casting.
In case, you do not specify a type cast operator; the compiler gives an error. Since this rule is enforced by the compiler,
it makes the programmer aware that the conversion he is about to do may cause some loss in data and prevents accidental
losses.
Example: To Understand Type Casting
Step 1) Copy the following code into an editor.
class Demo {
public static void main(String args[]) {
byte x;
int a = 270;
double b = 128.128;
[Link]("int converted to byte");
x = (byte) a;
[Link]("a and x " + a + " " + x);
[Link]("double converted to int");
a = (int) b;
[Link]("b and a " + b + " " + a);
[Link]("\ndouble converted to byte");
x = (byte)b;
[Link]("b and x " + b + " " + x);
}
}
Step 2) Save, Compile & Run the code.

Output:
int converted to byte
a and x 270 14
double converted to int
b and a 128.128 128
double converted to byte
b and x 128.128 -128

Page 4
What is Java Array?
Java Array is a very common type of data structure which contains all the data values of the same data type. The data
items put in the array are called elements and the first element in the array starts with index zero. Arrays inherit the
object class and implement the serializable and cloneable interfaces. We can store primitive values or objects in an array.
In simple words, it’s a programming construct which helps to replace this
x0=0;
x1=1;
x2=2;
x3=3;
x4=4;
x5=5;
with this …
x[0]=0;
x[1]=1;
x[2]=2;
x[3]=3;
x[4]=4;
x[5]=5;
In this part, you will learn-
• What is an array?
• Array Variables
• First Array Program
• Java Array: Pass by reference
• Multidimensional arrays
how this helps is that a variable can reference the index (the number in the bracket[]) for easy looping.
for(count=0; count<5; count++) {
[Link](x[count]);
}
Array Variables
Using an array in your program is a 3 step process –
1) Declaring your Array
2) Constructing your Array
3) Initialize your Array
1) Declaring your Array
Syntax
<elementType>[] <arrayName>;
or
<elementType> <arrayName>[];
Example:
int intArray[];
// Defines that intArray is an ARRAY variable which will store integer values
int []intArray;
2) Constructing an Array
arrayname = new dataType[]

Page 5
Example:
intArray = new int[10]; // Defines that intArray will store 10 integer values
Declaration and Construction combined
int intArray[] = new int[10];
3) Initialize an Array
intArray[0]=1; // Assigns an integer value 1 to the first element 0 of the array
intArray[1]=2; // Assigns an integer value 2 to the second element 1 of the array
Declaring and initialize an Array
[] = {};
Example:
int intArray[] = {1, 2, 3, 4};
// Initilializes an integer array of length 4 where the first element is 1 , second element is 2 and so on.
First Array Program
Step 1) Copy the following code into an editor.
class ArrayDemo{
public static void main(String args[]){
int array[] = new int[7];
for (int count=0;count<7;count++){
array[count]=count+1;
}
for (int count=0;count<7;count++){
[Link]("array["+count+"] = "+array[count]);
}
//[Link]("Length of Array = "+[Link]);
// array[8] =10;
}
}
Step 2) Save , Compile & Run the code. Observe the Output
Output:
array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4
array[4] = 5
array[5] = 6
array[6] = 7
Step 3) If x is a reference to an array, [Link] will give you the length of the array.
Uncomment line #10. Save, Compile & Run the [Link] the Output
Length of Array = 7
Step 4) Unlike C, Java checks the boundary of an array while accessing an element in it. Java will not allow the
programmer to exceed its boundary.
Uncomment line #11. Save, Compile & Run the [Link] the Output
Exception in thread "main" [Link]: 8
at [Link]([Link])
Command exited with non-zero status 1
Step 5) ArrayIndexOutOfBoundsException is thrown. In case of C, the same code would have shown some garbage
value.

Page 6
Java Array: Pass by reference
Arrays are passed to functions by reference, or as a pointer to the original. This means anything you do to the Array
inside the function affects the original.
Example: To understand Array are passed by reference
Step 1) Copy the following code into an editor
class ArrayDemo {
public static void passByReference(String a[]){
a[0] = "Changed";
}

public static void main(String args[]){


String []b={"Apple","Mango","Orange"};
[Link]("Before Function Call "+b[0]);
[Link](b);
[Link]("After Function Call "+b[0]);
}
}
Step 2) Save, Compile & Run the code. Observe the Output
Output:
Before Function Call Apple
After Function Call Changed
Multidimensional arrays
Multidimensional arrays are actually arrays of arrays.
To declare a multidimensional array variable, specify each additional index using another set of square brackets.
Ex: int twoD[ ][ ] = new int[4][5] ;
When you allocate memory for a multidimensional array, you need only specify the memory for the first (leftmost)
dimension.
You can allocate the remaining dimensions separately.
In Java, array length of each array in a multidimensional array is under your control.
Example
public class Guru99 {
public static void main(String[] args) {

// Create 2-dimensional array.


int[][] twoD = new int[4][4];

// Assign three elements in it.


twoD[0][0] = 1;
twoD[1][1] = 2;
twoD[3][2] = 3;
[Link](twoD[0][0] + " ");
}
}
Output:
1

Page 7

Common questions

Powered by AI

Initializing an array assigns specific values to each element after declaring and constructing the array. Declaration specifies the array's type and name (e.g., 'int[] arr;'), while construction allocates memory for it (e.g., 'arr = new int[5];'). Initialization might look like 'arr[0] = 1;', setting a value at each index. This step is crucial for defining the initial state of an array before usage to avoid unexpected behaviors.

Primitive data types in Java, such as int, char, and double, are predefined by the language and typically represent single values. They have a fixed size and do not share states with other primitive values. Non-primitive data types, such as arrays and classes, are objects that can store multiple values and support methods to operate on them. Unlike primitives, their size is variable, and they can represent complex structures.

Numeric data types in Java being signed means they can represent both positive and negative numbers, which is crucial for arithmetic operations. The consistent size of these data types across platforms ensures that Java programs produce the same results regardless of the underlying hardware architecture, aiding in cross-platform compatibility. This is especially important for global applications where software might run on various systems.

Local variables are defined within a method and are only accessible within that method. Instance variables are declared in a class but outside methods; they are specific to objects and differ between instances. Static variables are class-level variables initialized once and shared among all instances. Use local variables for temporary data, instance variables for data specific to each object, and static variables for shared data across all instances.

In Java, multidimensional arrays are arrays of arrays, allowing for varied lengths at each dimension, providing flexibility in memory allocation. Only the first dimension needs explicit memory allocation with 'new', and subsequent dimensions can be initialized separately. For example, 'int[][] twoD = new int[4][];' sets up a base array of size 4, with each of its elements capable of being a different-sized array. This flexibility helps optimize memory use.

In Java, declaring a variable involves specifying the data type and assigning a unique name to the variable. For instance, 'int a;' declares an integer variable named 'a.' Initializing a variable involves assigning it a valid initial value, such as 'a = 2;'. These steps can be combined into a single statement, such as 'int a = 2;' which declares and initializes 'a' simultaneously.

Arrays in Java are passed to methods by reference, not by value. This means that any modifications made to the array elements within the method are reflected in the original array outside the method. This can lead to unintended side effects if changes are made to the array within a method without the caller's knowledge, as the changes affect the original array.

In Java, type conversion happens automatically when a variable of a smaller capacity is assigned to a variable of a larger capacity, such as assigning an int to a long. This is an implicit process called widening conversion. Type casting is necessary when assigning a variable of larger capacity to one of a smaller capacity, like converting a double to an int. This requires explicit casting using the cast operator, such as '(int)b;', which can lead to data loss.

Java automatically checks and enforces array bounds during runtime, throwing an ArrayIndexOutOfBoundsException if an index is accessed outside its bounds. This contrasts with languages like C, where accessing out-of-bounds indices can lead to undefined behavior and potential security vulnerabilities. Java’s approach enhances program reliability by preventing buffer overflows and offering robust error handling through exceptions.

Java’s use of the Unicode character set enhances internationalization by allowing it to handle characters from virtually all writing systems globally, supporting localized text processing and storage. Unlike ASCII, which covers only English characters, Unicode encompasses a wide range of scripts, making Java applications more adaptable for international markets, facilitating the development of globalized applications.

You might also like