Data Types, Variables, and Arrays
The Primitive Types
• four groups:
– 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 does not support unsigned, positive-only integers.
• high-order bit, which defines the sign of an integer value.
• when byte and short values are used in an expression, they are promoted
to int when the expression is evaluated.
• Floating-Point Types
• Characters
– Java uses Unicode to represent characters.
– Unicode required 16 bits.
• Booleans
– Size is JVM dependent
// 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));
}
}
The output
b is false
b is true
This is executed.
10 > 9 is true
• Integer Literals
– Normal decimal numbers cannot have a leading zero.
– 09 will produce an error from the compiler, since 9 is outside of octal’s 0 to 7
– hexadecimal constant with a leading zero-x, (0x or 0X).
– Long-appending an upper- or lowercase L to the literal 9223372036854775807L
• Beginning with JDK 7
– integer literals using binary. prefix the value with 0b or 0B.
– int x = 0b1010; //x=10
– embed one or more underscores in an integer literal
– int x = 123_456_789;
– When the literal is compiled, the underscores are discarded.
– if underscore is at beginning or at end of the number it will show error
– Eg:
int x = _123_456_789 ( or) 123_456_789_ (or) _123_456_789_
Example: Floating-Point Literals
2.0, 3.14159, and 0.6667
6.022E23, 314159E–05, and 2e+100.
• Floating-point literals in Java default to double precision.
example : float f=1.2;
error: incompatible types: possible lossy conversion from double to float float f=1.2;
• To specify a float literal, append an F or f to the constant.
float f=1.2f //ok;
• explicitly specify a double literal by appending a D or d.
• 0x12.2P2 is a valid floating-point literal.
Hexadecimal floating-point literals -They must be in a form similar to scientific notation, but a P
or p, rather than an E or ebut a P or p, rather than an E or e, is used.
double num = 9_423_497_862.0;
9,423,497,862.0.
double num = 9_423_497.1_0_9;
is legal. In this case, the fractional part is .109.
• Boolean Literals
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.
Variables
// This program will not compile
class ScopeErr {
public static void main(String args[]) {
int bar = 1;
{ // creates a new scope
int bar = 2;// Compile-time error – bar already defined!
}
}
}
No Error
class Scope
{
int bar = 1;
public static void main(String args[])
{
int bar = 2;
System.out.println(bar);
}
}
E:\javaprogram>javac Scope.java
E:\javaprogram>java Scope
2
#include<iostream> class Scope{
using namespace std; public static void main(String args[]) {
int main() int i=10;
{ for(int i=0;i<5;i++)
{
int i=10;
for(int i=0;i<5;i++) }
{ }
} }
} E:\javaprogram>javac Scope.java
Scope.java:5: error: variable i is already defined
No Error in C++
in method main(String[])
for(int i=0;i<5;i++)
^
1 error
Type Conversion and Casting
• Java’s Automatic Conversions
– an automatic type conversion will take place if the following two conditions are met:
• The two types are compatible
• The destination type is larger than the source type
Characters can never be converted to boolean type. Both are incompatible.
• Casting Incompatible Types
– (target-type) value
– When int is cast into a byte variable, the result is the remainder of the division of int value
by 256 (the range of a byte)
– When double is converted to a byte, its fractional component is lost, and the value is
reduced modulo 256
• Automatic Type Promotion in Expressions
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
byte b = 50,c =2;
b = b * c; // Error! Cannot assign an int to a byte!
– Java automatically promotes each byte, short, or char operand to int when
evaluating an expression.
byte b = 50;
b = (byte)(b * 2);
// Demonstrate casts. class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
output:
Conversion of int to byte. i and b 257 1
Conversion of double to int. d and i 323.142 323
• The Type Promotion Rules
class Promote {
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}
f * b, b is promoted to a float
i/c, c is promoted to int
d * s, the value of s is promoted to double
• One-Dimensional Arrays Arrays
type var-name[ ]; int month_days[];
array-var = new type [size]; month_days = new int[12];
type array-var = new type [size]; int month_days = new int[12];
type var-name[ ]={va1,val2,……};
int var[2]; error
int var[]={1,2};:OK
// 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.");
}
// Average an array of values.
class Average {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
Int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5);
}
}
Output:
Average is 12.299999999999999
Multidimensional Arrays
• 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];
Output:
01234
int i, j, k = 0;
56789
for(i=0; i<4; i++)
10 11 12 13 14
for(j=0; j<5; j++)
15 16 17 18 19
{ 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();
}
}
}
// 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();
}
}
}
This program generates the following output:
0
12
345
6789
// Initialize a two-dimensional array.
class Matrix {
public static void main(String args[]) {
double m[][] = {
{ 0*0, 1*0, 2*0, 3*0 },
Output:
{ 0*1, 1*1, 2*1, 3*1 }, 0.0 0.0 0.0 0.0
{ 0*2, 1*2, 2*2, 3*2 }, 0.0 1.0 2.0 3.0
{ 0*3, 1*3, 2*3, 3*3 } 0.0 2.0 4.0 6.0
}; 0.0 3.0 6.0 9.0
int i, j;
for(i=0; i<4; i++)
{
for(j=0; j<4; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}
Alternative Array Declaration Syntax
• type[ ] var-name;
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];
• int[] nums, nums2, nums3; // create three arrays variables of type int.
It is the same as writing
int nums[], nums2[], nums3[]; // create three arrays
• The alternative declaration form is also useful when specifying an array as
a return type for a method.
String
• Java does not support string type
• Java’s string type, called String, is not a primitive type.
• String defines an object
• The String type is used to declare string variables.
• arrays of strings-possible.
String str = "this is a test";
System.out.println(str);