Beginning With Java

download Beginning With Java

of 104

Transcript of Beginning With Java

  • 8/2/2019 Beginning With Java

    1/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

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

  • 8/2/2019 Beginning With Java

    2/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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

  • 8/2/2019 Beginning With Java

    3/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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.

    1991This language was named as Oak1992 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.

    1994Development of web browser HotJava to run applets. Language became

    popular among internet users.

    1995Oak 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

  • 8/2/2019 Beginning With Java

    4/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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 withoutrecompilation

    Dynamic and extensible- Dynamic linking of class libraries. Supports functions

    written in other languages (native methods).

  • 8/2/2019 Beginning With Java

    5/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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.

  • 8/2/2019 Beginning With Java

    6/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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

  • 8/2/2019 Beginning With Java

    7/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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

  • 8/2/2019 Beginning With Java

    8/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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 .classfile to the machine language of the underlying

    platform.

    The underlying platform processes the commands given by the JVM

  • 8/2/2019 Beginning With Java

    9/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    Source File (HelloWorld.java)

    Java Architecture:

    Compiler (javac)

    Machine Code or Byte code(HelloWorld.class)

    JVM

    Class Loader

    Byte Code Verifier

    InterpreterJIT Code

    Generator

    Runtime

    Operating System

    Hardware

  • 8/2/2019 Beginning With Java

    10/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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.

    http://java.sun.com/http://java.sun.com/
  • 8/2/2019 Beginning With Java

    11/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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

  • 8/2/2019 Beginning With Java

    12/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    Source File Layout - Hello World

    We will have the source code first

    Type this into any text editorpublic 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

  • 8/2/2019 Beginning With Java

    13/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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.

  • 8/2/2019 Beginning With Java

    14/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    To execute

    Type in the command prompt

    java HelloWorldApp

    The result

  • 8/2/2019 Beginning With Java

    15/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    Compilation & Execution

    Java Program (.java)

    Java Complier (javac)

    Byte Code (.class file)

    Interpreter (java) Interpreter (java) Interpreter (java)

    Win 32 Linux Mac

  • 8/2/2019 Beginning With Java

    16/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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

  • 8/2/2019 Beginning With Java

    17/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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.

  • 8/2/2019 Beginning With Java

    18/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    Java Tokens

    Java program is a collection of tokens, comments and white spaces

    Tokens are of five types

    - Reserved keywords

    - Identifiers

    - Literals

    - Operators

    - Separators

  • 8/2/2019 Beginning With Java

    19/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    Java Keywords (For Reference Only)

    The reserved keywords defined in the Java language

    abstract const finally implements public this

    boolean continue for instanceof throw transient

    break float if null short void

    byte default import int super volatile

    case do false return switch while

    catch double interface package synchronized

    char else long private static

    class extends goto protected try

    true final new native throws

  • 8/2/2019 Beginning With Java

    20/104

  • 8/2/2019 Beginning With Java

    21/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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 - ( ) { } [ ] , ; .

  • 8/2/2019 Beginning With Java

    22/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    Comment entry in Java

    A single line comment in Java will start with //

    // This is a single line comment in JavaA multi line comment starts with a /* and ends with a */

    /* This is a multi line

    comment

    in Java */

  • 8/2/2019 Beginning With Java

    23/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    Data Types in Java

    Integer data types

    byte (1 byte)

    short (2 bytes)

    int (4 bytes)

    long (8 bytes)

    Floating Type

    float (4 bytes)

    double (8 bytes)

    Textual

    char (2 bytes)

    Logical

    boolean (1 byte) (true/false)

    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

  • 8/2/2019 Beginning With Java

    24/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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;

    }

    In Java, if a local variable is used without initializing it, the compiler will show an error

    BEST PRACTICE: Declare a variable in program only when

    required. Do not declare variables upfront like in C.

  • 8/2/2019 Beginning With Java

    25/104

  • 8/2/2019 Beginning With Java

    26/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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 lossof data

    Type cast operator

  • 8/2/2019 Beginning With Java

    27/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    Operators and Assignments

    Arithmetic Operators: Binary : + - * / % Unary : + -

    Assignment Operator: =

    Relational Operators: < >= == !=

    Boolean Logical operators: && || !

    The ternary / Conditional Operator: ? :

    Other Special operators : Increment operator ++ Decrement operator --

    Compound assignment operators += -= *= /= %=

    The Bitwise operators: & ! ^ ~ > >>>

  • 8/2/2019 Beginning With Java

    28/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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

  • 8/2/2019 Beginning With Java

    29/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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 handside value will be ignored.

    If avg is float or double, decimal part will be stored.

  • 8/2/2019 Beginning With Java

    30/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    Relational operators

    Following are the relational operators in java with sequence of precedence andmeaning as given :

    < less than greater than

    >= greater than or equal to

    == equal to

    != not equal to

    A simple relational expression contains a relational operator with one operandon each side left and right as follows

    exp1 relational-operator exp2 where exp1 and exp2 are arithmeticexpressions which may be variables, constants or combination of them.

    The arithmetic expressions will be evaluated first and then the results will becompared 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

  • 8/2/2019 Beginning With Java

    31/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    Logical Operators

    Following are the logical operators in java with their precedence, symbols andmeanings 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.

  • 8/2/2019 Beginning With Java

    32/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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++ ++a

    Example

    a=5;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

  • 8/2/2019 Beginning With Java

    33/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    Shorthand / Compound Assignment Operators

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

    a=a+5 can be written as a+=5

    b=b-2 can be written as b-=2 and so on

    m=m*n can be written as m*=n

    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

  • 8/2/2019 Beginning With Java

    34/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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.

  • 8/2/2019 Beginning With Java

    35/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    Operator Precedence

    Operators Precedence

    Postfix expr++ expr

    Unary ++expr --expr +expr -expr ~ !

    Multiplicative * / %

    Additive + -

    Shift > >>>

    Relational < > = instanceof

    Equality == !=

    logical AND &&

    logical OR ||

    Ternary ? :Assignment = += -= *= /= %=

  • 8/2/2019 Beginning With Java

    36/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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

  • 8/2/2019 Beginning With Java

    37/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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: if, if-else and switch.

    Loop statements: 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

  • 8/2/2019 Beginning With Java

    38/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

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

    Example :

    int a = 10, b = 20;if (a > b)

    System.out.println("a > b");

  • 8/2/2019 Beginning With Java

    39/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

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

    else

    Example :

    int a = 10, b = 20;

    if (a > b)System.out.println("a > b");

    else

    System.out.println("b > a");

  • 8/2/2019 Beginning With Java

    40/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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.

  • 8/2/2019 Beginning With Java

    41/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    switch case Statement

    The general form of switch case statement is

    switch(control_expression)

    {

    case expression1:

    ;

    case expression2:

    ;

    ...

    ...

    case expression_n:

    ;

    default:

    ;

    } // end switch

  • 8/2/2019 Beginning With Java

    42/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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.

  • 8/2/2019 Beginning With Java

    43/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

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

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

  • 8/2/2019 Beginning With Java

    44/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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

  • 8/2/2019 Beginning With Java

    45/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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 atleast 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 immediatelyfollowing 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

    while ();

  • 8/2/2019 Beginning With Java

    46/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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

  • 8/2/2019 Beginning With Java

    47/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

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

    {

    loop body }

    The first part of a for statement is a starting initialization, which executes once before theloop begins. The 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.

    E l f f l

  • 8/2/2019 Beginning With Java

    48/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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

  • 8/2/2019 Beginning With Java

    49/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

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

  • 8/2/2019 Beginning With Java

    50/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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 ; // the labeled form

    E l f b k t t t

  • 8/2/2019 Beginning With Java

    51/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

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

    }

    Th ti t t t

  • 8/2/2019 Beginning With Java

    52/104

    ER/CORP/CRS/LA10SC/003Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

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

    E l f ti t t t

  • 8/2/2019 Beginning With Java

    53/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, Infosys

    Technologies Ltd#

    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

  • 8/2/2019 Beginning With Java

    54/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, Infosys

    Technologies Ltd#

    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.

    Methods

  • 8/2/2019 Beginning With Java

    55/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, Infosys

    Technologies Ltd#

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

    Method Overloading (1/3)

  • 8/2/2019 Beginning With Java

    56/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, Infosys

    Technologies Ltd#

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

    M th d l di (2/3)

  • 8/2/2019 Beginning With Java

    57/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, Infosys

    Technologies Ltd#

    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

    Method overloading (3/3)

  • 8/2/2019 Beginning With Java

    58/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, Infosys

    Technologies Ltd#

    Method overloading (3/3)

    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.

    Overloaded methods

    Arrays in Java

  • 8/2/2019 Beginning With Java

    59/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, Infosys

    Technologies Ltd#

    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.

    Creating an array in Java

  • 8/2/2019 Beginning With Java

    60/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, Infosys

    Technologies Ltd#

    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 referenceto the newly created array

    The concept of references in Java is very similar to that of pointers in C

    Reference variables in Java (1/4)

  • 8/2/2019 Beginning With Java

    61/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, Infosys

    Technologies Ltd#

    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 arrayint [] x;//Create a new int array and make x refer to itx = new int[5];

    Reference variables in Java (2/4)

  • 8/2/2019 Beginning With Java

    62/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 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

  • 8/2/2019 Beginning With Java

    63/104

    Reference Types in Java (4/4)

  • 8/2/2019 Beginning With Java

    64/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, Infosys

    Technologies Ltd#

    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;

    Initializing an array in Java

  • 8/2/2019 Beginning With Java

    65/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, Infosys

    Technologies Ltd#

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

    The length of an array

  • 8/2/2019 Beginning With Java

    66/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, Infosys

    Technologies Ltd#

    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.lengthwill 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;

    }

    Two Dimensional Arrays

  • 8/2/2019 Beginning With Java

    67/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, InfosysTechnologies Ltd

    #

    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 arraysx = 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

    Example of two dimensional array

  • 8/2/2019 Beginning With Java

    68/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, InfosysTechnologies Ltd #

    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

  • 8/2/2019 Beginning With Java

    69/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, InfosysTechnologies Ltd #

    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

    Access Modifiers private and public

  • 8/2/2019 Beginning With Java

    70/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, InfosysTechnologies Ltd #

    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

    Creating Objects in Java (1/2)

  • 8/2/2019 Beginning With Java

    71/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, InfosysTechnologies Ltd #

    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 referenceto the newly created object

    Creating Objects in Java (2/2)

  • 8/2/2019 Beginning With Java

    72/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, InfosysTechnologies Ltd #

    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 StudentStudent s;//Create a new Student object and make s refer to the objects = new Student();

    Invoking methods in a class

  • 8/2/2019 Beginning With Java

    73/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, InfosysTechnologies Ltd #

    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 statementss.printGrade();System.out.println(s.getRollNo());

    The reference can be seen as the name of an object

    Constructors (1/4)

  • 8/2/2019 Beginning With Java

    74/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, InfosysTechnologies Ltd#

    Constructors (1/4)

    A constructor is a special method that is called to create a new object

    Student s = new Student();Calling theconstructor

    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

    Constructors (2/4)

  • 8/2/2019 Beginning With Java

    75/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, InfosysTechnologies Ltd #

    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 evenvoid

    Constructors (3/4)

  • 8/2/2019 Beginning With Java

    76/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, InfosysTechnologies Ltd #

    Co st ucto s (3/ )

    public class Counter {private int count;public Counter(){

    count = 1;}//Other Methods

    }

    User DefinedConstructor

    In the above example, the user defined constructor initializes count to 1

    Counter c = new Counter();//c.count is initialized to 1

    Constructors (4/4)

  • 8/2/2019 Beginning With Java

    77/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, InfosysTechnologies Ltd #

    ( )

    public class Counter {private int count;public Counter(){

    count = 1;}public Counter(int x){

    count = x;}//Other Methods

    }

    The constructor without any parameter is called a default constructor

    Just like other methods, constructors also can be overloaded

    Counter c1 = new Counter();//c1.count is initialized to 1Counter c2 = new Counter(5);//c2.count is initialized to 5

    Memory Allocation (1/2)

  • 8/2/2019 Beginning With Java

    78/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, InfosysTechnologies Ltd #

    y ( )

    All local variables are stored in a stack

    These variables are de-allocated as soon as the method terminates in a last infirst 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)

    Memory Allocation (2/2)

    Data members of the

  • 8/2/2019 Beginning With Java

    79/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, InfosysTechnologies Ltd #

    y ( )

    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

    }}

    ata e be s o t eclass are stored in the

    heap along with theobject. Their lifetime

    depends on thelifetime of the object

    Local variables xand y are stored

    in the Stack

    Local variable ais stored in the

    Stack

    Dynamic objectswill be stored in

    the heap

    Lifetime of objects (1 of 2)

  • 8/2/2019 Beginning With Java

    80/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, InfosysTechnologies Ltd #

    j ( )

    Student obj1 = new Student();

    Student obj2 = new Student();

    The two Student objects are now living on the heap

    -- References: 2

    -- Objects: 2

    Student obj3 = obj2;

    -- References: 3

    -- Objects: 2

    2

    1

    heap

    obj1

    obj2

    2

    1heap

    obj1

    obj2

    obj3

    Lifetime of objects (2 of 2)

  • 8/2/2019 Beginning With Java

    81/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00Copyright 2005, InfosysTechnologies Ltd#

    j ( )

    obj3 = obj1;

    -- References: 3

    -- Objects: 2

    obj2 = null;

    -- Active References: 2

    -- null references: 1

    -- Reachable Objects: 1

    -- Abandoned objects: 12

    1heap

    obj1

    obj2

    ob3

    2

    1

    obj1

    obj2

    ob3 heap

    Null reference

    This object can begarbage collected(Can be Removed

    from memory)

    Garbage Collection

  • 8/2/2019 Beginning With Java

    82/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    g

    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

    Array of Objects

  • 8/2/2019 Beginning With Java

    83/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    y j

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

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

  • 8/2/2019 Beginning With Java

    84/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    j g yp ( )

    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

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

  • 8/2/2019 Beginning With Java

    85/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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}

    }

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

  • 8/2/2019 Beginning With Java

    86/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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

    Parameter Passing Techniques

  • 8/2/2019 Beginning With Java

    87/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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

    The static keyword

  • 8/2/2019 Beginning With Java

    88/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    The static keyword can be used in 3 scenarios:

    For class variables

    For methods

    For a block of code

    Static Data Members (1/2)

  • 8/2/2019 Beginning With Java

    89/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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

    }

    The static variable is initialized to 0,ONLY when the class is first loaded,

    NOT each time a new instance ismade

    Static Data Members (2/2)

  • 8/2/2019 Beginning With Java

    90/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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

    }

    Each time the constructor is invokedand an object gets created, the staticvariable total will be incremented thus

    keeping a count of the total no ofStudent objects created

    Static Methods (1/3)

  • 8/2/2019 Beginning With Java

    91/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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 methodspublic static int getTotal(){

    return total;}

    }

    Static Methods (2/3)

  • 8/2/2019 Beginning With Java

    92/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    Static methods are invoked using the syntax

    Student s1 = new Student();System.out.println(Student.getTotal());//Prints 1Student s2 = new Student();System.out.println(Student.getTotal());//Prints 2Another example :

    y = Math.sqrt(x) ;

    // Math is a class in java.lang package and sqrt is a static method in it.

    Static Methods (3/3)

  • 8/2/2019 Beginning With Java

    93/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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)

    The Static Block

  • 8/2/2019 Beginning With Java

    94/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    Static Block

    The static block is a block of statement inside a Java class that will be executedwhen 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

    A static block helps to initialize the static data members just like constructors help to

    initialize instance members

    class Test{static {

    //Code goes here}

    }

    The this Reference (1/2)

  • 8/2/2019 Beginning With Java

    95/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

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

    The this Reference (2/2)

  • 8/2/2019 Beginning With Java

    96/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

    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 standardspublic Complex(float x, float y){

    real = x;imaginary = y;}

    *///Good coding style//The this reference is used to avoid ambiguitypublic Complex(float real, float imaginary){

    this.real = real;this.imaginary = imaginary;}

    }

    Coding Standards and Best Practices

  • 8/2/2019 Beginning With Java

    97/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, InfosysTechnologies Ltd

    #

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

    Commenting code in Java(1/3)

  • 8/2/2019 Beginning With Java

    98/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, Infosys

    Technologies Ltd

    #

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

    Commenting code in Java (3/3)

  • 8/2/2019 Beginning With Java

    99/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, Infosys

    Technologies Ltd

    #

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

    Strings in Java

  • 8/2/2019 Beginning With Java

    100/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, Infosys

    Technologies Ltd

    #

    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.

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

    System.out.println(Hello World);

    Arrays of strings

  • 8/2/2019 Beginning With Java

    101/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, Infosys

    Technologies Ltd

    #

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

    Some methods in String class

  • 8/2/2019 Beginning With Java

    102/104

    ER/CORP/CRS/LA10SC/003

    Version 1.00

    Copyright 2005, Infosys

    Technologies Ltd

    #

    Let s1 and s2 be two Strings

    s1.length() length of string s1

    s2 = s1.toLowerCase converts s1 to lowercase

    s2 = s1.toLowerCase converts s1 to uppercase

    s1.equals(s2) 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

  • 8/2/2019 Beginning With Java

    103/104

  • 8/2/2019 Beginning With Java

    104/104

    Thank You