79
Introduction to Java Subject Code CSE-404E

Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Embed Size (px)

Citation preview

Page 1: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Introduction to Java

Subject Code CSE-404E

Page 2: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Welcome to the First class of

Session Jan 2007-April 2007

Page 3: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Topics to be covered

• Introduction to Java,

• Data Types,

• Variables,

• Operators,

• Control Statements,

• Arrays

Page 4: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

A Versatile Plate form

• Applications– Enterprise based Applications– Hubble space telescope monitoring– Mars Pathfinder Mission simulator– Office packages (Star Office /open office)– Web Based Application (JSP/Servlets/Applets)

Page 5: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Features• C++ syntaxes simplified• Cross Plate form• Automatic Memory Management

– No dangling pointers– No memory leaks

• Simplified pointer handling– No reference/de reference operations

• No Make files/header files• Object Oriented• Rich with Powerful standard library

Page 6: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Java’s Features Cont.

• Java’s Hybrid Approach:Compiler + Interpreter– A java compiler converts Java Source code into

instructions for the java Virtual machine– These instructions, called byte codes, are the

same for any computer/operating system– A CPU specific java interpreter interprets byte

codes on a particular computer

Page 7: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Why Bytecodes ?

• Plate form Independent• Load from the internet faster than source code• A semi compiled java code is available for

interpreter which has been debugged as well, at the compile time.

• Interpreter is faster and smaller than it would be for java source

• Source code is not revealed to end users• Interpreter performs additional security checks,

screen out machine code

Page 8: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

JDK- Java Development Kit

• Javac– Java compiler

• Java– Java interpreter

• Appletviewer– Tests applets without a browser

• Javadoc– Generates HTML documentation (“docs”) from source

• Jar– Package classes into jar files(packages)

All these are command line tools

Page 9: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Java Tools Contd…ajar This tool is an alternative interface to the jar tool

appletviewer Allows to run applets without a browser

Apt Processes program annotations

Extcheck Detects the version conflicts between a target JAR file and currently installed JAR file

Idlj Generates the java bindings from a given IDL file

Jar Combines multiple files into single jar file

Jarsigner Signs jar files and verifies signatures on signed JAR files

javah Facilitates implementation of java native methods

Javadoc Generates API documentation

Page 10: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Java Tools Contd…javap Class file disassembler

RMI Tools Rmic,rmiregistry,rmid,serialver

Deployment tools Pack200,unpack200

Javaw Runs programs as a windows native application

Security tools Keytool,jarsigner,policytool,kinit,klist,ktab

Jdb Java debugger

Plug-in tools htmlconverter

Monitoring and management tools

Jconsole,jps,jstat,jstatd

Troubleshooting tools

Jinfo, jmap, jstack

Page 11: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Types of Java Programs

• Command line based Console applications

• GUI based applications

• Network based application

• Web based application– Applets– Servlets– JSP

Page 12: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Java Versions

• Java 1.0 released in 1995• Java 1.1 released in 1997

– A new event handling model based on listeners– RMI and object serialization– Support for inner and anonymous classes– Arbitrary precision integers and floating-point numbers– JDBC API for connecting to RDBMSs– Java Beans Component architecture( an answer to ActiveX)– Digitally signed applets to extend security privileges without

resorting to the all or nothing model of browser plug-ins or active x

Page 13: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Java Versions Cont…

• Java2 Version released in Dec. 1998(JDK 1.2)– Swing GUI components based on 100% pure java– Java 2D for professional, high-quality, two dimensional

graphics and imaging– The collections framework supporting advanced data

structures like linked lists, trees, and sets– Audio enhancements to support .wav, .au, .midi,

and .rm file formats– Printing of graphic objects– Java IDL API, which adds CORBA capability to java

Page 14: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

limat-cse.tripod.comJava Contd.

• JDK 1.3 released in Spring of 2000– Major Enhancements

• Java Naming and Directory Interface (JNDI)- A directory service for registering and looking up resources (objects)

• RMI IIOP- a protocol to communicate wit distributed clients that are written in CORBA complient language

• JDK 1.4 released in spring 2002– Major Enhancements

• XML Processing• Logging in API• Assertions• Next Generation I/O (java.nio)• SSL• JAAS- authentication and authorization API

Page 15: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Java 2 Plateform, Enterprise Edition

• Focused at E-commerce solutions– Java Servlets and JSP- Sun’s Answer to Microsoft ASP– EJB for bundling business logic in server side

components– JDBC data access for scrollable db queries(result sets)– JavaMail to send/receive mail with SMTP,POP3 or

IMAP protocols– JAXP for parsing XML components– Java Message Service for asynchronous communication

between enterprise applications

Page 16: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Getting Started: Installation

• The latest release of java can be downloaded from sun.java.com

• The requisite java version can be easily installed by executing the downloaded program

• The installation should append the path and class path information in the environmental variable.

Page 17: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Getting Started: Writing a java program

• A java program can be written using any of the following environments in case of Microsoft windows– Edit/Notepad (provided With all versions/variants of

Windows)– Jcreator (can be downloaded free/commercial edition after

payment)– Edit Plus(can be downloaded free/commercial edition after

payment)– Eclipse (can be downloaded free/commercial edition after

payment)– Kawa (available commercially in market)

Page 18: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Getting Started: First Program

Public class HelloWorld {

public static void main(String args[]) {

System.out.println(“Welcome to java programming”);

}

}

Save the program as HelloWorld.java

Page 19: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Getting started: compiling and running on DOS prompt

• Compile the program by– Javac HelloWorld.java

• Execute/run the program by – Java HelloWorld

• Output– Welcome to java programming

Page 20: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Command-Line Arguments

C:\javamethods\Ch02> javac Greetings.javaC:\javamethods\Ch02> java Greetings Ramesh Kumar

Hello, Josephine Jaworski

public class Greetings{ public static void main(String[ ] args) { String firstName = args[ 0 ]; String lastName = args[ 1 ]; System.out.println("Hello, " + firstName + " " + lastName); }}

Command-line arguments are passed to mainas an array of Strings.

Page 21: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Data Types

• byte- 8 bits – 1 byte• short –16 bits –2 byte• int –32 bits – 4 byte• long –64 bits –8 byte• float-32 bits –4 bytes• Double – 64 bits –8 bytes• char –16 bits – 2 bytes• boolean – 1 bit

Java Integer Types

Floating point Types

Page 22: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Data Type Casting

The process of converting one data type to another is called casting. It is necessary when a function returns a type different than the type you need to perform an operation. E.g.

char c = (char) System.in.read();

Care should be taken while casting to ensure that there is no information loss

Page 23: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Access Modifiers

• Access modifiers define varying levels of access between class members and the outside world( Other objects).

• For types of Access modifiers– default– public– protected– private

Page 24: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Relational Operators

<, >, <=, >=, = =, !=

is equal to

is NOT equal to

Page 25: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Logical Operators

&&, ||, !

and

or

not

Page 26: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

enum Data Types

• Used when an object’s attribute or state can have only one of a small set of values,for example:

• enum variables do not represent numbers, characters, or strings.

private enum Speed { LOW, MEDIUM, HIGH };

private enum InkColor { BLACK, RED };

private enum DayOfWeek { sunday, monday, tuesday, wednesday, thursday, friday, saturday };

Page 27: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

enum Data Types (cont’d)• Use == or != to compare enum values

• Can be used in a switch:

private enum Speed { LOW, MEDIUM, HIGH }; ... Speed currentSpeed = Speed.LOW; ... if (currentSpeed == Speed.LOW) ...

switch (currentSpeed) { case LOW: ... break; case MEDIUM: ...

Page 28: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Strings

• String is not a primitive data type

• Strings work like any other objects, with two exceptions:– String in double quotes are recognized as literal

constants– + and += concatenate strings ( or a string and a

number or an object, which is converted into a string)

Page 29: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Literal Constants

'A', '+', '\n', '\t'

-99, 2010, 0

0.75, -12.3, 8., .5

“coin.gif", "1776", "y", "\n"

new line

tab

char

int

double

String

Page 30: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Symbolic Constants

• Symbolic constants are initialized final variables:

private final int stepLength = 48;

private static final int BUFFER_SIZE = 1024;

public static final int PIXELS_PER_INCH = 6;

Page 31: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Arithmetic

• Operators: +, -, /, * , %

• The precedence of operators and parentheses is the same as in algebra

• m % n means the remainder when m is divided by n (for example, 17 % 5 is 2;

2 % 8 is 2)

• % has the same rank as / and *• Same-rank binary operators are performed

in order from left to right

Page 32: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Arithmetic (cont’d)

• The type of the result is determined by the types of the operands, not their values; this rule applies to all intermediate results in expressions.

• If one operand is an int and another is a double, the result is a double; if both operands are ints, the result is an int.

Page 33: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Arithmetic (cont’d)

• The type of the result is determined by the types of the operands, not their values; this rule applies to all intermediate results in expressions.

• If one operand is an int and another is a double, the result is a double; if both operands are ints, the result is an int.

Page 34: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Arithmetic (cont’d)• To get the correct double result, use double

constants or the cast operator: double ratio = 2.0 / 3;

double ratio = 2 / 3.0;

int m = ..., n = ...;

double factor = (double)m / (double)n;

double factor = (double)m / n;

double r2 = n / 2.0;

Casts

Page 35: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Arithmetic (cont’d)

• A cast to int can be useful:

int ptsOnDie = (int)(Math.random() * 6) + 1;

int miles = (int)(km * 1.61 + 0.5);

Returns a double

Converts kilometers to miles, rounded to the nearest integer

Page 36: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Arithmetic (cont’d)

• Caution: the range for ints is from -231 to 231-1 (about -2·109 to 2·109)

• Overflow is not detected by the Java compiler or interpreter:n = 8 10^n = 100000000 n! = 40320n = 9 10^n = 1000000000 n! = 362880n = 10 10^n = 1410065408 n! = 3628800n = 11 10^n = 1215752192 n! = 39916800n = 12 10^n = -727379968 n! = 479001600n = 13 10^n = 1316134912 n! = 1932053504n = 14 10^n = 276447232 n! = 1278945280

Page 37: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Arithmetic (cont’d)

• Compound assignment operators:

a = a + b; a += b;

a = a - b; a -= b;

a = a * b; a *= b;

a = a / b; a /= b;

a = a % b; a %= b;

• Increment and decrement operators:

a = a + 1; a++;

a = a - 1; a--;

Do not use these in larger expressions

Page 38: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

From Numbers to Strings• The easiest way to convert x into a string is to

concatenate x with an empty string:

String s = x + "";

• The same rules apply to System.out.print(x)

'A'

123

-1

.1

3.14

Math.PI

"A"

"123"

"-1"

"0.1"

"3.14"

"3.141592653589793"

Empty string

Page 39: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Control Statemetns: If-else

if ( <condition> ){ < statements >}else{ < other statements >}

if ( <condition> ){ < statements >}

else clause is optional

Page 40: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Control Statement: Switchswitch

(expression){

case value1: ...

break;

case value2: ...

break; ... ... default: ... break;}

Don’t forget breaks!

switch casedefaultbreak

Reserved words

Page 41: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

The switch Statement (cont’d)

• The same case can have two or more labels. For example:

switch (num){

case 1:case 2: System.out.println ("Buckle your shoe");

break; case 3: ...}

Page 42: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Control Structure : while loop

while ( condition ) { statement1; statement2; ... statementN; }

while ( condition ) statement1;

If the body has only one statement, the braces are optional

condition is any logical expression,

as in if

The body of the loop

Page 43: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

// Returns the smallest n // such that 2^n >= x public static int intLog2 (int x) { int n = 0, p = 1;

while ( p < x ) { p *= 2; n++; } return n; }

The while Loop (cont’d)

• Example:

Initialization

Testing

Change

Page 44: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Control Structure The for Loop

• for is a shorthand that combines in one statement initialization, condition, and change:

for ( initialization; condition; change ) { statement1; statement2; ... statementN; }

Page 45: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

// Returns the smallest n // such that 2^n >= x public static int intLog2 (int x) { int n = 0;

for (int p = 1; p < x; p *= 2) { n++; } return n; }

The for Loop (cont’d)

• Example:

Initialization

Testing

Change

The scope of p is the body of the loop, and p is undefined outside the loop

Page 46: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Control Structure :The do-while Loop

do { statement1; statement2; ... statementN; } while ( condition );

The code runs through the body of the loop at least once

Always use braces for readability (even if the body has only one statement)

if condition is false, the next iteration is not executed

Page 47: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

The do-while Loop (cont’d)

• do-while is convenient when the variables tested in the condition are calculated or read in the body of the loop:

String str;

do { str = file.readLine(); ... } while (str != null);

Page 48: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

The do-while Loop (cont’d)

• do-while can be easily avoided: we can usually replace it with a while loop initialized so that it goes through the first iteration:

String str = "dummy";

while (str != null) { str = file.readLine(); ... }

Page 49: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

•break in a loop instructs the program to immediately quit the current iteration and go to the first statement following the loop.

•return in a loop instructs the program to immediately quit the current method and return to the calling method.

•A break or return must be inside an if or an else, otherwise the code after it in the body of the loop will be unreachable.

•A continue statement causes the control to jump out of the current iteration of the loop

Break, continue and return in Loops

Page 50: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

break in Loops

• Example:

int d = n - 1;

while (d > 0) { if (n % d == 0) break; d--; }

if ( d > 0 ) // if found a divisor ...

Page 51: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

break in Loops

• Example:

int d = n - 1;

while (d > 0) { if (n % d == 0) break; d--; }

if ( d > 0 ) // if found a divisor ...

Page 52: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Arrays

Page 53: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

What is an Array• An array is a block of consecutive memory

locations that hold values of the same data type.

• Individual locations are called array’s elements.

• When we say “element” we often mean the value stored in that element.

1.39

1.69

1.74

0.0

An array of doubles

Page 54: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

What is an Array (cont’d)• Rather than treating each element as a

separate named variable, the whole array gets one name.

• Specific array elements are referred to by using array’s name and the element’s number, called index or subscript.

c[0] c[1] c[2] c[3]

1.39

1.69

1.74

0.0 c is array’s

name

Page 55: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Indices (Subscripts)

• In Java, an index is written within square brackets following array’s name (for example, a[k]).

• Indices start from 0; the first element of an array a is referred to as a[0] and the n-th element as a[n-1].

• An index can have any int value from 0 to array’s length - 1.

Page 56: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Indices (cont’d)

• We can use as an index an int variable or any expression that evaluates to an int value. For example:

a [3] a [k] a [k - 2] a [ (int) (6 * Math.random()) ]

Page 57: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Indices (cont’d)• In Java, an array is declared with fixed

length that cannot be changed.

• Java interpreter checks the values of indices at run time and throws ArrayIndexOutOfBoundsException if an index is negative or if it is greater than the length of the array - 1.

Page 58: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Why Do We Need Arrays?• The power of arrays comes from the fact

that the value of a subscript can be computed and updated at run time.

int sum = 0;sum += score0;sum += score1;…sum += score999;

No arrays:

int n = 1000;int sum = 0, k;

for (k = 0; k < n; k++) sum += scores[k];

With arrays:

1000times!

Page 59: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Why Arrays? (cont’d)

• Arrays give direct access to any element — no need to scan the array.

if (k == 0) display (score0);else if (k == 1) display (score1);else … // etc.

display (scores[k]);1000times!

No arrays: With arrays:

Page 60: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Arrays as Objects• In Java, an array is an object. If the type of

its elements is anyType, the type of the array object is anyType[ ].

• Array declaration:anyType [ ] arrName;

Page 61: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Arrays as Objects (cont’d)

• As with other objects, the declaration creates only a reference, initially set to null. An array must be created before it can be used.

• One way to create an array: arrName = new anyType [length] ; Brackets,

not parens!

Page 62: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Declaration and Initialization• When an array is created, space is allocated

to hold its elements. If a list of values is not given, the elements get the default values. For example:

scores = new int [10] ;

words = new String [10000];

length 10, all values set to 0

length 10000, all values set to null

Page 63: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Initialization (cont’d)

• An array can be declared and initialized in one statement. For example:

int [ ] scores = new int [10] ;

private double [ ] gasPrices = { 3.05, 3.17, 3.59 };

String [ ] words = new String [10000];

String [ ] cities = {"Atlanta", "Boston", "Cincinnati" };or int scores[] = new int [10];

String words[] = new String [10000];

Page 64: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

String [ ] words;

... words = new String [ console.readInt() ];

private double[ ] gasPrices; … gasPrices = new double[ ] { 3.05, 3.17, 3.59 };

Initialization (cont’d)

• Otherwise, initialization can be postponed until later. For example:

Not yet initialized

Not yet initialized

Page 65: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Array’s Length

• The length of an array is determined when that array is created.

• The length is either given explicitly or comes from the length of the {…} initialization list.

• The length of an array arrName is referred to in the code as arrName.length.

• length is like a public field (not a method) in an array object.

Page 66: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Initializing Elements

• Unless specific values are given in a {…} list, all the elements are initialized to the default value: 0 for numbers, false for booleans, null for objects.

• If its elements are objects, the array holds references to objects, which are initially set to null.

• Each object-type element must be initialized before it is used.

Page 67: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Initializing Elements (cont’d)

• Example: Color[ ] pens; ... pens = new Color [ 3 ]; ... pens [0] = Color.BLUE; pens [1] = new Color (15, 255, 255); pens [2] = g.getColor();

Now all three elements are initialized

Array is created; all three elements are set to null

Array not created yet

Page 68: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Passing Arrays to Methods

• As other objects, an array is passed to a method as a reference.

• The elements of the original array are not copied and are accessible in the method’s code. // Swaps a [ i ] and a [ j ]

public void swap (int [ ] a, int i, int j) { int temp = a [ i ]; a [ i ] = a [ j ]; a [ j ] = temp; }

Page 69: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Returning Arrays from Methods

• As any object, an array can be returned from a method.

• The returned array is usually constructed within the method or obtained from calls to other methods.

• The return type of a method that returns an array with someType elements is designated as someType[ ].

Page 70: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Returning Arrays from Methods (cont’d)

public double[ ] solveQuadratic (double a, double b, double c) { double d = b * b - 4 * a * c; if (d < 0) return null;

d = Math.sqrt(d);

double[ ] roots = new double[2]; roots[0] = (-b - d) / (2*a); roots[1] = (-b + d) / (2*a); return roots; }

Or simply:

return new double[ ] { (-b - d) / (2*a), (-b + d) / (2*a) };

Page 71: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Two Dimension Arrays

Page 72: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Two-Dimensional Arrays

• 2-D arrays are used to represent tables, matrices, game boards, images, etc.

• An element of a 2-D array is addressed using a pair of indices, “row” and “column.” For example:

board [ r ] [ c ] = 'x';

Page 73: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

2-D Arrays: Declaration

// 2-D array of char with 5 rows, 7 cols:char[ ] [ ] letterGrid = new char [5][7];

// 2-D array of Color with 1024 rows, 768 cols:Color[ ] [ ] image = new Color [1024][768];

// 2-D array of double with 2 rows and 3 cols:double [ ] [ ] sample = { { 0.0, 0.1, 0.2 }, { 1.0, 1.1, 1.2 } };

Page 74: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

2-D Arrays: Dimensions

• In Java, a 2-D array is basically a 1-D array of 1-D arrays, its rows. Each row is stored in a separate block of consecutive memory locations.

• If m is a 2-D array, then m[k] is a 1-D array, the k-th row.

• m.length is the number of rows.• m[k].length is the length of the k-th row.

Page 75: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Dimensions (cont’d)

• Java allows “ragged” arrays, in which different rows have different lengths.

• In a rectangular array, m[0].length can be used to represent the number of columns.

“Ragged” array: Rectangular array:

m.length

m[3].length m[0].length

m.length

Page 76: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

2-D Arrays and Nested Loops

• A 2-D array can be traversed using nested loops:

for (int r = 0; r < m.length; r++) { for (int c = 0; c < m[0].length; c++) { ... // process m[ r ][ c ] } }

Page 77: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

“Triangular” Loops

• “Transpose a matrix” idiom: int n = m.length;

for (int r = 1; r < n; r++) { for (int c = 0; c < r; c++) { double temp = m [ r ][ c ]; m [ r ][ c ] = m [ c ][ r ]; m [ c ][ r ] = temp; } }

The total number of iterations through the inner loop is:

1 + 2 + 3 + ... + n-1 =n (n - 1) / 2

Page 78: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Questions ?

Page 79: Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007

Thank You