0% found this document useful (0 votes)
68 views79 pages

Introduction To Java: Subject Code CSE-404E

The document provides an introduction to the Java programming language. It discusses topics that will be covered in the CSE-404E session from January to April 2007, including data types, variables, operators, control statements, and arrays. It also describes Java features such as object-oriented programming, automatic memory management, and the Java Development Kit (JDK) tools.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views79 pages

Introduction To Java: Subject Code CSE-404E

The document provides an introduction to the Java programming language. It discusses topics that will be covered in the CSE-404E session from January to April 2007, including data types, variables, operators, control statements, and arrays. It also describes Java features such as object-oriented programming, automatic memory management, and the Java Development Kit (JDK) tools.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 79

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

Javas Features Cont.


Javas 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 appletviewer Apt This tool is an alternative interface to the jar tool Allows to run applets without a browser Processes program annotations

Extcheck
Idlj Jar Jarsigner javah

Detects the version conflicts between a target JAR file and currently installed JAR file Generates the java bindings from a given IDL file
Combines multiple files into single jar file Signs jar files and verifies signatures on signed JAR files Facilitates implementation of java native methods

Javadoc

Generates API documentation

Java Tools Contd


javap RMI Tools Class file disassembler Rmic,rmiregistry,rmid,serialver

Deployment tools Pack200,unpack200


Javaw Security tools Jdb Plug-in tools Runs programs as a windows native application Keytool,jarsigner,policytool,kinit,klist,ktab Java debugger htmlconverter

Monitoring and Jconsole,jps,jstat,jstatd management tools Troubleshooting Jinfo, jmap, jstack tools

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.com Java 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- Suns 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.java C:\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 + " } }

Command-line arguments are passed to main as an array of Strings. " + lastName);

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 objects attribute or state can have only one of a small set of values, for example:
private enum Speed { LOW, MEDIUM, HIGH };

private enum InkColor { BLACK, RED };


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

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

enum Data Types (contd)


Use == or != to compare enum values
private enum Speed { LOW, MEDIUM, HIGH }; ... Speed currentSpeed = Speed.LOW; ... if (currentSpeed == Speed.LOW) ...

Can be used in a switch:


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
new line tab

'A', '+', '\n', '\t' -99, 2010, 0

char

int
double String

0.75, -12.3, 8., .5


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

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 (contd)
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 (contd)
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 (contd)
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 (contd)
A cast to int can be useful:
Returns a double

int ptsOnDie = (int)(Math.random() * 6) + 1; int miles = (int)(km * 1.61 + 0.5);


Converts kilometers to miles, rounded to the nearest integer

Arithmetic (contd)
Caution: the range for ints is from -231 to 231-1 (about -2109 to 2109)

Overflow is not detected by the Java compiler or interpreter:


n n n n n n n = = = = = = = 8 9 10 11 12 13 14 10^n 10^n 10^n 10^n 10^n 10^n 10^n = = = = = = = 100000000 1000000000 1410065408 1215752192 -727379968 1316134912 276447232 n! n! n! n! n! n! n! = 40320 = 362880 = 3628800 = 39916800 = 479001600 = 1932053504 = 1278945280

Arithmetic (contd)
Compound assignment Increment and operators: decrement operators: a = a + b; a = a - b; a += b; a -= b; a = a + 1; a = a - 1; a++; a--;

a = a * b; a = a / b; a = a % b;

a *= b; a /= b; a %= b;

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: Empty string String s = x + "";
'A' 123 -1
.1 3.14 Math.PI

"A" "123" "-1"


"0.1" "3.14" "3.141592653589793"

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

Control Statemetns: If-else


if ( <condition> ) { < statements > } else { < other statements > } if ( <condition> ) { < statements > }
else clause is optional

Control Statement: Switch


switch (expression) { case value1: ... break;

switch case default break


Reserved words

case value2: ... break; ... ... default: ... break;


}

Dont forget breaks!

The switch Statement (contd)


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; } If the body has only one statement, the braces are optional condition is any logical expression, as in if

The body of the loop

while ( condition ) statement1;

The while Loop (contd)


Example:
// 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; }

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

The for Loop (contd)


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

Initialization

Testing for (int p = 1; p < x; p *= 2) { Change n++; } return n; 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 ); Always use braces for readability (even if the body has only one statement)

The code runs through the body of the loop at least once
if condition is false, the next iteration is not executed

The do-while Loop (contd)


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


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, continue and return in Loops


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 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 arrays 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 (contd)


Rather than treating each element as a separate named variable, the whole array gets one name. Specific array elements are referred to by using arrays name and the elements number, called index or subscript.
1.39 c[0]

1.69
c[1]

1.74
c[2]

0.0 c[3]

c is arrays name

Indices (Subscripts)
In Java, an index is written within square brackets following arrays name (for example, a[k]). Indices start from 0; the first element of an array a is referred to as a[0] and the nth element as a[n-1]. An index can have any int value from 0 to arrays length - 1.

Indices (contd)
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 (contd)
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.
No arrays: With arrays:

1000 times!

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

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


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

Why Arrays? (contd)


Arrays give direct access to any element no need to scan the array.
No arrays: if (k == 0) display (score0); else if (k == 1) display (score1); else // etc. With arrays: display (scores[k]);

1000 times!

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


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: length 10,
scores = new int [10] ;
words = new String [10000];
all values set to 0

length 10000, all values set to null

Initialization (contd)
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];

Initialization (contd)
Otherwise, initialization can be postponed until later. For example:
String [ ] words;
Not yet initialized

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


private double[ ] gasPrices; initialized gasPrices = new double[ ] { 3.05, 3.17, 3.59 };
Not yet

Arrays 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 (contd)


Example:
Color[ ] pens; Array is created; ... all three elements pens = new Color [ 3 ]; are set to null ... pens [0] = Color.BLUE; Now all three pens [1] = new Color (15, 255, 255); elements are pens [2] = g.getColor();
initialized 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 methods 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 (contd)


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 (contd)
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: m.length Rectangular array: m.length

m[3].length

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy