Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Lesson 2 The Java Prog Lan AUBG ICoSCIS Team Assoc. Prof. Stoyan Bonev March, 23 - 24, 2013 SWU, Blagoevgrad Time Schedule March 23, Saturday – 10:00 – 10:45 – 11:00 – 11:45 – 12:00 – 12:45 Lunch Break (45’) – 13:30 – 14:15 – 14:30 – 15:15 – 15:30 – 16:15 March 24, Sunday 09:00 – 09:45 10:00 – 10:45 11:00 – 11:45 Lunch Break (45’) 12:30 – 13:15 13:30 – 14:15 14:30 – 15:15 Lesson Contents Overview of Java Programming Language Anatomy of a Java program Sample source text Packages Comments Names – identifiers, reserved words, modifiers Classes – data fields, methods (statements, blocks of statements ) Components of a Java program Data – by category Data – by type Expressions (incl. operands & operators) Statements Routines (member functions - methods) I/O facilities Data collections – arrays Demo programs - examples The Basics of a Java Program Java program: collection of classes. Classes capsulated as packages – named or unnamed Package: collection of related classes Class: collection of data items and methods Method: designed to accomplish a specific task There is a main method public static void main()in every Java program. The main method provides the control of program flow. The JVM executes application by invoking the main method 4 4 The package Logical entity describes user defined or API predefined package Really located as one file or as many files Syntax to mark package start: package <name>; Always first line in the source code May be omitted: program without explicit package name Reference to predefined package: import <package name>; import java.lang.*; This statement makes the methods in the library package java.lang available to the class following it. java.lang is just 1 package in the Java library or API. Primitive data types and the class String: Part of the Java language. They Don’t need to be imported Java Programming: From Problem Analysis to Program Design, 5 4e 5 Anatomy of a Java program: Sample source text Sample Run: Java Programming: From Problem Analysis to Program Design, 4e 3e 6 Comments Three types of comments in Java. Line comment: A line comment is preceded by two slashes (//) in a line. Paragraph comment: A paragraph comment is enclosed between /* and */ in one or multiple lines. javadoc comment: javadoc comments begin with /** and end with */. Used for documenting classes, data, methods. They can be extracted into HTML file using JDK's javadoc command. 5/3/2017 Assoc. Prof. Stoyan 7 Bonev Names - Identifiers • Names of entities (like variables, named constants, methods, classes, objects etc.) • An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($). • An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit. • An identifier cannot be a reserved word. • An identifier can be of any length. • Java is case sensitive – ion, Ion, IOn, ION Java Programming: From Problem Analysis to Program Design, 3e 8 Naming Conventions • Choose meaningful and descriptive names. • Class names: – Capitalize the first letter of each word in the name. For example, the class name ComputeArea. • Named Constants: – Capitalize all letters in constants, and use underscores to connect words. For example, PI and MAX_VALUE • Variables and method names: – Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area, and the method computeArea. Java Programming: From Problem Analysis to Program Design, 3e 9 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used for other purposes in the program. For example, class, void. are reserved words. Modifiers Java uses certain reserved words called modifiers that specify the properties of the data, methods, and classes and how they can be used. Examples of modifiers are public and static. Other modifiers are private, final, abstract, and protected. Java Programming: From Problem Analysis to Program Design, 3e 10 Data classified by Type • Data Types Classified: – 8 Primitive Data Types – boolean, byte, short, int, long, float, double, char – Abstract/Reference Data Types (classes, objects) – String, Object, Frame, Person, Animal, … – Array types (also reference types) Java Programming: From Problem Analysis to Program Design, 4e 3e 11 Primitive Data Types – 3 subgroups • Integral, which is a data type that deals with integers (or numbers without a decimal part) and characters • char – Unicode – 2 bytes/char, to present symbolic data • byte, short, int, long, to present numeric data fixed point • Floating-point, a data type that deals with decimal numbers • float: precision = 6 or 7 decimal places, Single (4 bytes) • double: precision = 15 decimal places, Double (8 bytes) • Boolean, a data type that deals with logical values: true, false • Memory allocated to boolean data type is 1 bit Java Programming: From Problem Analysis to Program Design, 4e 3e 12 Values and Memory Allocation for Integral Data Types Java Programming: From Problem Analysis to Program Design, 4e 3e 13 Primitive Data Types • Classified by Category as: • Literals • Named Constants • Variables Java Programming: From Problem Analysis to Program Design, 4e 3e 14 Literals (Constants) • Integer literals, integer constants, or integers: 23 -67 +447 0177 0x1a • Floating-point literals, floating-point constants, floatingpoint numbers: 12.34 +25.60 -3.15 5. .166 3.14e-2 2.78e+3 5.23e4 • Character literals, character constants, or characters: 'a' '5' '+' '\n' Java Programming: From Problem Analysis to Program Design, 4e 3e 15 Named Constants • • Named constant – – Cannot be changed during program execution Declared by using the reserved word final – Initialized when it is declared Example: final final final final double CENTIMETERS_PER_INCH = 2.54; int NO_OF_STUDENTS = 20; char BLANK = ' '; double PAY_RATE = 15.75; Java Programming: From Problem Analysis to Program Design, 4e 3e 16 Variables • Variable (name, value, data type, size) – – – – – • Content may change during program execution Must be declared before it can be used May not be automatically initialized If new value is assigned, old one is destroyed Value can only be changed by an assignment statement or an input (read) statement Example: double int char int amountDue; counter; ch; num1, num2; Java Programming: From Problem Analysis to Program Design, 4e 3e 17 Declaring and Initializing Variables int first; first = 13; OR int first = 13; char ch; ch = ‘E’; OR char ch = ‘E’; double value; value = 35.68; OR double value = 35.68; ------------------------------------------------------------- Java Programming: From Problem Analysis to Program Design, 3e 18 Unicode Format Java characters use Unicode, a 16-bit encoding scheme established by the Unicode Consortium to support the interchange, processing, and display of written texts in the world’s diverse languages. Unicode takes two bytes, preceded by \u, expressed in four hexadecimal numbers that run from '\u0000' to '\uFFFF'. So, Unicode can represent 65535 + 1 characters. char letter = 'A'; (ASCII) char letter = '\u0041'; (Unicode) char numChar = '4'; char numChar = '\u0034'; Unicode \u03b1 \u03b2 \u03b3 for three Greek letters Java Programming: From Problem Analysis to Program Design, 3e 19 (Non-)Pointers in Java • In Java, all primitive variables are value variables. (Real, actual) – it is impossible to have a pointer to any variable of one of the primitive data types • All object variables are actually reference variables (pointers, memory addresses) to objects. – it is impossible to have anything but references to objects. You can never have a plain object variable Java Programming: From Problem Analysis to Program Design, 3e 20 Expressions - operands • Operands – Literals – Named Constants – Variables – regular(scalar) or indexed – Method call – Sub expression like ( … ) Java Programming: From Problem Analysis to Program Design, 3e 21 Arithmetic Operators and Operator Precedence • • 1. 2. • Operators in 1 have a higher precedence than operators in 2 When operators have the same level of precedence, operations are performed from left to right Unary operator: operator that has one operand Binary operator: operator that has two operands • • • * + / - % (same precedence) (same precedence) Java Programming: From Problem Analysis to Program Design, 4e 3e 22 Mixed Arithmetic Expressions • Operands of different types • Examples 2 + 3.5 6 / 4 + 3.9 • Integer operands yield an integer result; floating-point numbers yield floating-point results • If both types of operands are present, the result is a floating-point number • Precedence rules are followed Java Programming: From Problem Analysis to Program Design, 4e 3e 23 Type Conversion (Casting) • Used to avoid implicit type coercion • Syntax (dataTypeName)expression • Expression evaluated first, then type converted to dataTypeName • Examples (int)(7.9 + 6.7) => 14 (int)(7.9) + (int)(6.7) => 13 Java Programming: From Problem Analysis to Program Design, 4e 3e 24 Conversion Rules When performing a binary operation involving two operands of different types, Java automatically converts the operand based on the following rules: 1. If one of the operands is double, the other is converted into double. 2. Otherwise, if one of the operands is float, the other is converted into float. 3. Otherwise, if one of the operands is long, the other is converted into long. 4. Otherwise, both operands are converted into int. Java Programming: From Problem Analysis to Program Design, 3e 25 Type Casting Implicit casting double d = 3; (type widening permitted) Explicit casting int i = (int)3.0; (type narrowing) int i = (int)3.9; (Fraction part is truncated) What is wrong? int x = 5 / 2.0; range increases byte, short, int, long, float, double Java Programming: From Problem Analysis to Program Design, 3e 26 Comparison Operators Logical Operators Operator Name Operator Name < less than ! not <= less than or equal to && and > greater than || or >= greater than or equal to ^ == equal to != not equal to Java Programming: From Problem Analysis to Program Design, 3e exclusive or Conditional Operator y = (x > 0) ? 1 : -1;27 The class String • Used to manipulate strings • String – – – – Sequence of zero or more characters Enclosed in double quotation marks Null or empty strings have no characters Numeric strings consist of integers or decimal numbers – Length is the number of characters in a string Java Programming: From Problem Analysis to Program Design, 4e 3e 28 Strings and the Operator + • Operator + can be used to concatenate two strings or a string and a numeric value or character • Example "The sum = " + 12 + 26 -After this statement executes, the string assigned to str is: "The sum = 1226"; • Consider the following statement: "The sum = " + (12 + 26) • In this statement, because of the parentheses, you first evaluate num1 + num2 – Because num1 and num2 are both int variables, num1 + num2 = 12 + 26 = 38 – After this statement executes, the string assigned to str is: "The sum = 38"; Java Programming: From Problem Analysis to Program Design, 4e 3e 29 Types of statements • Declaration/definition statements • Executable statements • Every statement in Java ends with a semicolon (;). Java Programming: From Problem Analysis to Program Design, 4e 3e 30 Blocks A pair of braces in a program forms a block that groups components of a program. public class Test { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } Class block Method block Use end-of-line style for braces. Java Programming: From Problem Analysis to Program Design, 3e 31 Executable Statements • Assignment stmts – • To implement linear algorithms Selection/Decision stmts – To implement branch algorithmsif, if-else, if-else if, switch • Repetition/Iteration stmts – To implement loop algorithms for, while, dowhile, for(version foreach) • Input/Output – Other break, continue Java Programming: From Problem Analysis to Program Design, 4e 3e 32 Assignment Statements x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a; variable = variable * (expression); is equivalent to variable *= expression; Similarly, variable = variable + (expression); is equivalent to variable += expression; Java Programming: From Problem Analysis to Program Design, 3e 33 One-way if Statements if (radius >= 0) { area = radius * radius * PI; System.out.println("The area" + " for the circle of radius " + radius + " is " + area); } if (boolean-expression) { statement(s); } Boolean Expression false false (radius >= 0) true true Statement(s) area = radius * radius * PI; System.out.println("The area for the circle of " + "radius " + radius + " is " + area); (A) Java Programming: From Problem Analysis to Program Design, 3e (B) 34 The Two-way if Statement if (boolean-expression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; } true Boolean Expression Statement(s) for the true case false Statement(s) for the false case Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Java Programming: From Problem Analysis to Program Design, 3e 12 35 if...else Example if (radius >= 0) { area = radius * radius * 3.14159; System.out.println("The area for the “ + “circle of radius " + radius + " is " + area); } else { System.out.println("Negative input"); } Java Programming: From Problem Analysis to Program Design, 3e 36 Switch-case switch ( N ) { // (Assume N is an integer variable.) case 1: System.out.println("The number is 1."); break; case 2: case 4: case 8: System.out.println("The number is 2, 4, or 8."); System.out.println("(That's a power of 2!)"); break; case 3: case 6: case 9: System.out.println("The number is 3, 6, or 9."); System.out.println("(That's a multiple of 3!)"); break; case 5: System.out.println("The number is 5."); break; default: System.out.println("The number is 7 or is outside range 1 to 9."); } Java Programming: From Problem Analysis to Program Design, 3e 37 switch Statement Flow Chart status is 0 Compute tax for single filers break Compute tax for married file jointly break Compute tax for married file separatly break Compute tax for head of household break status is 1 status is 2 status is 3 default Default actions Next Statement Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Java Programming: From Problem Analysis to Program Design, 3e 44 38 Introducing while Loops int count = 0; while (count < 100) { System.out.println("Welcome to Java"); count++; } while Loop Flow Chart while (loop-continuation-condition) { int count = 0; while (count < 100) { // loop-body; System.out.println("Welcome to Java!"); Statement(s); count++; } } count = 0; Loop Continuation Condition? true Statement(s) (loop body) false (count < 100)? false true System.out.println("Welcome to Java!"); count++; Java Programming: From Problem Analysis to Program Design, 3e (B) (A) Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 39 6 do-while Loop Statement(s) (loop body) true do { // Loop body; Loop Continuation Condition? false Statement(s); } while (loop-continuation-condition); Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Java Programming: From Problem Analysis to Program Design, 3e 1 40 for Loops for (initial-action; loopcontinuation-condition; action-after-each-iteration) { // loop body; Statement(s); } int i; for (i = 0; i < 100; i++) { System.out.println( "Welcome to Java!"); } Initial-Action Loop Continuation Condition? i=0 false (i < 100)? true Statement(s) (loop body) true System.out.println( "Welcome to Java"); Action-After-Each-Iteration i++ (A) (B) false Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Java Programming: From Problem Analysis to Program Design, 3e 21 41 For-loop For (int i=1, j=10; i < j; i++, j-=2) System.out.println("i="+i+" j="+j); i=1 j=10 i=2 j=8 i=3 j=6 for (int i = 0; i < 4; i++){ for( char letter = 'A'; letter <= 'A' + i; letter++) System.out.print(letter); System.out.println(); } A AB ABC ABCD Java Programming: From Problem Analysis to Program Design, 3e 42 Enhanced for Loop (for-each loop) JDK 1.5 introduced a new for loop that enables you to traverse the complete array sequentially without using an index variable. For example, the following code displays all elements in the array myList: for (double value: myList) System.out.println(value); In general, the syntax is for (elementType value: arrayRefVar) { // Process the value } You still have to use an index variable if you wish to traverse the array in a different order or change the elements in the array. Java Programming: From Problem Analysis to Program Design, 3e 43 Console Input (Read) statement • Standard input stream object: System.in • Input numeric data to program – • Separate by blanks, lines, or tabs To read data: 1. Create an input stream object of the class Scanner (import java.util.*; or import java.util.Scanner;) 2. Use the methods such as next(), nextLine(), nextInt(), nextFloat(), nextDouble() Java Programming: From Problem Analysis to Program Design, 4e 3e 44 Input (Read) statement static Scanner console = new Scanner(System.in); • Java program: static Scanner cin = new Scanner(System.in); int feet; int inches; Suppose the input is: 23 7 Feet = cin.nextInt(); Inches = cin.nextInt(); • //Line 1 //Line 2 How to read a single character: – char ch; ch = console.next().charAt(0); Java Programming: From Problem Analysis to Program Design, 4e 3e 45 Reading Input from the Console 1. Create a Scanner object Scanner cin = new Scanner(System.in); 2. Use the methods next(), nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or nextBoolean() to obtain to a string, byte, short, int, long, float, double, or boolean value. For example, System.out.print("Enter a double value: "); Scanner cin = new Scanner(System.in); double d = cin.nextDouble(); Java Programming: From Problem Analysis to Program Design, 3e 46 public class CalculatingArea { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("This program calculates " + "the area of a rectangle or a triangle"); System.out.print("Enter a and b (for rectangle) " + "or a and h (for triangle): "); int a = input.nextInt(); int b = input.nextInt(); System.out.print("Enter 1 for a rectangle or " + "2 for a triangle: "); int choice = input.nextInt(); double area = (double) (a * b) / choice; System.out.println("The area of your figure is " + area); } } Java Programming: From Problem Analysis to Program Design, 3e 47 Output (Write/Print/Display) statement • Standard output object: System.out • Methods print println • Syntax System.out.print(stringExp); System.out.println(stringExp); System.out.println(); Java Programming: From Problem Analysis to Program Design, 4e 3e 48 Input/Output using Dialog Boxes Java Programming: From Problem Analysis to Program Design, 4e 3e 49 JOptionPane Input Two ways of obtaining input. 1. Using the Scanner class (console input) needs import java.util.Scanner; 2. Using JOptionPane input dialogs needs import javax.swing.JOptionPane; Java Programming: From Problem Analysis to Program Design, 3e 50 Getting Input from Input Dialog Boxes String input = JOptionPane.showInputDialog( "Enter an input"); 51 Converting Strings to Integers The input returned from the input dialog box is a string. If you enter a numeric value such as 123, it returns “123”. To obtain the input as a number, you have to convert a string into a number. To convert a string into an int value, you can use the static parseInt() method in the Integer class as follows: int intValue = Integer.parseInt(intString); where intString is a numeric string such as “123”. 52 Converting Strings to Doubles To convert a string into a double value, you can use the static parseDouble method in the Double class as follows: double doubleValue =Double.parseDouble(doubleString); where doubleString is a numeric string such as “123.45”. 53 Displaying Text in a Message Dialog Box Instead of using System.out.println() for console output you can use the showMessageDialog method in the JOptionPane class. JOptionPane is one of the many predefined classes in the Java system, which can be reused rather than “reinventing the wheel.” 54 The showMessageDialog Method JOptionPane.showMessageDialog(null, "Welcome to Java!", "Display Message", JOptionPane.INFORMATION_MESSAGE); DEMO program: Open file ProgDialogBoxes.java 55 Exercise on statements Write a Java program as a single class: • single method main() to include: • program segment to calculate the greatest common divisor of two positive integer values • program segment to calculate the factorial of a nonnegative integer value • program segment to calculate the sum of integer numbers in range from n1…n2, such that n1<n2 56 Components of a Java program Methods & Classes • To be discussed in lesson 3. Java Programming: From Problem Analysis to Program Design, 3e 57 Data Collections Typical popular Data collections: • Arrays Detailed discussion on arrays follows Java Programming: From Problem Analysis to Program Design, 3e 58 Declaring and creating arrays Similar to C# • Example for array objects: int[] myArray; // declaration • This declares myArray to be an array reference variable • It does not create an array — it only provides a place to put a reference of an array, i.e. address of an array. • Notice that the size is not part of the type myArray = new int[10]; // creation • The new int[10] creates the array of size 10 • Write as int[] myArray = new int[10]; 5/3/2017 // combined Assoc. Prof. Stoyan 59 Bonev An array’s size is not part of its type • When you declare an array, you declare its type; you must not specify its size – Example:String[] names; – orString names[];//not recommended • When you create the array, you allocate space; you must specify its size – Example: names = new String[50]; • This is true even when the two are combined. Example: String[] names = new String[50]; 5/3/2017 Assoc. Prof. Stoyan 60 Bonev Arrays of objects • Suppose you declare and create an array of objects: – Person[] people = new Person[20]; • You have created an array named people, but you have not yet given values to each element in that array • There is nothing wrong with this array, but – it has 20 references to Persons in it – all of these references are initially null – you have not yet defined 20 Persons – For example, people[12].name will give you a nullPointerException if you do not define the Persons. 5/3/2017 Assoc. Prof. Stoyan 61 Bonev Here’s one way to initialize an array of objects: Person[] people = new Person[20]; for (int i = 0; i < people.length; i++) { people[i] = new Person(“John"); } This approach has a slight drawback: all the array elements have similar values! Remember: index of array elements starts at 0 and ends at (length – 1) 5/3/2017 Assoc. Prof. Stoyan 62 Bonev Resizing an array The following is legal: int[] myArray = new int[10]; ...and later in the program, myArray = new int[500]; // legal! This is legal because the array’s size is not part of its type, but part of its value 5/3/2017 Assoc. Prof. Stoyan 63 Bonev Length of an array • Arrays are objects. • Every array has an instance constant, length, that tells how large the array is • Example: for (int i = 0; i < scores.length; i++) System.out.println(scores[i]); • Use of length is always preferred over using a literal constant such as 10 • Arrays have a length variable, • Strings have a length() method 5/3/2017 Assoc. Prof. Stoyan 64 Bonev • There is a special syntax for giving initial values to the elements of arrays – This syntax can be used in place of new type[size] – It can only be used in an array declaration – The syntax is: { value, value, ..., value } • Examples: int[] primes = { 2,3,5,7,11,13,19}; String[] languages = { "Java","C","C++" }; 5/3/2017 Assoc. Prof. Stoyan 65 Bonev Initializing arrays • To initialize an array of Person: Person[] people = { new Person(“Elena"), new Person(“Ivan"), new Person(“Katya"), new Person(“Dimitar") }; • Notice that you do not specify the size of the array 5/3/2017 Assoc. Prof. Stoyan 66 Bonev Arrays - Recap • Declare an array ref variable: – int[] counts; – String[] names; – int[][] matrix; //this is an array of arrays • Create an array and assign its reference to array ref variable: – counts = new int[5]; – names = new String[100]; – matrix = new int[5][10]; • Use: – String months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"}; 5/3/2017 – for(int i = 0; i < months.length; i++) System.out.println("month: " + months[i]); Assoc. Prof. Stoyan 67 Bonev Array assignment • Array assignment is object assignment: • Object assignment does not copy values Person p1; Person p2; p1 = new Person(“Ivan"); p2 = p1; // p1 and p2 refer to same person (“point to”) • Array assignment does not copy values int[] a1; int[] a2; a1 = new int[10]; a2 = a1; // a1 and a2 refer to the same array 5/3/2017 Assoc. Prof. Stoyan 68 Bonev Copying Arrays Often, in a program, you need to duplicate an array or a part of an array. In such cases you could attempt to use the assignment statement (=), as follows: list2 = list1; Before the assignment list2 = list1; list1 After the assignment list2 = list1; Contents of list1 list2 list1 list2 Contents of list2 Garbage Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 5/3/2017 Contents of list1 Contents of list2 45 Assoc. Prof. Stoyan 69 Bonev Copying Arrays Using a loop: int[] srcArray = {2, 3, 1, 5, 10}; int[] targetArray = new int[srcArray.length]; for (int i = 0; i < srcArrays.length; i++) targetArray[i] = srcArray[i]; 5/3/2017 Assoc. Prof. Stoyan 70 Bonev Arrays of arrays Arrays of arrays Or Multi – Dimensional arrays 5/3/2017 Assoc. Prof. Stoyan 71 Bonev Arrays of arrays = Multidimensional arrays • One-dimensional arrays are used to store linear collections of elements, i.e. vector. • Two-dimensional arrays are used to store a matrix or a table. • A two-dimensional array is one-dimensional array in which each element is another one-dimensional array. (look fwd after 7 slides) • A multidimensional array is an array in which each element is another array 5/3/2017 Assoc. Prof. Stoyan 72 Bonev Arrays of arrays = Multidimensional arrays • A three-dimensional array consists of an array of twodimensional arrays, each of which is an array of onedimensional arrays. int[][][] x = new int[2][2][5]; • x[0] and x[1] are two-dimensional arrays. • x[0][0], x[0][1], x[1][0], x[1][1] are one-dimensional arrays and each contains 5 elements • x.length is 2 • x[0].length and x[1].length are 2 • x[0][0].length, x[0][1].length, x[1][0].length, x[1][1].length are 5 5/3/2017 Assoc. Prof. Stoyan 73 Bonev Arrays of arrays • The elements of an array can be arrays. • Declaration: int[][] table; • Definition: table = new int[10][15]; • Combined: int[][] table = new int[10][15]; • The first index (10) is called the row index; • The second index (15) is the column index 5/3/2017 Assoc. Prof. Stoyan 74 Bonev Example array of arrays • int[][] table = new int[3][2]; or, • int[][] table = { {1, 2}, {3, 6}, {7, 8} }; An array of three rows and two columns • For example, table[1][1] contains 6 • table[2][1] contains 8, and 0 1 1 3 2 7 0 5/3/2017 1 • table[1][2] is “array out of bounds” 2 6 • To “zero out this table”: 8 for (int i = 0; i < 3; i++) for (int j = 0; j < 2; j++) table[i][j] = 0; Assoc. Prof. Stoyan 75 Bonev Declaring Variables of 2-D Arrays and Creating 2D Arrays // Declare array ref var dataType[][] refVar; // Create array & assign its reference to variable refVar = new dataType[10][10]; // Combine declaration and creation in one stmt dataType[][] refVar = new dataType[10][10]; // Alternative syntax, not recommended dataType refVar[][] = new dataType[10][10]; 5/3/2017 Assoc. Prof. Stoyan 76 Bonev Declaring Variables of 2-D Arrays and Creating 2-D Arrays // declare array ref var, create 2D array and assign its reference to array ref var // all three above activities in one step - statement int[][] matrix = new int[10][10]; matrix[0][0] = 3; for (int i = 0; i < matrix.length; i++) for (int j = 0; j < matrix[i].length; j++) matrix[i][j] = (int)(Math.random() * 1000); // matrix.length – numr of rows or matrix capacity // matrix[i].length – capacity of row nmr i 5/3/2017 Assoc. Prof. Stoyan 77 Bonev Two-dimensional Array Illustration 0 1 2 3 4 0 1 2 3 4 0 2 0 0 0 1 1 1 4 2 2 2 7 8 9 3 3 10 11 12 4 4 matrix = new int[5][5]; 7 matrix[2][1] = 7; 3 1 2 3 5 6 int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; matrix.length? 5 array.length? 4 matrix[0].length? 5 array[0].length? 3 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 5/3/2017 1 6 Assoc. Prof. Stoyan 78 Bonev Lengths of Two-dimensional Arrays int[][] x = new int[3][4]; x x[0][0] x[0][1] x[0][2] x[0][3] x[0].length is 4 x[1][0] x[1][1] x[1][2] x[1][3] x[1].length is 4 x[2][0] x[2][1] x[2][2] x[2][3] x[2].length is 4 x[0] x[1] x[2] x.length is 3 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 5/3/2017 8 Assoc. Prof. Stoyan 79 Bonev Ragged Arrays Each row in a two-dimensional array is itself an array. So, the rows can have different lengths. Such an array is known as a ragged array. For example, int[][] matrix = { {1, 2, 3, 4, 5}, matrix.length is 5 {2, 3, 4, 5}, matrix[0].length is 5 {3, 4, 5}, matrix[1].length is 4 {4, 5}, matrix[2].length is 3 matrix[3].length is 2 {5} matrix[4].length is 1 }; 5/3/2017 Assoc. Prof. Stoyan 80 Bonev Associative Arrays import java.util.Hashtable; … // associative array - special case – hashtable Hashtable<String, String> ht = new Hashtable<String, String>(); ht.put("Sofia", "BG"); ht.put("Berlin", "DE"); System.out.print(" " + ht.get("Sofia")); 5/3/2017 Assoc. Prof. Stoyan 81 Bonev The ArrayList and Vector Classes You can create an array to store objects. But the array’s size is fixed once the array is created. Java provides the ArrayList class that can be used to store an unlimited number of objects. java.util.ArrayList +ArrayList() Creates an empty list. +add(o: Object) : void Appends a new element o at the end of this list. +add(index: int, o: Object) : void Adds a new element o at the specified index in this list. +clear(): void Removes all the elements from this list. +contains(o: Object): boolean Returns true if this list contains the element o. +get(index: int) : Object Returns the element from this list at the specified index. +indexOf(o: Object) : int Returns the index of the first matching element in this list. +isEmpty(): boolean Returns true if this list contains no elements. +lastIndexOf(o: Object) : int Returns the index of the last matching element in this list. +remove(o: Object): boolean Removes the element o from this list. +size(): int Returns the number of elements in this list. +remove(index: int) : Object Removes the element at the specified index. +set(index: int, o: Object) : Object 5/3/2017 Sets the element at the specified index. Assoc. Prof. Stoyan 82 Bonev ArrayList demo example package sbarraylist; import java.util.ArrayList; public class SBArrayList { public static void main(String[] args) { ArrayList ar = new ArrayList(); ar.add("Sofia"); ar.add("Varna"); System.out.println(ar.toString()); for (int i=ar.size()-1; i>=0; i--) System.out.print(ar.get(i) +" "); } } 5/3/2017 Assoc. Prof. Stoyan 83 Bonev Practical tasks . 5/3/2017 Assoc. Prof. Stoyan 84 Bonev Initializing arrays with input values java.util.Scanner input = new Scanner(System.in); System.out.println("Enter " + matrix.length + " rows and " + matrix[0].length + " columns: "); for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { matrix[row][column] = input.nextInt(); } } 5/3/2017 Assoc. Prof. Stoyan 85 Bonev Initializing arrays with random values for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { matrix[row][column] = (int)(Math.random() * 100); } } 5/3/2017 Assoc. Prof. Stoyan 86 Bonev Printing arrays for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { System.out.print(matrix[row][column] + " "); } System.out.println(); } 5/3/2017 Assoc. Prof. Stoyan 87 Bonev Summing all elements int total = 0; for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { total += matrix[row][column]; } } 5/3/2017 Assoc. Prof. Stoyan 88 Bonev Summing elements by column for (int column = 0; column < matrix[0].length; column++) { int total = 0; for (int row = 0; row < matrix.length; row++) total += matrix[row][column]; System.out.println("Sum for column " + column + " is " + total); } 5/3/2017 Assoc. Prof. Stoyan 89 Bonev Demo programs - Example // Package Declaration import java.lang.*; // not required // Program start class public class HelloWorld { // Main begins program execution public static void main(string[] args) { // This is a single line comment /* This is a multiple line comment */ System.out.println("Hello World!"); } } 90 import java.util.*; public class test11 { public static void main(String[] args) { System.out.println("Hello, it’s: "); System.out.println(new Date()); } } 91 Demo Programs Demonstrate end-of-file controlled loop using standard input from the keyboard and standard output to the screen Solution to implement in a version: as console application Problem: To accumulate sum of stream of input integers terminated by end-of-data (CTRL/Z) indicator 92 Demo Program – Source Code // Java demo program, standard Input (keyboard) / Output (screen) // Class Scanner (Import java.util.Scanner;) // Methods next(), nextInt(), nextFloat(), nextDouble(), nextLine(), hasNext() import java.util.Scanner; public class Main { public static void main(String[] args) { int sum=0, arg; Scanner cin = new Scanner(System.in); while (cin.hasNext()) { sum += cin.nextInt(); } System.out.println("Final sum = " + sum); } } 93 Thank You For Your Attention! 94