Sie sind auf Seite 1von 104

Objectives

Origins of Java Features of Java

Concept of Java Virtual Machine


Characters and Character Set of Java Tokens (keywords, identifiers etc.) in Java

Keyword class, function main()

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Introduction to Java
A language developed by Sun Microsystems A general-purpose language

High-level language
Developed initially for consumer devices Popular platform to develop enterprise applications
Finds use in internet based applications

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Origins of Java
C and C++ have limitations in reliability and portability. e.g. size of data types. Java was developed by removing the sources of problems in C and C++ like pointers, multiple inheritance, array bounds etc. Milestones in history of Java 1990 Sun microsystems started developing the language to manipulate consumer electronic devices. It took 18 months to develop first working version. 1991 This language was named as Oak 1992 Demonstration of application to control home appliances 1993 Development in www. Transformation of text based internet into graphical-rich environment. Project on web applets that could run on all types of computers on internet. 1994 Development of web browser HotJava to run applets. Language became popular among internet users. 1995 Oak was renamed as Java. Netscape, Microsoft etc. announced support. 1996- JDK 1.0, 1997- JDK 1.1, 1998- SDK1.2, 1999- J2SE, J2EE, 2000- SDK 1.3, 2002- SDK 1.4, 2004- J2SE 5.0
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Features of Java (1/2)


Object-oriented All program code and data reside within objects and classes Simpler language Compared to earlier OO languages like C++, it is simple Designed considering the pitfalls of earlier languages Robust Provides many safeguards to ensure reliable code. - Example : Strict compile time and runtime checking for data types.

- Provides Exception handling, Garbage collection


Architecture Neutral / Portable (Platform independent) Example: Java code compiled on Windows can be run on Unix without

recompilation

Dynamic and extensible- Dynamic linking of class libraries. Supports functions written in other languages (native methods).
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Features of Java (2/2)


Secure Secured for programming on internet. Ensures no viruses are

communicated with an applet


Built -in security features like absence of pointers secures memory access and confines of the java program within its runtime environment

Support for Multithreading at language level Programs can be written to


handle multiple tasks simultaneously. Designed to handle Distributed applications Java is designed for creating

applications distributed on networks. It can share both data and programs. This
enables multiple programmers at multiple locations to work together on a single project.
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Platform independence
Java is a language that is platform independent. A platform is the hardware and software environment in which a program runs Once compiled, code will run on any platform without recompiling or any kind of modification.
Write Once Run Anywhere

This is made possible by making use of a Java Virtual Machine commonly known as JVM

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Java Virtual Machine (JVM) (1/2)


The source code of Java will be stored in a text file with extension .java The Java compiler compiles a .java file into byte code

The byte code will be in a file with extension .class


In most other languages like C and C++, the output of the compiler will be in the machine code of the underlying platform But, the .class file that is generated by the Java compiler is NOT in the machine code of the underlying platform

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Java Virtual Machine (JVM) (2/2)


The byte code is interpreted by the JVM JVM can be considered as a processor purely implemented with software.

The interface that the JVM has to the .class file remains the same irrespective
of the underlying platform.
This makes platform independence possible

The JVM interprets the .class file to the machine language of the underlying
platform. The underlying platform processes the commands given by the JVM

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Java Architecture:

JVM

Source File (HelloWorld.java)

Class Loader

Byte Code Verifier

Compiler (javac)

Interpreter

JIT Code Generator

Runtime Machine Code or Byte code (HelloWorld.class)

Operating System

Hardware

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Installing and using Java


Before we begin, something on installation
Java 2 SDK (v1.4 or higher) Can be downloaded freely from http://java.sun.com Also available in the intranet

Setting Environment variables for Java Environment Variable:


A variable that describes the operating environment of the process
Common environment variables describe the home directory, command search path etc.

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Environment variables used by JVM


JAVA_HOME: Java Installation directory
This environment variable is used to derive all other env. variables used by JVM In Windows: set JAVA_HOME=C:\jdk1.4.3 In UNIX: export JAVA_HOME=/var/usr/java

CLASSPATH
In Windows: set PATH=%PATH%;%JAVA_HOME%\lib\tools.jar;. In UNIX: set PATH=$PATH:$JAVA_HOME/lib/tools.jar:.

PATH
Path variable is used by OS to locate executable files In Windows: set PATH=%PATH%;%JAVA_HOME%\bin In UNIX: set PATH=$PATH:$JAVA_HOME/bin

This approach helps in managing multiple versions of Java Changing JAVA_HOME will reflect on CLASSPATH and PATH as well Set these environment variables on the command prompt and type javac
Displays all the options of using javac
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Source File Layout - Hello World


We will have the source code first Type this into any text editor
public class HelloWorldApp {

public static void main(String[]args){


System.out.println(Hello World!); } }

Save this as HelloWorldApp.java Important :


Take care!! cAsE of file name matters

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

To Compile
Open a command prompt Set Environment variables (explained earlier)

Go to the directory in which you have saved your program.


Type javac HelloWorldApp.java
If it says bad command or file name then check the path setting

If it does not say anything, and you get the prompt, then the compilation was
successful.

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

To execute
Type in the command prompt java HelloWorldApp

The result

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Compilation & Execution


Java Program (.java)

Java Complier (javac)

Byte Code (.class file)

Interpreter (java)

Interpreter (java)

Interpreter (java)

Win 32

Linux

Mac

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Best Practices
One .java file must contain only one class declaration The name of the file must always be same as the name of the class

Stand alone Java program must have a public static void main defined
It is the starting point of the program Not all classes require public static void main

Code should be adequately commented Must follow indentation and coding standards

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Java Character Set


Unicode character set 16-bit character coding system

Supports characters from large number of scripts worldwide


We will use basic ASCII character set ( a subset of UNICODE ) consisting of letters, digits and punctuation marks used in English.

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Java Tokens
Java program is a collection of tokens, comments and white spaces Tokens are of five types

- Reserved keywords
- Identifiers - Literals

- Operators
- Separators

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Java Keywords (For Reference Only)


The reserved keywords defined in the Java language
abstract boolean break byte case catch char class true const continue float default do double else extends final finally for if import false interface long goto new
Copyright 2005, Infosys Technologies Ltd

implements instanceof null int return package private protected native


#

public throw short super switch


synchronized

this transient void volatile while

static try throws


ER/CORP/CRS/LA10SC/003 Version 1.00

Identifiers - Programmer designed tokens

- cannot begin with digits


- can be of any length - can contain alphabets, digits and underscores (spaces are not allowed)

- uppercase and lowercase letters are distinct


Examples : abc, Number1, Student_Name are three valid identifiers 1Sum, emp name are two invalid identifiers

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Literals They are constants (represent constant values) Five types of literals

- Integer literals
- Floating point literals - Character literals

- String literals
- Boolean literals Operators It is a symbol that takes arguments Example Arithmetic operators are + - / * etc. Separators Symbols used to indicate where groups of code are divided Example - ( ) { } [ ] , ; .
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Comment entry in Java


A single line comment in Java will start with //
// This is a single line comment in Java

A multi line comment starts with a /* and ends with a */


/* This is a multi line comment in Java */

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Data Types in Java


Integer data types
byte (1 byte) short (2 bytes) int (4 bytes) long (8 bytes)

Notes:
All numeric data types are signed The size of data types remain the same on all platforms (standardized) char data type in Java is 2 bytes because it uses UNICODE character set. By virtue of it, Java supports internationalization UNICODE is a character set which covers all known scripts and language in the world

Floating Type
float (4 bytes)
double (8 bytes)

Textual
char (2 bytes)

Logical
boolean (1 byte) (true/false)

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Variables in Java
Using primitive data types is similar to other languages
int count; //Declaration count = 10; //Assignment operation

int max = 100; //Declaration and Initialization

In Java variables can be declared anywhere in the program


for (int count=0; count < max; count++) {

int z = count * 10;


}

BEST PRACTICE: Declare a variable in program only when required. Do not declare variables upfront like in C.
In Java, if a local variable is used without initializing it, the compiler will show an error

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Give it a try.
What will be the output of the following code snippet when you try to compile and run it?

class Sample{ public static void main (String args[]){ int count; System.out.println(count); } }

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Typecasting of primitive data types


Automatic, non-explicit type changing is known as Conversion
Variable of smaller capacity can be assigned to another variable of bigger capacity int i = 10; double d; d = i;

Whenever a larger type is converted to a smaller type, we have to explicitly specify the type cast operator
double d = 10 int i; i = (int) d; This prevents accidental loss of data
Type cast operator

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Operators and Assignments


Arithmetic Operators: Assignment Operator: Relational Operators: Boolean Logical operators: Binary : + - * / % = < <= > >= && || ?: ! == != Unary : + -

The ternary / Conditional Operator:

Other Special operators : Increment operator ++ Decrement operator -Compound assignment operators += The Bitwise operators: & ! ^ ~ -= << *= >> /= >>> %=

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Evaluation of Arithmetic Expressions


int a=10, b=5, c=2, d=3; a-b*c+d will be evaluated as 10-5*2+3 = 10-10+3 = 0+3 = 3 Since * has higher precedence, multiplication will be done first. Addition and subtraction will be performed from left to right as per the appearance of the operators. Operators with same precedence are evaluated from left to right as per the appearance of the operators. Parentheses can be used to overcome the normal hierarchy (a-b)*(c+d) will be evaluated as (10-5)*(2+3) = 5 * 5 = 25 Expressions in Parenthesis will be evaluated first. a-b*c/d will result into 10-5*2/3 = 10 -10/3 = 10-3 (decimal part will be ignored) = 7
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Integer and floating point arithmetic


In integer arithmetic, part after decimal point will be neglected If result is required in real number, at least one operand should be real number

in the division.
If left hand side variable of the assignment statement is integer, the though the right hand side expression is resulting into real number, decimal part will be truncated while assigning the value. e.g. Consider the following assignment statement : avg = (m1+m2+m3) / 3.0 ; where avg, m1, m2, m3 are int

avg will be assigned integer value and decimal part evaluated in right hand side value will be ignored. If avg is float or double, decimal part will be stored.

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Relational operators
Following are the relational operators in java with sequence of precedence and meaning as given : < less than <= less than or equal to > greater than >= greater than or equal to == equal to != not equal to A simple relational expression contains a relational operator with one operand on each side left and right as follows exp1 relational-operator exp2 where exp1 and exp2 are arithmetic expressions which may be variables, constants or combination of them. The arithmetic expressions will be evaluated first and then the results will be compared to return true or false. e.g. (5+2) > (10-4) will return true a==b will return false if value of variable a is not equal to value of variable b
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Logical Operators
Following are the logical operators in java with their precedence, symbols and meanings as given Symbol Meaning ! NOT (Logical complement operator) && AND || OR They are used to form combination of conditions / relational expressions e.g. a>b && a>c A logical expression results in value true or false according to the truth table as Operand1 Operand2 && || ! true true true true !(true) is false true false false true !(false) is true false true false true e.g. !(5>2) is true false false false false The ! (Not) operator will invert the logical value of the operand next to it.
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Increment / Decrement Operators


++ Increment operator; increments a value by 1 -- Decrement operator; decrements a value by 1

Can be used as prefix or postfix with the operand. e.g. a++


Example a=5;

++a

b=a++;
Here b will be assigned value of a as 5 and then value of a will be incremented by 1. Hence after execution, b will hold value 5 and a will hold 6. But if a=5; b=++a;

then after execution, b will hold value 6 and a will hold value 6
because pre-increment will increment the value first and then will assign

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Shorthand / Compound Assignment Operators


+= -= *= /= %= are Shorthand / Compound Assignment Operators a+=5

a=a+5

can be written as

b=b-2
m=m*n

can be written as
can be written as

b-=2
m*=n

and so on

It has following advantages

What appears on left-hand side need not be repeated and becomes easy to write
The statement is more concise and easier to read Use of shorthand operator results in a more efficient code

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

The Conditional / Ternary Operator


It is combination of ? And : and takes three operands in the following form: Conditional expression ? expression1 : expression2

The conditional expression is evaluated first. If the result is true, expression1 is


evaluated and is returned as the value of the conditional expression. Otherwise, expression2 is evaluated and its value is returned. Example : flag = (x>10) ? (2*x - 5) : (2*x + 10)

value of flag will be 2*x-5 if x is greater than 10, otherwise flag will be 2*x + 10 Though this is equivalent to an ifelse statement, the limitation is that there can be only one statement each in the form of expression1 and expression2. Whereas in ifelse, we can have any number of statement in if block and else block. Advantage of ? : is that it is more concise to understand.

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Operator Precedence
Operators Postfix Unary Multiplicative Additive Shift Relational Equality logical AND logical OR Ternary Assignment Precedence expr++ expr ++expr --expr +expr -expr ~ ! * / % + << >> >>> < > <= >= instanceof == != && || ?: = += -= *= /= %=

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Control Statements
The syntax of the control statements in Java are very similar to those of C language
if
if-else for while do-while switch break continue

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Java Control statements control the order of execution in a java program, based on data values and conditional logic. There are three main categories of

control flow statements;


Selection statements: Loop statements: if, if-else and switch. while, do-while and for.

Transfer statements:

break, continue, return, try-catch-finally and assert.

We use control statements when we want to change the default sequential order of execution

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

if Statement
The if statement executes a block of code only if the specified expression is true. If the value is false, then the if block is skipped and execution continues

with the rest of the program. You can either have a single statement or a block
of code (enclosed in curly braces) within an if statement. Note that the conditional expression must be a Boolean expression. The simple if statement has the following syntax: if (<conditional expression>) <statement action> Example : int a = 10, b = 20; if (a > b) System.out.println("a > b");

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

if else Statement
The if/else statement is an extension of the if statement. If the condition in the if statement fails (is false), the statements in the else block are executed. You can either have a single statement or a block of code within if-else blocks. Note

that the conditional expression must be a Boolean expression.


The if-else statement has the following syntax: if (<conditional expression>) <statement action> else <statement action> Example : int a = 10, b = 20; if (a > b) System.out.println("a > b"); else System.out.println("b > a");
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

switch case Statement


Switch Case Statement The switch case statement, also called a case statement is a multi-way branch with several choices. A switch is easier to implement than a series of if/else statements. The switch statement begins with a keyword switch, followed by an

expression that equates to a non-long integral value. Following the controlling expression
is a code block that contains zero or more labeled cases. Each label must equate to an integer constant and each must be unique. When the switch statement executes, it compares the value of the controlling expression to the values of each case label. The program will select the value of the case label that equals the value of the controlling expression and branch down that path to the end of the code block (until it finds a break statement). If none of the case label values match, then none of the codes within the switch statement code block will be executed. Java includes a default label to use in cases where there are no matches. We can have a nested switch within a case block of an outer switch.
ER/CORP/CRS/LA10SC/003 Version 1.00

Copyright 2005, Infosys Technologies Ltd

switch case Statement


The general form of switch case statement is switch(control_expression) {

case expression1:
<statement>; case expression2: <statement>;

...
... case expression_n: <statement>;

default:
<statement>; } // end switch
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Comparison between if else and switch


A switch statement is equivalent to multiple if statements or nested if statements.

In switch statement only integer expressions are allowed for condition and
case. If you want to test on real number value, you cannot use switch. You cannot have specification of range for a particular case. For example, if you want to execute a block for the value of range between 1 to 100, another block for the value of range between 101 to 150 etc., switch is not suitable, you should use if. If the application is suitable for switch-case, then switch-case will be more

efficient than the equivalent if-else codes. It will also look more precise and
easy to understand the logic.

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Looping / Iteration / Repetition Statements


while loop : The while statement is a looping construct control statement that executes a

block of code while a condition is true. You can either have a single statement
or a block of code within the while loop. The loop will never be executed if the testing expression evaluates to false. The loop condition must be a boolean expression. The body of the loop is executed repeatedly until the condition becomes false i.e. every time before the iteration, the condition is checked and the body is executed only if condition is true. The syntax of the while loop is

while (<loop condition>)


< statements > // i.e. body of the loop

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Example of while loop


Below is an example that demonstrates the looping construct namely while loop used to print numbers from 1 to 10 :

int count = 1; System.out.println("Printing Numbers from 1 to 10");

while (count <= 10)


{ System.out.println(count++);

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

do while loop
The do-while loop is similar to the while loop, except that the test is performed at the end of the loop instead of at the beginning. This ensures that the loop will be executed at least once (even if the condition is false). A do-while loop begins with the keyword do, followed by the statements that make up the body of the loop. Finally, the keyword while and the test expression completes the do-while loop. When the loop condition becomes false, the loop is terminated and execution continues with the statement immediately

following the loop. You can either have a single statement or a block of code within the
do-while loop. The syntax of the do-while loop is do <loop body> while (<loop condition>);

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Example of do-while loop


Below is an example that demonstrates the looping construct namely do-while loop used to print sum of numbers from 1 to 10.

int count = 1, sum = 0 ; do {

sum += count ; // i.e. sum = sum + count


count++; } while (count <= 10);

System.out.println(Sum of Numbers from 1 to 10 is + sum);

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

for loop
The for loop is a looping construct which can execute a set of instructions a specified number of times. Its a counter controlled loop. The syntax of the loop is as follows: for (<initialization>; <loop condition>; <increment/decrement expression>) { loop body } The first part of a for statement is a starting initialization, which executes once before the loop begins. The <initialization> section can also be a comma-separated list of expression statements. The second part of a for statement is a test expression. As long as the expression is true, the loop will continue. If this expression is evaluated as false the first time, the loop will never be executed. The third part of the for statement is the body of the loop. These are the instructions that are repeated each time the program executes the loop. The final part of the for statement is an increment expression that automatically executes after each repetition of the loop body. Typically, this statement changes the value of the counter, which is then tested to see if the loop should continue.
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Example of for loop


Below is an example that demonstrates the looping construct namely for loop used to print numbers from 1 to 10.

System.out.println("Printing Numbers from 1 to 10");


for (int count = 1; count <= 10; count++) {

System.out.println(count);
}

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Additional features of for loop


All the sections in the for-header are optional. Any of them can be left empty, but the two semicolons are mandatory. In particular, leaving out the <loop condition> signifies that the loop condition is true. The ( ; ; ) form of for loop is

commonly used to construct an infinite loop.


More than one variables can be initialized (separated by comma) at a time in the for statement. e.g. count=1, sum=0; //(in the initialization part) A variable can be declared and initialized first time in the for statement. e.g. for ( int i=0; .. ) // i.e. not necessary to declare the variable before.

Like the initialization section, the increment/decrement section may also have more than one part separated by comma. e.g. for ( n=1, m=10; n<m; n++,m--) A compound test condition can be used e.g. for(i=1, i<10 && j>5; ++i) The initialization and increment part can have any arithmetic expression.
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Branching Statements: break and continue


break and continue are used in loops usually combined with an if statement. Break statements:

The break statement transfers control out of the enclosing loop ( for, while, do
or switch statement). You use a break statement when you want to jump immediately to the statement following the enclosing control structure. You can also provide a loop with a label, and then use the label in your break statement. The label name is optional, and is usually only used when you wish to terminate the outermost loop in a series of nested loops. The Syntax for break statement is as shown below; break; // the unlabeled form break <label>; // the labeled form
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Example of break statement


Below is a program to demonstrate the use of break statement to print numbers Numbers 1 to 10.

for (int i = 1; ; ++i)


{ if (i == 11)

break;
// Rest of loop body skipped when i is 11 System.out.println(i + "\t");

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

The continue statement


A continue statement stops the iteration of a loop (while, do or for) and causes execution to resume at the top of the nearest enclosing loop. You use a

continue statement when you do not want to execute the remaining statements
in the loop, but you do not want to exit the loop itself. The syntax of the continue statement is continue; // the unlabeled form continue <label>; // the labeled form You can also provide a loop with a label and then use the label in your continue statement. The label name is optional, and is usually only used when you wish to return to the outermost loop in a series of nested loops.

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Example of continue statement


Below is a program to demonstrate the use of continue statement to print Odd Numbers between 1 to 10.

for (int i = 1; i <= 10; ++i)


{ if (i % 2 == 0)

continue;
// Rest of loop body skipped when i is even System.out.println(i + "\t");

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Nesting of loops
Any type of loop can be nested with the same type of loop or any other type of loop.

Inner loop is a statement in the body of the outer loop.


The inner loop is executed intended number of times (depending on the condition or number of times specified) for every iteration of the outer loop.

If a break statement is used in the inner loop, the control will go to the outer
loop at the place just after the completion of inner loop body. The loops should be properly indented so as to enable the reader to easily

determine which statements are contained within each loop.

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Methods
The syntax of writing a method in Java is similar to that of a function in C language Java being an object oriented language will not permit the user to write a global

function. Any method in Java should be written inside a class


A method has declaration (or header part) (consisting of return type, name of method and parameters) and definition (code inside the definition is executed when that method is called) main() is a special method from which program execution starts Methods may have any number of parameters of any data types or may not have any parameters A Method may return a value or may return void A method can call itself which is called recursion
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Method Overloading (1/3)


Two or more methods in a Java class can have the same name, if they have a difference in the data type of the parameters or number of parameters

This feature is known as Method Overloading


void myPrint(int i){ System.out.println(i); } void myPrint(double d){ System.out.println(d); }

void myPrint(char c){


System.out.println(c); }
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Method overloading (2/3)


Calls to overloaded methods will be resolved during compile time
Also known as static polymorphism

Argument list could differ in


No of parameters Data type of parameters Sequence of parameters

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Method overloading (3/3)


Overloaded methods

void add (int a, int b) void add (int a, float b) void add (float a, int b) void add (int a, int b, float c)

void add (int a, float b) int add (int a, float b)

Not overloading. Compiler error.

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Arrays in Java
An array is a data structure that defines an ordered collection of a fixed number of homogeneous data elements

The size of an array (number of elements in the array) is fixed and cannot
increase to accommodate more elements Any element of the array can be accessed randomly using name of the array

and index of the element


In java, array index starts from 0 (zero) so that index of the last element is (size-1) i.e. one less than the size of the array.

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Creating an array in Java


In Java, all arrays are created dynamically The operator new is used for dynamic memory allocation

The following statement creates an array of 5 integers


new int[5] The above statement returns a reference to the newly created array The concept of references in Java is very similar to that of pointers in C

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Reference variables in Java (1/4)


Reference variables are used in Java to store the references of the objects created by the operator new

Any one of the following syntax can be used to create a reference to an int
array
int x[]; int [] x;

The reference x can be used for referring to any int array


//Declare a reference to an int array int [] x;

//Create a new int array and make x refer to it


x = new int[5];
# ER/CORP/CRS/LA10SC/003 Version 1.00

Copyright 2005, Infosys Technologies Ltd

Reference variables in Java (2/4)


The following statement also creates a new int array and assigns its reference to x

int [] x = new int[5];


In simple terms, reference can be seen as the name of the array

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Reference variables in Java (3/4)


Even though we can think of Java references as C pointers, their usages are different Pointers Printing a pointer will print the address stored in it Pointer arithmetic like incrementing a pointer is valid in the case of a pointer References Printing a reference will NOT print the address of the object referred by it We cannot use arithmetic operators on references

A pointer has to be dereferenced using the * operator to get the value pointed by it

A reference is automatically dereferenced to give the data referred by it and no special operator is required for this

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Reference Types in Java (4/4)


A reference type cannot be cast to primitive type A reference type can be assigned null to show that it is not referring to any object
null is a keyword in Java

int [] x = null;

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Initializing an array in Java


An array can be initialized while it is created as follows int [] x = {1, 2, 3, 4}; char [] c = {a, b, c};

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

The length of an array


Unlike C, Java checks the boundary of an array while accessing an element in it

Java will not allow the programmer to exceed its boundary


If x is a reference to an array, x.length will give you the length of the array So setting up a for loop as follows is very common in Java

for(int i = 0; i < x.length; ++i){ x[i] = 5; }

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Two Dimensional Arrays


Two dimensional arrays are arrays of arrays. To declare a two dimensional array variable, specify additional index using

another set of square brackets.


int [][] x; //x is a reference to an array of int arrays x = new int[3][4]; //Create 3 new int arrays, each having 4 elements //x[0] refers to the first int array, x[1] to the second and so on //x[0][0] is the first element of the first array //x.length will be 3 //x[0].length, x[1].length and x[2].length will be 4

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Example of two dimensional array


Initialiazation : int matrix [2] [3] = {10, 23, 15, 5, 34, 12 } ; OR other way : int matrix [ ] [ ] = { { 10, 23, 15 } , { 5, 34, 12 } }; // here matrix is an array of size 3X3 // To access elements of a two dimensional array : for (int i=0; i<2; i++) { for (int j=0; j<3; j++) { System.out.println ( matrix[i][j] ) ; } } // Assignment : Write a program to add two matrices (same dimension) giving third matrix.
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Classes in Java
The following example shows the syntax of a class in Java
public class Student { private int rollNo; private char grade; public int getRollNo (){ return rollNo; } public void printGrade(){ System.out.println(grade); } }

Data Members (State)

Methods (Behavior)

The main method may or may not be present depending on whether the class
is a starter class

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Access Modifiers private and public


Data members are usually kept private
It is accessible only within the class

The methods which expose the behavior of the object are kept public
However, we can have helper methods which are private

Key features of object oriented programs


Encapsulation (binding of code and data together)
State (data) is hidden and Behavior (methods) is exposed to external world

Access modifiers (public, private etc) will be covered in more details in the later slides

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Creating Objects in Java (1/2)


In Java, all objects are created dynamically The operator new is used for dynamic memory allocation

The following statement creates an object of the class Student


new Student() The above statement returns a reference to the newly created object

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Creating Objects in Java (2/2)


The following statement creates a reference to the class Student
Student s;

The reference s can be used for referring to any object of type Student
//Declare a reference to class Student Student s; //Create a new Student object and make s refer to the object s = new Student();

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Invoking methods in a class


The following statement also creates a new Student object and assigns its reference to s

Student s = new Student();


All the public members of the object can be accessed with the help of the reference

Student s = new Student();


//More statements s.printGrade(); System.out.println(s.getRollNo()); The reference can be seen as the name of an object

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Constructors (1/4)
A constructor is a special method that is called to create a new object Calling the constructor Student s = new Student(); It is not mandatory for the coder to write a constructor for the class If no user defined constructor is provided for a class, compiler initializes member variables to its default values.
numeric data types are set to 0 char data types are set to null character(\0) boolean data types are set to false reference variables are set to null
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Constructors (2/4)
The coder can also write a constructor in a class, if required The user defined constructor is mostly used to initialize the data members of

the objects to some required values


The user defined constructor is called just after the memory is allocated for the object

When writing a constructor, remember that:


it has the same name as the class it does not return a value not even void

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Constructors (3/4)
public class Counter { private int count; public Counter(){ User Defined Constructor

count = 1;
} //Other Methods } In the above example, the user defined constructor initializes count to 1 Counter c = new Counter(); //c.count is initialized to 1

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Constructors (4/4)
The constructor without any parameter is called a default constructor Just like other methods, constructors also can be overloaded
public class Counter { private int count; public Counter(){ count = 1; } public Counter(int x){ count = x; } //Other Methods } Counter c1 = new Counter(); //c1.count is initialized to 1 Counter c2 = new Counter(5); //c2.count is initialized to 5
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Memory Allocation (1/2)


All local variables are stored in a stack These variables are de-allocated as soon as the method terminates in a last in

first out order


All dynamically allocated arrays and objects are stored in heap Since they are stored in a heap, they need not be de-allocated in any specific order The objects in the heap can be garbage collected when their use is over All objects share the memory space of methods whereas each object is allocated different space for class variables. static data members are common to all objects (share same memory space of static data members for all objects)

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Memory Allocation (2/2)


class Student { private int rollNo; private char grade; public void sample(int x){ int y; //More Statements } //More Methods } class Test{ public static void main(String [] args){ Student a; a = new Student(); //More Statements } }

Data members of the class are stored in the heap along with the object. Their lifetime depends on the lifetime of the object

Local variables x and y are stored in the Stack Local variable a is stored in the Stack

Dynamic objects will be stored in the heap


Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Lifetime of objects (1 of 2)
obj1

Student obj1 = new Student(); Student obj2 = new Student();

heap 2

The two Student objects are now living on the heap


-- References: 2
obj2

-- Objects: 2
obj1

Student obj3 = obj2; -- References: 3


obj3 2 1 heap

-- Objects: 2
obj2

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Lifetime of objects (2 of 2)
obj1

obj3 = obj1; -- References: 3


ob3 2 1 heap

-- Objects: 2
obj2

obj2 = null;

-- Active References: 2
obj1

-- null references: 1 -- Reachable Objects: 1


ob3 1 heap

-- Abandoned objects: 1
Null reference obj2

This object can be garbage collected (Can be Removed from memory)

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Garbage Collection
In C language, it is the programmers responsibility to de-allocate memory allocated dynamically
free() function is used to de-allocate

In Java, JVM will automatically do the memory de-allocation


Called Garbage collection However programmer has to ensure that reference to the object is released
If a reference variable is declared within a function, the reference is invalidated soon as the function call ends Other way of explicitly releasing the reference is to set the reference variable to null Setting a reference variable to null means that it is not referring to any object

An object which is not referred by any reference variable is removed from memory by the garbage collector Primitive types are not objects. They cannot be assigned null
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Array of Objects
An array of objects is created as follows Student [] x = new Student[3]; //3 Student references x[0], x[1] and x[2] are created //All 3 references are null for(int i = 0; i < x.length; ++i){ x[i] = new Student(); //Creating Student object }

for(int i = 0; i < x.length; ++i){


System.out.println(x[i].getRollNo()); }

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Object as Method Arguments and Return Types (1/3)


Objects and arrays can be passed to a method by passing their references as arguments

Similarly, they can be returned from a method by returning their references

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Object as Method Arguments and Return Types (2/3)


Class Complex{

private float real; private float imaginary; Complex add(Complex x){ Complex z = new Complex(); z.real = real + x.real; z.imaginary = imaginary + x.imaginary; return z; } public void read(){ //Read real and imaginary //from the keyboard }
}

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Object as Method Arguments and Return Types (3/3)


Complex a = new Complex(); Complex b = new Complex(); a.read(); b.read(); Complex c = a.add(b); //The object referred by b is passed to the method add

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Parameter Passing Techniques


Java supports only pass by value When an object is passed to a method, the reference variable is passed by value public void swap(String s1, String s2){ String temp; temp = s1; s1 = s2; s2 = temp; } The above method when invoked as swap(x, y), the Strings x and y will NOT

get really swapped as s1 will be just of copy of x and s2 that of y

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

The static keyword


The static keyword can be used in 3 scenarios:
For class variables

For methods
For a block of code

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Static Data Members (1/2)


When designing some classes, we may want a data member that is common for the entire class Consider a class Student with data members Roll No, Grade and Total Number

of Students
The data member that holds the total number of students is common to the entire class

Such data members are called static data members


public class Student { private int rollNo; private char grade; private static int total; //Other methods }
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

The static variable is initialized to 0, ONLY when the class is first loaded, NOT each time a new instance is made

Static Data Members (2/2)


Static Variable It is a variable that belongs to the class A single copy to be shared by all instances of the class In the class Student, the constructor can be used to increment the variable total so that it shows the total number of Student objects
public class Student {

private int rollNo;


private char grade; private static int total; public Student(){ ++total; } //Other methods }
Copyright 2005, Infosys Technologies Ltd #

Each time the constructor is invoked and an object gets created, the static variable total will be incremented thus keeping a count of the total no of Student objects created
ER/CORP/CRS/LA10SC/003 Version 1.00

Static Methods (1/3)


In the class Student, consider a method getTotal() that returns the value of the static data member total It is more logical to invoke it for the entire class rather than for an object Such methods, that are invoked for a class are called static methods
public class Student { private int rollNo; private char grade; private static int total; //Other methods public static int getTotal(){

return total;
} }

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Static Methods (2/3)


Static methods are invoked using the syntax <ClassName.MethodName> Student s1 = new Student();

System.out.println(Student.getTotal());
//Prints 1 Student s2 = new Student(); System.out.println(Student.getTotal()); //Prints 2 Another example : y = Math.sqrt(x) ; // Math is a class in java.lang package and sqrt is a static method in it.

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Static Methods (3/3)


Static Method It is a class method

For using static methods, creation of an instance is not necessary


A static method can only access other static data and methods. It cannot access non-static members

(Non static methods can access static members but static methods can
access only static members)

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

The Static Block


Static Block
The static block is a block of statement inside a Java class that will be executed

when a class is first loaded and initialized


A class is loaded typically after the JVM starts In some cases a class is loaded when the program requires it class Test{ static { //Code goes here } }

A static block helps to initialize the static data members just like constructors help to initialize instance members
ER/CORP/CRS/LA10SC/003 Version 1.00

Copyright 2005, Infosys Technologies Ltd

The this Reference (1/2)


All instance methods (non-static methods) will have a reference called this The this reference will refer to the object that has invoked the method

For example, when the method getRollNo is invoked by an object x, the


method getRollNo can use the reference this to refer to x Both the following syntax can be used to implement the method getRollNo
public int getRollNo (){ return rollNo; } public int getRollNo (){ return this.rollNo; }

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

The this Reference (2/2)


The this reference can be used in some cases to improve the readability of a program
Class Complex{ private float real; private float imaginary; /*Bad coding standards public Complex(float x, float y){ real = x; imaginary = y; } */ //Good coding style //The this reference is used to avoid ambiguity public Complex(float real, float imaginary){ this.real = real; this.imaginary = imaginary; } }

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Coding Standards and Best Practices


Class name should begin with uppercase and camel casing
Eg. Student, ArrayList

Name should tell what the variable, method or class does No short form of words Variable name should start with lower case and to follow camel casing
Eg. int numberOfStudents;

Method names should begin with lowercase and follow camel casing
Eg. void displayUserChoice()

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Commenting code in Java (1/3)


File header
Description of the file

/* This java file contains a class with a method to compute the * Sum of two numbers. This method is invoked from another class * by passing the necessary values as parameters */

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Commenting code in Java (3/3)


Method header
description of the method

@param
@return Note: Do not type method name in header
/** * Computes the sum of the two integer variables passed * as parameters * @param number1 The First number * @param number2 The Second number * @return the sum of the two numbers passed as arguments */

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Strings in Java
Unlike C, String is a system defined class in Java Declaring Hello World in code will create an object of type string with data Hello World and returns a reference to it. System.out.println(Hello World); Unlike C, the string is of fixed length and memory for the string is managed totally by the String class
Prevents buffer overruns (checks bounds) NULL terminator not used in strings

Unlike C, String is not a simple array of characters. They are objects of class

String. Strings may be created as follows:


String employeeName = new String(Ram);
ER/CORP/CRS/LA10SC/003 Version 1.00

Copyright 2005, Infosys Technologies Ltd

Arrays of strings
Example : String itemArray = new String[5] ;

will create an array of strings of size 5 to hold five string constants.


We can assign the strings to the array elements, element by element using five different statements or using a for loop (using itemArray[i] )

We can initialize an array of strings as follows :


String city[ ] = { Pune, Delhi, Mumbai } ;

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Some methods in String class


Let s1 and s2 be two Strings s1.length() length of string s1

s2 = s1.toLowerCase
s2 = s1.toLowerCase s1.equals(s2)

converts s1 to lowercase
converts s1 to uppercase returns true if s1 equals s2

s1.equalsIgnoreCase(s2) returns true if s1 equals s2 ignoring case


s2 = s1.replace(x, y) replace all appearances of x with y s2=s1.trim() remove all spaces in beginning and end of s1

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA10SC/003 Version 1.00

Command Line Arguments


The main method takes an array of String as the parameter Information that follows the programs name on the command line when it is executed will be passed as a String array to the main method >java Sample Hello Welcome Ok Hello, Welcome and Ok will be passed as an array of 3 elements to the main method of the class Sample class Sample{ public static void main(String [] args){

for(int i = 0; i < args.length; ++i)


System.out.println(args[i]); } }
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Thank You
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00

Das könnte Ihnen auch gefallen