Lesson 2 The Java Prog Lan AUBG ICoSCIS Team Assoc. Prof. Stoyan Bonev March, 23 - 24, 2013 SWU,...
-
Upload
eustace-logan -
Category
Documents
-
view
214 -
download
0
description
Transcript of Lesson 2 The Java Prog Lan AUBG ICoSCIS Team Assoc. Prof. Stoyan Bonev March, 23 - 24, 2013 SWU,...
Lesson 2The Java Prog Lan
AUBG ICoSCIS TeamAssoc. Prof. Stoyan Bonev
March, 23 - 24, 2013 SWU, Blagoevgrad
Time Schedule
March 23, Saturday - March 24, Sunday– 10:00 – 10:45 09:00 – 09:45– 11:00 – 11:45 10:00 – 10:45– 12:00 – 12:45 11:00 – 11:45
Lunch Break (45’) Lunch Break (45’)– 13:30 – 14:15 12:30 – 13:15– 14:30 – 15:15 13:30 – 14:15– 15:30 – 16:15 14:30 – 15:15
Lesson ContentsOverview 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
4 4
The Basics of a Java ProgramJava program: collection of classes. Classes
capsulated as packages – named or unnamedPackage: collection of related classesClass: collection of data items and methods Method: designed to accomplish a specific taskThere 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
5 5Java Programming: From Problem Analysis to Program Design, 4e
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, 3e 66Java Programming: From Problem Analysis to Program Design, 4e
Anatomy of a Java program: Sample source text
Sample Run:
05/05/23 Assoc. Prof. Stoyan Bonev
7
Comments
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.
Three types of comments in Java.
Java Programming: From Problem Analysis to Program Design, 3e 8
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 9
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 10
Reserved WordsReserved 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.
ModifiersJava 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 1111Java Programming: From Problem Analysis to Program Design, 4e
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, 3e 1212Java Programming: From Problem Analysis to Program Design, 4e
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, 3e 1313Java Programming: From Problem Analysis to Program Design, 4e
Values and Memory Allocation for Integral Data Types
Java Programming: From Problem Analysis to Program Design, 3e 1414Java Programming: From Problem Analysis to Program Design, 4e
Primitive Data Types
• Classified by Category as:• Literals• Named Constants• Variables
Java Programming: From Problem Analysis to Program Design, 3e 1515Java Programming: From Problem Analysis to Program Design, 4e
Literals (Constants)• Integer literals, integer constants, or integers:
23 -67 +4470177 0x1a
• Floating-point literals, floating-point constants, floating-point numbers: 12.34 +25.60 -3.15 5. .1663.14e-2 2.78e+3 5.23e4
• Character literals, character constants, or characters: 'a' '5' '+' '\n'
Java Programming: From Problem Analysis to Program Design, 3e 1616Java Programming: From Problem Analysis to Program Design, 4e
Named Constants• Named constant
– Cannot be changed during program execution– Declared by using the reserved word final– Initialized when it is declared
• Example:final double CENTIMETERS_PER_INCH = 2.54;final int NO_OF_STUDENTS = 20;final char BLANK = ' ';final double PAY_RATE = 15.75;
Java Programming: From Problem Analysis to Program Design, 3e 1717Java Programming: From Problem Analysis to Program Design, 4e
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 amountDue;int counter;char ch;int num1, num2;
Java Programming: From Problem Analysis to Program Design, 3e 18
Declaring and Initializing Variables int first; OR int
first = 13; first = 13;
char ch; OR char ch = ‘E’; ch = ‘E’;
double value; OR double value = 35.68; value = 35.68;
-------------------------------------------------------------
Java Programming: From Problem Analysis to Program Design, 3e 19
Unicode FormatJava 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 20
(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 21
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 2222Java Programming: From Problem Analysis to Program Design, 4e
Arithmetic Operators and Operator Precedence
• 1. * / % (same precedence)• 2. + - (same precedence)
• 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
Java Programming: From Problem Analysis to Program Design, 3e 2323Java Programming: From Problem Analysis to Program Design, 4e
Mixed Arithmetic Expressions• Operands of different types• Examples2 + 3.56 / 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, 3e 2424Java Programming: From Problem Analysis to Program Design, 4e
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, 3e 25
Conversion RulesWhen 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 26
Type CastingImplicit 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;
byte, short, int, long, float, double
range increases
Java Programming: From Problem Analysis to Program Design, 3e 27
Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
Logical Operators
Operator Name
! not
&& and
|| or
^ exclusive or
Conditional Operator
y = (x > 0) ? 1 : -1;
Java Programming: From Problem Analysis to Program Design, 3e 2828Java Programming: From Problem Analysis to Program Design, 4e
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, 3e 2929Java Programming: From Problem Analysis to Program Design, 4e
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, 3e 3030Java Programming: From Problem Analysis to Program Design, 4e
Types of statements
• Declaration/definition statements
• Executable statements
• Every statement in Java ends with a semicolon (;).
Java Programming: From Problem Analysis to Program Design, 3e 31
BlocksA 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 3232Java Programming: From Problem Analysis to Program Design, 4e
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, do-
while, for(version foreach)• Input/Output
– Other break, continue
Java Programming: From Problem Analysis to Program Design, 3e 33
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 tovariable *= expression;Similarly,variable = variable + (expression);is equivalent tovariable += expression;
Java Programming: From Problem Analysis to Program Design, 3e 34
One-way if Statements
Boolean Expression
true
Statement(s)
false (radius >= 0)
true
area = radius * radius * PI; System.out.println("The area for the circle of " + "radius " + radius + " is " + area);
false
(A) (B)
if (boolean-expression) { statement(s);}
if (radius >= 0) { area = radius * radius * PI; System.out.println("The area" + " for the circle of radius " + radius + " is " + area);}
Java Programming: From Problem Analysis to Program Design, 3e 3512Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
The Two-way if Statementif (boolean-expression) {
statement(s)-for-the-true-case;}else {
statement(s)-for-the-false-case;}
Boolean Expression
false true
Statement(s) for the false case Statement(s) for the true case
Java Programming: From Problem Analysis to Program Design, 3e 36
if...else Exampleif (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 37
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 38
44Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
switch Statement Flow Chart
status is 0 Compute tax for single filers break
Compute tax for married file jointly break status is 1
Compute tax for married file separatly break status is 2
Compute tax for head of household break status is 3
Default actions default
Next Statement
Java Programming: From Problem Analysis to Program Design, 3e 39
Introducing while Loopsint count = 0;while (count < 100) { System.out.println("Welcome to Java"); count++;}
6Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
while Loop Flow Chartwhile (loop-continuation-condition) {
// loop-body;
Statement(s);
}
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java!");
count++;
}
Loop Continuation Condition?
true
Statement(s) (loop body)
false (count < 100)?
true
System.out.println("Welcome to Java!"); count++;
false
(A) (B)
count = 0;
Java Programming: From Problem Analysis to Program Design, 3e 40
1Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
do-while Loop
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
Loop Continuation Condition?
true
Statement(s) (loop body)
false
Java Programming: From Problem Analysis to Program Design, 3e 41
21Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
for Loopsfor (initial-action; loop-
continuation-condition; action-after-each-iteration) {
// loop body;Statement(s);
}
int i;for (i = 0; i < 100; i++) {System.out.println(
"Welcome to Java!"); }
Loop Continuation Condition?
true Statement(s) (loop body)
false
(A)
Action-After-Each-Iteration
Initial-Action
(i < 100)?
true System.out.println( "Welcome to Java");
false
(B)
i++
i = 0
Java Programming: From Problem Analysis to Program Design, 3e 42
For-loop
For (int i=1, j=10; i < j; i++, j-=2)
System.out.println("i="+i+" j="+j);
for (int i = 0; i < 4; i++){ for( char letter = 'A'; letter <= 'A' + i; letter++) System.out.print(letter); System.out.println();}
i=1 j=10i=2 j=8i=3 j=6
AABABCABCD
Java Programming: From Problem Analysis to Program Design, 3e 43
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 4444Java Programming: From Problem Analysis to Program Design, 4e
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, 3e 4545Java Programming: From Problem Analysis to Program Design, 4e
Input (Read) statementstatic 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(); //Line 1Inches = cin.nextInt(); //Line 2
• How to read a single character:– char ch; ch = console.next().charAt(0);
Java Programming: From Problem Analysis to Program Design, 3e 46
Reading Input from the Console1. 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 47
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 4848Java Programming: From Problem Analysis to Program Design, 4e
Output (Write/Print/Display) statement
• Standard output object: System.out• Methods
printprintln
• SyntaxSystem.out.print(stringExp);System.out.println(stringExp);
System.out.println();
Java Programming: From Problem Analysis to Program Design, 3e 4949Java Programming: From Problem Analysis to Program Design, 4e
Input/Output using Dialog Boxes
Java Programming: From Problem Analysis to Program Design, 3e 50
JOptionPane InputTwo 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;
51
Getting Input from Input Dialog Boxes String input = JOptionPane.showInputDialog( "Enter an input");
52
Converting Strings to IntegersThe 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”.
53
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”.
54
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.”
55
The showMessageDialog Method JOptionPane.showMessageDialog(null, "Welcome to Java!", "Display Message", JOptionPane.INFORMATION_MESSAGE);
DEMO program: Open file ProgDialogBoxes.java
56
Exercise on statementsWrite 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
Java Programming: From Problem Analysis to Program Design, 3e 57
Components of a Java programMethods & Classes
• To be discussed in lesson 3.
Java Programming: From Problem Analysis to Program Design, 3e 58
Data Collections
Typical popular Data collections:
• Arrays
Detailed discussion on arrays follows
05/05/23 Assoc. Prof. Stoyan Bonev
59
Declaring and creating arrays
• 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]; // combined
Similar to C#
05/05/23 Assoc. Prof. Stoyan Bonev
60
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;– or String 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];
05/05/23 Assoc. Prof. Stoyan Bonev
61
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.
05/05/23 Assoc. Prof. Stoyan Bonev
62
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)
05/05/23 Assoc. Prof. Stoyan Bonev
63
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
05/05/23 Assoc. Prof. Stoyan Bonev
64
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
05/05/23 Assoc. Prof. Stoyan Bonev
65
• 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++" };
05/05/23 Assoc. Prof. Stoyan Bonev
66
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
05/05/23 Assoc. Prof. Stoyan Bonev
67
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"};
– for(int i = 0; i < months.length; i++) System.out.println("month: " + months[i]);
05/05/23 Assoc. Prof. Stoyan Bonev
68
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
05/05/23 Assoc. Prof. Stoyan Bonev
69
45Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
Copying ArraysOften, 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;
Contents of list1
list1
Contents of list2
list2
Before the assignment list2 = list1;
Contents of list1
list1
Contents of list2
list2
After the assignment list2 = list1;
Garbage
05/05/23 Assoc. Prof. Stoyan Bonev
70
Copying ArraysUsing 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];
05/05/23 Assoc. Prof. Stoyan Bonev
71
Arrays of arrays
Arrays of arraysOr
Multi – Dimensional arrays
05/05/23 Assoc. Prof. Stoyan Bonev
72
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
05/05/23 Assoc. Prof. Stoyan Bonev
73
Arrays of arrays = Multidimensional arrays
• A three-dimensional array consists of an array of two-dimensional arrays, each of which is an array of one-dimensional 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
05/05/23 Assoc. Prof. Stoyan Bonev
74
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
05/05/23 Assoc. Prof. Stoyan Bonev
75
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
1 23 67 8
0 10
12
• For example, table[1][1] contains 6• table[2][1] contains 8, and• table[1][2] is “array out of bounds”
• To “zero out this table”: for (int i = 0; i < 3; i++) for (int j = 0; j < 2; j++) table[i][j] = 0;
05/05/23 Assoc. Prof. Stoyan Bonev
76
Declaring Variables of 2-D Arrays and Creating 2-D Arrays
// Declare array ref vardataType[][] refVar;
// Create array & assign its reference to variablerefVar = new dataType[10][10];
// Combine declaration and creation in one stmtdataType[][] refVar = new dataType[10][10];
// Alternative syntax, not recommendeddataType refVar[][] = new dataType[10][10];
05/05/23 Assoc. Prof. Stoyan Bonev
77
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
05/05/23 Assoc. Prof. Stoyan Bonev
78
6Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
Two-dimensional Array Illustration
0 1 2 3 4 0
7
0 1 2 3 4
1 2 3 4
0 1 2 3 4 matrix[2][1] = 7;
matrix = new int[5][5];
3
7
0 1 2 0 1 2
int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} };
1
2
3
4
5
6
8
9
10
11
12
array.length? 4
array[0].length? 3
matrix.length? 5
matrix[0].length? 5
05/05/23 Assoc. Prof. Stoyan Bonev
79
8Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
Lengths of Two-dimensional Arrays
x
x[0]
x[1]
x[2]
x[0][0] x[0][1] x[0][2] x[0][3] x[1][0] x[1][1] x[1][2] x[1][3] x[2][0] x[2][1] x[2][2] x[2][3]
x.length is 3
x[0].length is 4
x[1].length is 4
x[2].length is 4
int[][] x = new int[3][4];
05/05/23 Assoc. Prof. Stoyan Bonev
80
Ragged ArraysEach 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}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5}};
matrix.length is 5 matrix[0].length is 5 matrix[1].length is 4 matrix[2].length is 3 matrix[3].length is 2 matrix[4].length is 1
05/05/23 Assoc. Prof. Stoyan Bonev
81
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"));
05/05/23 Assoc. Prof. Stoyan Bonev
82
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() +add(o: Object) : void +add(index: int, o: Object) : void +clear(): void +contains(o: Object): boolean +get(index: int) : Object +indexOf(o: Object) : int +isEmpty(): boolean +lastIndexOf(o: Object) : int +remove(o: Object): boolean +size(): int +remove(index: int) : Object +set(index: int, o: Object) : Object
Appends a new element o at the end of this list. Adds a new element o at the specified index in this list. Removes all the elements from this list. Returns true if this list contains the element o. Returns the element from this list at the specified index. Returns the index of the first matching element in this list. Returns true if this list contains no elements. Returns the index of the last matching element in this list. Removes the element o from this list. Returns the number of elements in this list. Removes the element at the specified index. Sets the element at the specified index.
Creates an empty list.
05/05/23 Assoc. Prof. Stoyan Bonev
83
ArrayList demo examplepackage 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) +" ");
}
}
05/05/23 Assoc. Prof. Stoyan Bonev
84
Practical tasks.
05/05/23 Assoc. Prof. Stoyan Bonev
85
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(); }}
05/05/23 Assoc. Prof. Stoyan Bonev
86
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); }}
05/05/23 Assoc. Prof. Stoyan Bonev
87
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();}
05/05/23 Assoc. Prof. Stoyan Bonev
88
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]; }}
05/05/23 Assoc. Prof. Stoyan Bonev
89
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);}
90
// Package Declarationimport 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!"); } }
Demo programs - Example
91
import java.util.*;
public class test11 {
public static void main(String[] args) {
System.out.println("Hello, it’s: ");
System.out.println(new Date());
}
}
92
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
93
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); }}
94
Thank You For
Your Attention!