0% found this document useful (0 votes)
3 views21 pages

6_Array_Coversion_CLA

Uploaded by

rkmaharshi1108
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)
3 views21 pages

6_Array_Coversion_CLA

Uploaded by

rkmaharshi1108
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
You are on page 1/ 21

• Reference Types

• Array
o One-Dimensional Arrays
o length variable for an array
o Multidimensional Arrays
o Alternative Array Declaration Syntax
o Exercises
• Array of objects
• Using Command-Line Arguments
Reference Data Types

What is reference data type ?

• In Java, a reference data type is a variable that can contain the reference or an
address of dynamically created object.
• These type of data types are not predefined like primitive data type.
• The reference data types are :

▪ Classes
▪ Arrays
▪ Interfaces
▪ Enum
▪ Annotation

• These are made and handle according to a programmer in a java program which
can hold the values like:

array type
// Points to an array instance

class type
// Points to an object or a class instance

interface type
// Points to an object and a method, which is implemented to the
corresponding interface
etc..

• Because objects are passed by reference, two different variables may refer to the
same object:

Button p, q;
p = new Button(); // p refers to a Button object.
q = p; // q refers to the same Button.
p.setLabel("Ok"); // A change to the object through p...
String s = q.getLabel(); // ...is also visible through q. // s now contains "Ok."

This is not true of primitive types, however:


int i = 3; // i contains the value 3.
int j = i; // j contains a copy of the value in i.
i = 2; // Changing i doesn't change j.
// Now, i == 2 and j == 3.
class Type:

• Java is an object-oriented programming language where an object is a variable,


associated with methods that is described by a class.
• The name of a class is treated as a type in a java program, so that you can declare a
variable of an object-type, and a method which can be called using that object- type
variable.
• Whenever a variable is created, a reference to an object is also created using the
name of a class for its type i.e. that variable can contain either null or a reference to
an object of that class.
• It is not allowed to contain any other kinds of values. Such type is called reference
types in Java.
• The object becomes an instance when the memory is allocated to that object using
new keyword.
• In addition, array types are reference types because these are treated as objects in
Java.
• For example:
class Fruit
{
fColor()
{
//.................
}
fSize()
{
//.................
}
}
class Demo
{
public static void main(String args[])
{
Fruit mango;
Fruit banana;
...
}
}
▪ In the given example the Fruit is a class that has the reference variables as mango &
banana through which we can call the behaviors associated with that class as
mango.fColor(); within the main method of the Demo class.

Array Type:

• An array is a special kind of object that contains values called elements.


• The java array enables the user to store the values of the same type in contiguous
memory allocations.
• The elements in an array are identified by an integer index which initially starts
from 0 and ends with one less than number of elements available in the array.
• All elements of an array must contain the same type of value i.e. if an array is a type
of integer then all the elements must be of integer type.
• It is a reference data type because the class named as Array implicitly extends
java.lang.Object.
• The syntax of declaring the array is shown as:

DataType [ ] variable1, variable2,


.......variableN;
DataType [ ] variable = new DataType
[ArraySize];
DataType [ ] variable = {item 1, item 2,...item n};

For example:

int [] a = new int [10];


String [] b = {"reference","data", "type"};

• In the first statement, an array variable "a" is declared of integer data type that
holds the memory spaces according to the size of int. The index of the array starts
from a[0] and ends with a[9]. Thus, the integer value can be assigned for each or a
particular index position of the array.
• In the second statement, the array "b" is declared of string data type that has the
enough memory spaces to directly holds the three string values. Thus each value is
assigned for each index position of the array.

interface Type:

• Java provides an another kind of reference data type or a mechanism to


support multiple inheritance feature called an interface.
• The name of an interface can be used to specify the type of a reference.
• A value is not allowed to be assign to a variable declared using an interface type
until the object implements the specified interface.
• When a class declaration implements an interface, that class inherits all of the
variables and methods declared in that interface.
• So the implementations for all of the methods declared in the interface must be
provided by that class.
• For example, Java provides a class called Thread that implements Runnable
interface.
Thus the following assignment can be allowed:

Runnable r;
r = new Thread();

enum Type:

• The enum types were introduced in Java programming from Java Version 5.0.
• These are special classes that have a fixed number of instances.
• All these instances are known at the compile time.
• The name of an interface can be used to specify the type of a reference.
• An enum type is a type whose fields consist of a fixed set of constants. Common
examples include compass directions (values of NORTH, SOUTH, EAST, and WEST)
and the days of the week.
• Because they are constants, the names of an enum type's fields are in uppercase
letters.
• In the Java programming language, you define an enum type by using the enum
keyword. For example, you would specify a days-of-the-week enum type as:

public enum Day


{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
public class EnumTest
{
Day day;

public EnumTest(Day day)


{
this.day = day;
}
public void tellItLikeItIs()
{
switch (day)
{
case MONDAY:
System.out.println("Mondays are bad.");
break;

case FRIDAY:
System.out.println("Fridays are better.");
break;

case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;

default:
System.out.println("Midweek days are so-so.");
break;
}
}
public static void main(String[] args)
{
EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs();
EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
thirdDay.tellItLikeItIs();
EnumTest fifthDay = new EnumTest(Day.FRIDAY);
fifthDay.tellItLikeItIs();
EnumTest sixthDay = new EnumTest(Day.SATURDAY);
sixthDay.tellItLikeItIs();
EnumTest seventhDay = new EnumTest(Day.SUNDAY);
seventhDay.tellItLikeItIs();
}
}
The output is:

Mondays are bad.


Midweek days are so-so.
Fridays are better.
Weekends are best.
Weekends are best.
annotation Type:

• Annotations were introduced in Java programming from Java Version 5.0.


• These are special kinds of interfaces that are used to annotate programming
elements in the source code.
• These could then be used by annotation processing tools.

Reference Type Summary


The distinction between primitive types passed by value, and objects and arrays passed by
reference is a crucial one in Java. Be sure you understand the following:
• All objects and arrays are handled by reference in Java. (Those object references are
passed-by-value to methods, however.)
• The = and == operators assign and test references to objects. Use clone() and
equals() to actually copy or test the objects themselves.
• The necessary referencing and dereferencing of objects and arrays is handled
automatically by Java.
• A reference type can never be cast to a primitive type.
• A primitive type can never be cast to a reference type.
• There is no pointer arithmetic in Java.
• There is no sizeof operator in Java.
• null is a special value that means "no object" or indicates an absence of reference.
Array

• An array is a group of like-typed variables that are referred to by a common name.


• Arrays of any type can be created and may have one or more dimensions.

One-Dimensional Arrays

• A one-dimensional array is, essentially, a list of like-typed variables. To create an


array, you first must create an array variable of the desired type.
• The general form of a one dimensional array declaration is

type var-name[ ];

type - declares the base type of the array

Example : Array declaration

int month_days[];

• To link month_days with an actual, physical array of integers, you must allocate one
using new and assign it to month_days. new is a special operator that allocates
memory.

array-var = new type[size];

Example : Array allocation

month_days = new int[12];

int month_days[] = new int[12];

• That is, to use new to allocate an array, you must specify the type and number of
elements to allocate.
• The elements in the array allocated by new will automatically be initialized to zero.
Example : 1 :

// Demonstrate a one-dimensional array.

class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
Example : 2 :
An array initializer is a list of comma-separated expressions surrounded by curly braces.

// Example for array initializer.


class AutoArray {
public static void main(String args[]) {

int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}
length variable for an array

• Specifically, the size of an array—that is, the number of elements that an array can hold—is
found in its length instance variable.
• All arrays have this variable, and it will always hold the size of the array. Here is a program
that demonstrates this property:

// This program demonstrates the length array member.


class Length {
public static void main(String args[]) {
int a1[] = new int[10];
int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};
int a3[] = {4, 3, 2, 1};
System.out.println("length of a1 is " + a1.length);
System.out.println("length of a2 is " + a2.length);
System.out.println("length of a3 is " + a3.length);
}
}

Output:
Multidimensional Arrays

• In Java, multidimensional arrays are actually arrays of arrays.


• To declare a multidimensional array variable, specify each additional index using another
set of square brackets.

For example, the following declares a two-dimensional array variable

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

.
// Demonstrate a two-dimensional array.

class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}

Output:
// Manually allocate differing size second dimensions.
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}

Output:
Alternative Array Declaration Syntax

There is a second form that may be used to declare an array:

type[ ] var-name;

Here, the square brackets follow the type specifier, and not the name of the array
variable.

For example, the following two declarations are equivalent:

int al[ ] = new int[3];


int[ ] a2 = new int[3];

The following declarations are also equivalent:

char twod1[ ][ ] = new char[3][4];


char[ ][ ] twod2 = new char[3][4];

This alternative declaration form is included as a convenience, and is also useful when specifying
an array as a return type for a method.
//Creating instance for each element of an array for Dog class
for (int i=0; i<7 ; i++)
{
pets[i] = new Dog();
}
Conversion of Numeric Types

• There are various types of conversions for numeric types, like


▪ Widening Conversion
▪ Narrowing Conversion
▪ Mixed Conversion

Widening Primitive Conversion


• The widening conversion is the conversion of a sub-type to one of its super-types.
• The following are specific conversions on primitive types & are called the widening
primitive conversions:

▪ byte to short, int, long, float, or double


▪ short to int, long, float, or double
▪ char to int, long, float, or double
▪ int to long, float, or double
▪ long to float or double
▪ float to double

• Widening primitive conversions do not lose information about the overall


magnitude of a numeric value.
• Indeed, conversions widening from an integral type to another integral type and
from float to double do not lose any information at all; the numeric value is
preserved exactly.
• Here is an example of a widening conversion that loses precision:

class Test {
public static void main(String[] args)
{
int big = 1234567890;
float approx = big;
System.out.println(big - (int)approx);
}
}
output

-46
Narrowing Conversion

The narrowing conversion occurs from a type to a different type that has a smaller size,
such as from a long (64 bits) to an int (32 bits).

In general, the narrowing primitive conversion can occur in these cases:

1. short to byte or char


2. char to byte or short
3. int to byte, short, or char
4. long to byte, short, or char
5. float to byte, short, char, int, or long
6. double to byte, short, char, int, long, or float

• The narrowing primitive conversion must be explicit.


• You need to specify the target type in parentheses.

public class MainClass {


public static void main(String[] args) {
long a = 10;
int b = (int) a; // narrowing conversion
System.out.println(a);
System.out.println(b);
}
}
Mixed Conversion
• A mixed conversion is the conversion that involves first a widening conversion
followed by a narrowing conversion.
• For numeric types, the following are the cases for mixed conversions:
o char to byte or short
o short to char
o byte to char
• The mixed conversion involve the conversion of char with the other two sub-types
of int.
In these conversion, first a widening conversion is done to the int type and then the
narrowing conversion is done to the target type.
Using Command-Line Arguments

• Sometimes you will want to pass information into a program when you run it. This is
accomplished by passing command-line arguments to main( ).
• A command-line argument is the information that directly follows the program’s name on
the command-line when it is executed.
• To access the command-line arguments inside a Java program is quite easy—they are
stored as strings in the String array passed to main( ).
• For example, the following program displays all of the command-line arguments that it is
called with:

// Display all command-line arguments.


class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}

Try executing this program, as shown here:

You might also like