Data Types, Variables, and Arrays
Java’s most fundamental elements: data types, variables, and arrays. Java supports several types of data. You may use these types to declare variables and to create arrays.
Java Is a Strongly Typed Language:
ü It is important to state that Java is a strongly typed language.
ü First, every variable has a type, every expression has a type, and every type is strictly defined.
ü Second, all assignments, whether explicit or via parameter passing in method calls, are checked for type compatibility.
ü There are no automatic conversions of conflicting types as in some languages. The Java compiler checks all expressions and parameters to ensure that the types are compatible. Any type mismatches that errors must be corrected before the compiler will finish compiling the class.
For example, in C/C++ you can assign a floating-point value to an integer. In Java, you cannot. Also, in C there is not necessarily strong type-checking between a parameter and an argument. In Java, there is. You might find Java’s strong type-checking a bit tedious at first. But remember, in the long run it will help reduce the possibility of errors in your code.
Data Types:
Java provides two different kinds of data types:
Primitive data types:
Primitive, or basic, data types are classified as,
ü Integers This group includes byte, short, int, and long, which are for whole valued signed numbers.
ü Floating-point numbers This group includes float and double, which represent numbers with fractional precision.
ü Characters This group includes char, which represents symbols in a character set, like letters and numbers.
ü Boolean This group includes boolean, which is a special type for representing true/false values
Integers:
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and negative values. Java does not support unsigned, positive-only integers.
The width and ranges of these integer types vary widely, as shown in this table:
Name Size Minimum Value Maximum Value |
byte 1 byte (8 bits) –128 127 |
short 2 bytes (16 bits) –32768 32767 |
int 4 bytes (32 bits) –2147483648 2147483647 |
long 8 bytes (64 bits) –9223372036854775808 9223372036854775807 |
Examples: byte b, c; short s; int x; long days;
Endianness:
ü Which describes how multibyte data types, such as short, int, and long, are stored in memory. If it takes 2 bytes to represent a short, then which one comes first, the most significant or the least significant? To say that a machine is big-endian, means that the most significant byte is first, followed by the least significant one. Machines such as the SPARC and PowerPC are big-endian, while the Intel x86 series is little-endian.
ü Numbers larger than 1 byte are stored in big-endian order. The high-order (or most significant) byte is stored first in memory. Little-endian order follows the reverse convention. For example, take the short (2 byte) representation of the number 256: 00000001 00000000.
The order conventions are:
Address Big-Endian Representation Little-Endian Representation
00 00000001 00000000
01 00000000 00000001
Program: Compute distance light travels using long variables.
class Light
{
public static void main(String args[])
{
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
}
}
Output: In 1000 days light will travel about 16070400000000 miles.
Clearly, the result could not have been held in an int variable.
Floating-Point Types:
· Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision.
· For example, calculations such as square root, or transcendental such as sine and cosine, result in a value whose precision requires a floating-point type.
· Java implements the standard (IEEE–754) set of floating-point types and operators. There are two kinds of floating-point types, float and double, which represent single- and double-precision numbers, respectively.
· Their width and ranges are shown here:
Name Width in Bits Approximate Range |
double 64 4.9e–324 to 1.8e+308 |
float 32 1.4e−045 to 3.4e+038 |
Ex: float hightemp, lowtemp; double pi, r, a;
Program: Compute the area of a circle.
class Area
{
public static void main(String args[])
{
double pi, r, area;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
area = pi * r * r; // compute area
TJA System.out.println("Area of circle is " + area);
}
}
Output: Area of circle is 366.436224
Characters:
ü In Java, the data type used to store characters is char.
ü However, C/C++ programmers beware: char in Java is not the same as char in C or C++.
ü In C/C++, char is an integer type that is 8 bits wide. This is not the case in Java. Instead, Java uses Unicode to represent characters.
ü Unicode defines a fully international character set that can represent all of the characters found in all human languages.
ü It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more. For this purpose, it requires 16 bits.
ü In Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. The standard set of characters known as ASCII still ranges from 0 to 127 as always, and the extended 8-bit character set, ISO-Latin-1, ranges from 0 to 255.
Program: Demonstrate char data type.
class CharDemo
{
public static void main(String args[])
{
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
Output: ch1 and ch2: X Y
Notice that ch1 is assigned the value 88, which is the ASCII (and Unicode) value that corresponds to the letter X.
Booleans:
A boolean data type can take on only one of the literal values, true or false. For example,
Program: Demonstrate boolean values
class BoolTest
{
public static void main(String args[])
{
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}
Output: b is false
b is true
This is executed.
10 > 9 is true
There are three interesting things to notice about this program:
ü First, as you can see, when a boolean value is output by println( ), “true” or “false” is displayed.
ü Second, the value of a boolean variable is sufficient, by itself, to control the if statement. There is no need to write an if statement like this: if(b == true) ...
ü Third, the outcome of a relational operator, such as <, is a boolean value. This is why the expression 10 > 9 displays the value “true”.
Composite or Reference or advanced data types:
· Each of the Primitive data types accepts only one number, one character, or one state. Composite or reference data types represent several values. This is the main difference between primitive and referenced data types.
· Composite data types are of two kinds: classes and arrays. For example, take an array. It can store several values. Similarly take a class. It can store different values. So they are called advanced data types. We can access an array or an object of a class in memory through references. So, they are also called referenced data types.
Type Casting:
ü Converting one data type into another data type is called Type Casting or simply Casting.
ü Whenever we assign a value to a variable using assignment operator, the java compiler checks for uniformity and hence the data types at both the sides should be same.
ü If the data types are not same, then we should convert the data types to become same at both the sides.
ü To convert the data type, we use ‘cast operator’. Cast operator means writing the data type between simple braces, before a variable or method whose value is to be converted.
Casting Primitive Data Types:
It is possible to convert one primitive data type into another primitive data type. This can be done in two ways:
- Widening
- Narrowing
The primitive data types are classified into two types, lower types and higher types. Naturally, the lower types are the types which use less memory and which can be represent less number of digits in the value. The higher types use more memory and can represent more number of digits. To better understand this see the following diagram.
byte, short, char, int, long, float, double lowerß----------------------------------àhigher |
Thus, char is lower type than int. float is higher type than long.
Note: boolean is not included earlier, because it cannot be converted into any other data type.
Widening in primitive data types
Java Literals:
Java provides 5 kinds of Literals. Those are,
Integer Literals:
· Integer literals can be used in decimal, octal notation, or hexadecimal
· To specify a decimal value, simply use the normal number like 1,2,45 and so on. To indicate that a literal value is long, "L" or "l" has to be appended to the number.
· An octal values are given in base 8 is preceded by 0 symbol and the value can have the digits 0 – 7. The valid value 09 will produce an error from the compiler, since 9 is outside of octal’s 0 to 7 range.
· A more common base for numbers used by programmers is hexadecimal, Hexadecimal values are given in base 16 and can include the digits 0-9 and the letters A-F or a-f. To specify a hexadecimal value, use 0x followed by digits and letters that comprise the value.
· The Table below lists few examples.
Integer Long Octal Hexadecimal |
0 0L 0 0x0 |
1 1L 01 0x1 |
10 10L 012 0xA |
15 15L 017 0XF |
16 16L 020 0x10 |
100 100L 0144 0x64 |
Floating-Point Literals:
· Floating-point numbers represent decimal values with a fractional component. They can be expressed in either standard or scientific notation.
· Standard notation consists of a whole number component followed by a decimal point followed by a fractional component. For example, 2.0, 3.14159, and 0.6667 represent valid standard-notation floating-point numbers.
· Scientific notation uses a standard-notation, floating-point number plus a suffix that specifies a power of 10 by which the number is to be multiplied. The exponent is indicated by an E or e followed by a decimal number, which can be positive or negative. Examples include 6.022E23, 314159E–05, and 2e+100.
· Floating-point literals in Java default to double precision. To specify a float literal, you must append an F or f to the constant. You can also explicitly specify a double literal by appending a D or d.
Boolean Literals:
· Boolean literals are simple. There are only two logical values that a boolean value can have, true and false. The values of true and false do not convert into any numerical representation.
· The true literal in Java does not equal 1, nor does the false literal equal 0. In Java, they can only be assigned to variables declared as boolean, or used in expressions with Boolean operators.
Character Literals:
· Characters in Java are indices into the Unicode character set. They are 16-bit values that can be converted into integers and manipulated with the integer operators, such as the addition and subtraction operators. A literal character is represented inside a pair of single quotes.
· All of the visible ASCII characters can be directly entered inside the quotes, such as ‘a’, ‘z’, and ‘@’.
· For characters that are impossible to enter directly, there are several escape sequences, which allow you to enter the character you need, such as ‘\’’ for the single-quote character itself, and ‘\n’ for the new line character.
· There is also a mechanism for directly entering the value of a character in octal or hexadecimal. For octal notation use the backslash followed by the three-digit number. For example, ‘\141’ is the letter ‘a’. For hexadecimal, you enter a backslash-u (\u), then exactly four hexadecimal digits. For example, ‘\u0061’ .
· Table shows the character escape sequences.
THE JAVA LANGUAGE
Escape Sequence Description
\ddd Octal character (ddd)
\uxxxx Hexadecimal UNICODE character (xxxx)
\’ Single quote
\” Double quote
\\ Backslash
\r Carriage return
\n New line (also known as line feed)
\f Form feed
\t Tab
\b Backspace
String Literals:
· String literals in Java are specified by enclosing a sequence of characters between a pair of double quotes.
· Examples of string literals are
“Hello World”
“two\nlines”
“\”This is in quotes\””
Note: In C/C++, strings are implemented as arrays of characters. However, this is not the case in Java. Strings are actually object types.
Variables
ü A variable is used to store data in the computer's memory, which can be used by the program later.
ü A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition, all variables have a scope, which defines their visibility, and a lifetime.
ü Variables store the data temporarily.
ü Variable names are case sensitive.
Note: The data contained by the variable can vary (that’s why it is called a variable), but the data type can’t change.
Types of Variables:
ü The Java programming language defines the following types of variables:
· Instance Variables (non-static fields).
· Local Variables.
· Class Variables (static fields).
ü Instance variables are used to define attributes or the state of a particular object and are used to store information needed by multiple methods in the objects.
ü Local variables are used inside blocks as counters or in methods as temporary variables and are used to store information needed by a single method.
ü Class variables are global to a class and to all the instances of the class and are useful for communicating between different objects of all the same class or keeping track of global states.
Declaring a Variable:
In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
The type is one of Java’s atomic types, or the name of a class or interface. (Class and interface types are discussed later in Part I of this book.) The identifier is the name of the
variable.
We can initialize the variable by specifying an equal sign and a value. To declare more than one variable of the specified type, use a comma-separated list.
Ex: int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
Dynamic Initialization:
ü 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.
ü For example, here is a short program that computes the length of the hypotenuse of a right triangle given the lengths of its two opposing sides:
Program: Demonstrate dynamic initialization.
class DynInit
{
public static void main(String args[])
{
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
Here, three local variables—a, b,and c—are declared. The first two, a and b, are initialized by constants. However, c is initialized dynamically to the length of the hypotenuse (using the Pythagorean theorem). The program uses another of Java’s built-in methods, sqrt( ), which is a member of the Math class, to compute the square root of its argument. The key point here is that the initialization expression may use any element valid at the time of the initialization, including calls to methods, other variables, or literals.
The Scope and Lifetime of Variables:
ü All of the variables used have been declared at the start of the main( ) method. However, Java allows variables to be declared within any block.
ü A block is begun with an opening curly brace ({ ) and ended by a closing curly brace ( }). A block defines a scope. Thus, each time you start a new block, you are creating a new scope.
ü A scope determines what objects are visible to other parts of your program. It also determines the lifetime of those objects.
ü In Java, the two major scopes are those defined by a class and those defined by a method.
ü In Chapter 6 (Introducing Classes and Objects) we will discuss what about scope of class
ü The scope defined by a method begins with its opening curly brace. However, if that method has parameters, they too are included within the method’s scope.
ü Scopes can be nested. For example, each time we create a block of code, we are creating a new, nested scope. When this occurs, the outer scope encloses the inner scope. This means that objects declared in the outer scope will be visible to code within the inner scope. However, the reverse is not true. Objects declared within the inner scope will not be visible outside it.
ü To understand the effect of nested scopes, consider the following program:
Program: Demonstrate block scope.
class Scope
{
public static void main(String args[])
{
int x; // known to all code within main
x = 10;
if(x == 10)
{ // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
Output: x and y: 10 20
x is 40
ü Suppose a class contains 50 students, and we want to store their roll numbers, we need 50 separate variables for storing the roll numbers, as shown here:
int rno;
int rno1;
int rno2;
------
------
int rno49;
ü Now to store roll numbers into these variables, we need another 50 statements. Imagine writing 100 statements just to store the roll numbers of students.
ü On the other hand, if we have a single variable which can represent all of these 50 variables, it would be very useful to us. Such a variable is called an array.
ü Definition: An array represents a group of elements of same data type. It can store a group of elements. So we can store a group of int values or a group of float values or a group of strings in the array.
Note: We can not store some int values and some float values in the array.
ü The Advantage of using arrays is that they simplify programming by replacing a lot of statements by just one or two statements.
ü The difference between arrays in C/C++ and Java is that, in C/C++, by default arrays are created on static memory unless pointers are used to create them. In Java, arrays are created on dynamic memory, i.e., allotted at runtime by JVM.
Types of Arrays:
Arrays are generally categorized into two parts:
- Single dimensional arrays or 1D arrays
- Multi dimensional arrays or 2D, 3D, .. arrays
Single dimensional arrays:
A one dimensional (1D) or single dimensional array represents a row or a column of elements. For example, the marks obtained by a student in 5 different subjects can be represented by a 1D array, because these marks can be written as a row or as a column.
Creating a single dimensional array:
There are some ways of creating a single dimensional array as mentioned here:
ü We can declare a one dimensional array and directly store elements at the time of its declaration, as;
int marks[] = {91, 74, 85, 87, 94}; // declare marks[] and initialize with 5 elements
Here, int represents integer type elements which can be stored into the array, and the
array name is marks.
To represent a one dimensional array, we should use a pair of square braces [] after
the array name. Then the actual elements (integers) are mentioned inside the curly
braces { and }.
Now JVM creates 5 blocks of memory as there are 5 elements being stored into the
array. These blocks of memory can be individually referred to as marks[0], marks[1]..
marks[4]. Here, 0,1,2,3,4 elements are called as index of the array.
Index refers to the element position in the array. A one dimensional array will have
only one index.
In general, any element of the array can be shown by writing marks[i], where i=0,1,..
4.
91 | 74 | 85 | 87 | 94 |
marks[0] marks[1] marks[2] marks[3] marks[4]
marks[i]
Figure. Arrangement of elements in a 1D array
ü Another way of creating a one dimensional array is by declaring the array first and then allocating memory for it by using new operator.
int marks[]; // declare marks array
marks = new int[5]; // allocate memory for storing 5 elements.
These two statements can also be written by combining them into a single statement,
int marks[] = new int[5]; or int[] marks = new int[5];
Here, we should understand that JVM allots memory for strong 5 integer elements
into the array. But there are no actual elements stored in the array so far. To store the
elements into array, we can use statements in the program like,
marks[0] = 91;
marks[1] = 74;
marks[2] = 85;
marks[3] = 87;
marks[4] = 94;
Or, we can pass the values from the keyboard to the array by using a loop like,
for(int i=0;i<5;i++)
{
// read integer value from the keyboard and store into marks[i]
marks[i] = Integer.parseInt(br.readLine( ));
}
ü Some examples of 1D array:
· float salary [] = { 5670.55f, 1300f, 3500f, 9050f };
· float salary[] = new float[50];
· char ch[] = { ‘a’, ‘b’, ‘c’, ‘d’,’e’};
· char ch[] = new char[5];
· Srting names[] = { “Madhava“, “Ramesh“, “Murali“, “Madhu “};
· String names[] = new String[10];
Program: Demonstrate one-dimensional array
class Array
{
public static void main(String args[])
{
int marks[];
marks = new int[5];
marks[0] = 91;
marks[1] = 74;
marks[2] = 85;
marks[3] = 87;
marks[4] = 94;
System.out.println(“Marks of 5 Students are:” + marks[0]+" "+marks[1]+"
"+marks[2]+" "+marks[3]+" "+marks[4]);
//find total marks
int tot = 0;
for(int i=0; i<5; i++)
tot += marks[i]; // or tot = tot + marks[i];
System.out.println(“Total marks:” + tot);
//find percentage
float percent = (float)tot/5;
system.out.println(“Percentage=” + percent);
}
}
Output: C:\Madhava>javac Array.java
C:\Madhava>java Array
Marks of 5 Students are:91 74 85 87 94
Total marks: 431
Percentage=86.2
Multi dimensional arrays ( 2D,3D,… arrays):
Multi dimensional arrays represent 2D, 3D, .. arrays which are combinations of several earlier types. For example, a two dimensional array is a combination of two or more (1D) one dimensional arrays. Similarly, a three dimensional array is a combination of two or more (2D) two dimensional arrays.
Two dimensional array:
A two dimensional array represents several rows and columns of data. For example, the marks obtained by 3 students in 5 subjects can be represented by 2D array as:
50, 60, 67, 85, 67
67, 78, 56, 86, 95
77, 67, 59, 89, 81
Creating a Two dimensional array:
There are some ways of creating two dimensional array as mentioned here:
ü We can declare a two dimensional array and directly store elements at the time of its declaration, as:
int marks[] [] = {{50, 60, 67, 85, 67},
{67, 78, 56, 86, 95},
{77, 67, 59, 89, 81}};
By observing these elements, we can understand the rows which are starting from 0 to
2 and the columns are starting from 0 to 4. So any element can be referred in general
as marks[i][j], where i represents row position and j represents column position. Thus,
a two dimensional array has two indexes: i and j
j=0 j=1 j=2 j=3 j=4
50 | 60 | 67 | 85 | 67 |
67 | 78 | 56 | 86 | 95 |
77 | 67 | 59 | 89 | 81 |
i=0
i=1
i=2
Figure: Arrangement of elements in a 2D array
ü Another way of creating a two dimensional array is by declaring the array first and then allocating memory for it by using new operator:
int marks[] [];
marks = new int[3][5]; or int marks[] [] = new int[3][5];
ü Some examples of 2D array:
· double d[][] = {{20.2, -5.5},{6.9,51.88}};
· byte b[][] = new byte[20][40];
· String str[][] = new String[10][15];
Program: Write a program to take a 2D array and display its elements in the form of a matrix. To display the elements of 2D array, we use two for loops, the outer loop represents the rows and the inner loop represents the columns.
class Matrix
{
public static void main(String args[])
{
float x[][] = {{1.1f, 1.2f, 1.3f, 1.4f},
{2.1f, 2.2f, 2.3f, 2.4f},
{3.1f, 3.2f, 3.3f, 3.4f}};
for(int i=0;i<3;i++) //rows
{
for(int j=0;j<4;j++) // columns
{
System.out.println(x[i][j]+”\t”);
}
}
}
}
Output: 1.1 1.2 1.3 1.4
2.1 2.2 2.3 2.4
3.1 3.2 3.3 3.4
Technical Interview Questions and Answers:
1. What is the difference between float and double in Java?
Ans: float can represent up to 7 digits accurately after decimal point, whereas double can represent up to 15 digits accurately after decimal point.
2. What is a Unicode system?
Ans: Unicode system is an encoding standard that provides a unique number for every character, no matter what the platform, program, or language is. Unicode uses 2 bytes to represent a single character.
3. On which memory, arrays are created in Java?
Ans: Arrays are created on dynamic memory by JVM. There is no question of static memory in Java. Every thing ( variable, array, object etc.) is created on dynamic memory only.
4. How do I initialize an array of objects?
Ans: By writing a loop that initializes the base elements of array one by one like,
String str = new String[10];
for(int i=0; i<str.length; i++)
{
str[i] = “String at index:”+i;
}
5. What kinds of variables available in Java?
Ans: Java has three kinds of variables:
- Instance variables
- Local variables
- Class variables.
6. How do u assign values to variables?
Ans: By using assignment operator =.
7. What are default values if different primitive types?
Ans: int-0, short-0, byte-0, long-01, float-0.0f, double-0.0d, boolean- false, char-null.
8. How can u change the values of elements in the array?
Ans: The array subscript expression can be used to change the values of elements in the array.
9. How can one prove that the array is not null but empty?
Ans: Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.
10. What is the difference between declaring a variable and defining a variable?
Ans: In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization.
E.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions
11. Primitive data types are passed by reference or pass by value?
Ans: Primitive data types are passed by value.
12. What is final varaible?
Ans : If a variable is declared as final variable, then we can not change its value. It becomes constant.
13. What is static variable?
Ans : Static variables are shared by all instances of a class.
14. What is the value of a[3] as the result of the array declaration?
Ans : d
15. What environment variables do I need to set on my machine in order to be able to run Java programs?
Ans: CLASSPATH and PATH are the two variables.
16. Are there any global variables in Java, which can be accessed by other part of your program?
Ans: No, it is not the main method in which you define variables. Global variables are not possible because concept of encapsulation is eliminated here.