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

Preview:

Citation preview

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

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)

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

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

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

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

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

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

Types of Java Programs

• Command line based Console applications

• GUI based applications

• Network based application

• Web based application– Applets– Servlets– JSP

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

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

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

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

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.

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)

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

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

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.

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

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

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

Relational Operators

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

is equal to

is NOT equal to

Logical Operators

&&, ||, !

and

or

not

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 };

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: ...

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)

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

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;

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

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.

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.

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

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

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

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

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

Control Statemetns: If-else

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

if ( <condition> ){ < statements >}

else clause is optional

Control Statement: Switchswitch

(expression){

case value1: ...

break;

case value2: ...

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

Don’t forget breaks!

switch casedefaultbreak

Reserved words

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: ...}

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

// 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

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; }

// 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

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

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);

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(); ... }

•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

break in Loops

• Example:

int d = n - 1;

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

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

break in Loops

• Example:

int d = n - 1;

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

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

Arrays

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

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

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.

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()) ]

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.

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!

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:

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;

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!

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

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];

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

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.

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.

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

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; }

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[ ].

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) };

Two Dimension Arrays

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';

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 } };

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.

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

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 ] } }

“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

Questions ?

Thank You

Recommended