Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50
Data types, variables, and arrays
Java’s three most fundamental
elements 1. data types, 2. variables, and 3. arrays. 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 coercions or conversions of conflicting types as in some languages. Primitive Data Types
• Java defines eight primitive data types:
1)byte – 8-bit integer type 2)short – 16-bit integer type 3)int – 32-bit integer type 4)long – 64-bit integer type 5)float – 32-bit floating-point type 6)double – 64-bit floating-point type 7)char – 16 bit - symbols in a character set 8)boolean – logical values true and false Int (Java Vs C/C++) • Languages such as C and C++ allow the size of an integer to vary based upon the dictates of the execution environment. However, Java is different. • Because of Java’s portability requirement, all data types have a strictly defined range. • For example, an int is always 32 bits, regardless of the particular platform. • This allows programs to be written that are guaranteed to run without porting on any machine architecture. Integers 1. Byte 2. Short 3. Int 4. Long • All of these are signed, positive and negative values. • Java does not support unsigned, positive-only integers. Integers • byte: 8-bit integer type. Range: -128 to 127. Example: byte b = -15; Usage: particularly when working with data streams. • short: 16-bit integer type. Range: -32768 to 32767. Example: short c = 1000; Usage: probably the least used simple type. • int: 32-bit integer type. Range: -2147483648 to 2147483647. Example: int b = -50000; Usage: 1) Most common integer type. 2) Typically used to control loops and to index arrays. 3) Expressions involving the byte, short and int values are promoted to int before calculation. long: 64-bit integer type. Range: -9223372036854775808 to 9223372036854775807. Example: long l = 10000000000000000; Usage: 1) useful when int type is not large enough to hold the desired value • float: also known as real numbers. • There are two kinds of floating-point types, float and double, which represent single- and double-precision numbers, respectively. 1. Float is a 32-bit floating-point number. Range: 1.4e-045 to 3.4e+038. Example: float f = 1.5; Usage: 1) fractional part is needed 2) large degree of precision is not required 2. double: 64-bit floating-point number. Range: 4.9e-324 to 1.8e+308. Example: double pi = 3.1416; Usage: 1) accuracy over many iterative calculations 2) manipulation of large-valued numbers Char char: 16-bit data type used to store characters. Range: 0 to 65536. Example: char c = ‘a’; Usage: 1) Represents both ASCII and Unicode character sets; Unicode defines a character set with characters found in (almost) all human languages. 2) Not the same as in C/C++ where char is 8-bit and represents ASCII only. Char (Java Vs C/C++) • C/C++ programmers beware: char in Java is not the same as char in C or C++. In C/C++, char is 8 bits wide. • 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. • Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. Char • This program displays the following 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. • As mentioned, the ASCII character set occupies the first 127 values in the Unicode character set. • For this reason, all the “old tricks” that you may have used with characters in other languages will work in Java, too. char as int • char can also be thought of as an integer type on which you can perform arithmetic operations. Boolean • Two-valued type of logical values. Range: values true and false. Example: boolean b = (1<2); Usage: 1) returned by relational operators, such as 1<2 2) required by branching expressions such as if or for Boolean boolean b; b = false; System.out.println("b is " + b); b = true; System.out.println("b is " + b); if(b) System.out.println("This is executed."); b = false; if(b) System.out.println("This is not executed."); System.out.println("10 > 9 is " + (10 > 9)); Boolean • b is false • b is true • This is executed. • 10 > 9 is true LITERALS Integer Literals • Decimal • Octal - Octal values are denoted in Java by a leading zero. • Normal decimal numbers cannot have a leading zero • Hexadecimal - You signify a hexadecimal constant with a leading zero-x, (0x or 0X). • An integer literal can always be assigned to a long variable. However, to specify a long literal, you will need to explicitly tell the compiler that the literal value is of type long. • You do this by appending an upper- or lowercase L to the literal. For example, 0x7ffffffffffffffL or 9223372036854775807L Floating-Point Literals • Standard notation – 3.1649 • 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. Character literal • A literal character is represented inside a pair of single quotes. • 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. String Literals • String literals 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\”“ Escape sequence Variables
• declaration – how to assign a type to a variable
• initialization – how to give an initial value to a variable • scope – how the variable is visible to other parts of the program • lifetime – how the variable is created, used and destroyed • type conversion – how Java handles automatic type conversion • type casting – how the type of a variable can be narrowed down • type promotion – how the type of a variable can be expanded Variables
• Java uses variables to store data.
• To allocate memory space for a variable JVM requires: 1) to specify the data type of the variable 2) to associate an identifier with the variable 3) optionally, the variable may be assigned an initial value • All done as part of variable declaration. Basic Variable Declaration • datatype identifier [=value]; • datatype must be – A simple datatype – User defined datatype (class type) • Identifier is a recognizable name confirm to identifier rules • Value is an optional initial value. Variable Declaration
• We can declare several variables at the same time:
type identifier [=value], identifier [=value] …; Examples: int a, b, c; int d = 3, e, f = 5; byte g = 22; double pi = 3.14159; char ch = 'x'; Variable Scope • Scope determines the visibility of program elements with respect to other program elements. • In Java, scope is defined separately for classes and methods: 1) variables defined by a class have a global scope 2) variables defined by a method have a local scope A scope is defined by a block: { … } A variable declared inside the scope is not visible outside: { int n; } n = 1;// this is illegal Variable Lifetime • Variables are created when their scope is entered by control flow and destroyed when their scope is left: • A variable declared in a method will not hold its value between different invocations of this method. • A variable declared in a block looses its value when the block is left. • Initialized in a block, a variable will be re-initialized with every re-entry. Variables lifetime is confined to its scope! Type Conversion and Casting • If the two types are compatible, then Java will perform the conversion automatically. For example - int value to a long variable • Use cast to obtain a conversion between incompatible types. Java’s Automatic Conversions • When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met: 1. The two types are compatible. 2. The destination type is larger than the source type. • When these two conditions are met, a widening conversion takes place. Casting Incompatible Types • called as a narrowing conversion • To create a conversion between two incompatible types, you must use a cast. • A cast is simply an explicit type conversion. It has this general form: (target-type) value • Example – int a; byte b; // ... b = (byte) a; Type conversion example Arrays • An array is a group of liked-typed variables referred to by a common name, with individual variables accessed by their index. • Arrays are: 1) declared 2) created 3) initialized 4) used • Also, arrays can have one or several dimensions. Array Declaration • Array declaration involves: 1) declaring an array identifier 2) declaring the number of dimensions 3) declaring the data type of the array elements • Two styles of array declaration: type array-variable[]; or type [] array-variable; Array Creation • After declaration, no array actually exists. • In order to create an array, we use the new operator: type array-variable[]; array-variable = new type[size]; • This creates a new array to hold size elements of type type, which reference will be kept in the variable array-variable. Array Indexing • Later we can refer to the elements of this array through their indexes: array-variable[index] • The array index always starts with zero! • The Java run-time system makes sure that all array indexes are in the correct range, otherwise raises a run-time error. Array Initialization
• Arrays can be initialized when they are declared:
int monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31}; • Note: 1) there is no need to use the new operator 2) the array is created large enough to hold all specified elements 2D Arrays
• Multidimensional arrays are arrays of arrays:
1) declaration: int array[][]; 2) creation: int array = new int[2][3]; 3) initialization: int array[][] = { {1, 2, 3}, {4, 5, 6} }; ODA_Example_DeclarationWithout Assignment class Array { month_days[7] = 31; public static void main(String args[]) month_days[8] = 30; { month_days[9] = 31; int month_days[]; month_days[10] = 30; month_days = new int[12]; month_days[11] = 31; month_days[0] = 31; System.out.println("April has " + month_days[1] = 28; month_days[3] + " days."); month_days[2] = 31; } month_days[3] = 30; } month_days[4] = 31; month_days[5] = 30; month_days[6] = 31; ODA_Example_DeclarationWithAssign ment 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."); } } 2DA_Example • A program to number each element in the array (dimension4 rows and 5 columns) from left to right, top to bottom, and then displays these values: 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(); } } } 3 Dimensional Array class ThreeDMatrix { public static void main(String args[]) { int threeD[][][] = new int[3][4][5]; int i, j, k; for(i=0; i<3; i++) for(j=0; j<4; j++) for(k=0; k<5; k++) threeD[i][j][k] = i * j * k; for(i=0; i<3; i++) { for(j=0; j<4; j++) { for(k=0; k<5; k++) System.out.print(threeD[i][j][k] + " "); System.out.println(); } System.out.println(); } } } String • It is just that Java’s string type, called String, is not a simple type. Nor is it simply an array of characters. • Rather, String defines an object String • The String type is used to declare string variables. You can also declare arrays of strings. • A quoted string constant can be assigned to a String variable. • A variable of type String can be assigned to another variable of type String. • You can use an object of type String as an argument to println( ). For example, String str = "this is a test"; System.out.println(str); String • Here, str is an object of type String. • It is assigned the string “this is a test”. • This string is displayed by the println( ) statement. • String objects have many special features and attributes that make them quite powerful and easy to use.