Top Banner

of 47

2 Java Basic n Method(Function) New

Apr 04, 2018

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 7/30/2019 2 Java Basic n Method(Function) New

    1/47

    Java Basics

  • 7/30/2019 2 Java Basic n Method(Function) New

    2/47

  • 7/30/2019 2 Java Basic n Method(Function) New

    3/47

  • 7/30/2019 2 Java Basic n Method(Function) New

    4/47

    So, what is Java?

    According to Sun's definition:Java is a " simple, object-oriented,interpreted, robust, secure,architecture-neutral, portable,

    high-performance, multithreaded,and dynamic language. "

  • 7/30/2019 2 Java Basic n Method(Function) New

    5/47

    multitasking infers the mechanism to runmany processes simultaneously with userinteraction.

    in contrast,multithreading is a mechanismof running various threads under single

    process within its own space.

  • 7/30/2019 2 Java Basic n Method(Function) New

    6/47

    Java Environment

    EditorDraft .java file

    Compiler .java file

    .class File

    Byte code VerifierByte code on RAM Verified Byte code

    InterpreterVerified Byte codeExecuted machinecode

    Class Loader .class File Byte code on RAM

  • 7/30/2019 2 Java Basic n Method(Function) New

    7/47

    Compiling/Running Java

    ProgramsTo compile your program, use command:

    c:\> javac MyProgramName.javaTo run your program, use command:

    c:\> java MyProgramName

  • 7/30/2019 2 Java Basic n Method(Function) New

    8/47

    Program skeleton1 //the skeleton of a java application

    2 package packagename;

    3 import packagename.ClassName;

    4 public class ProgramName

    5 {

    6 // Define program variables here.7 . . .

    8 // Define program methods here.

    9 . . .

    10 //Define the main method here.

    11 public static main(String args[])

    12 {

    13 // Main method body

    14 }//end of the main method.

    15 } //End of class HelloWorld

    Java is a casesensitive language

    Braces must occuron matching pairs

    Coding stylesshould be followed.

    Notes

  • 7/30/2019 2 Java Basic n Method(Function) New

    9/47

    Comment StylesComments are used to clear the logic of the codeand to increase the readability if it.Comments are ignored by the compiler.Java uses three types of comments: Single-line comment( // ). Example :

    //single-line comment here Multiple-line comment( /**/ ). Example :

    /*

    line 1 hereline 2 here

    */ Documentation comment( /***/ ). It is multiple-line

    and used with javadoc utility to create applicationdocumentation.

  • 7/30/2019 2 Java Basic n Method(Function) New

    10/47

    Playing With Strings

    A string is a group of charactersWe use class String to define a string.

    Example : String name;

    Strings are bounded by double quotations. Example : String name = Jane;

    We can concatenate two or more strings using theoperator +Strings can contain escape characters like \n ,\t , \\ , \ .

  • 7/30/2019 2 Java Basic n Method(Function) New

    11/47

    Variables DefinitionVariables are used to represent the data that aprogram deals withAs the name might imply, the data that avariable holds can change.We have to define a variable before using itHere is an example of defining a variable:

    int numberOfChar;String nameOfPerson;

  • 7/30/2019 2 Java Basic n Method(Function) New

    12/47

    Identifiers

    An identifier may contain combinations of theletters of the alphabet (both uppercase A-Z andlowercase a-z), an underscore character _, a

    dollar sign $, and decimal digits 0-9.

    Assignment Statement:

    identifier = literal ; identifier = identifier ; identifier = expression ;

  • 7/30/2019 2 Java Basic n Method(Function) New

    13/47

    What's a Java Literal?A constant value in a program is denoted by aliteral. Literals represent numerical (integer orfloating-point), character, boolean or string values.

    Example of literals: Integer literals: 33 0 -9Floating-point literals: .3 0.3 3.14

    Character literals: '(' 'R 'r '{ Boolean literals:(predefined values) true falseString literals: "language" "0.2" "r" ""

  • 7/30/2019 2 Java Basic n Method(Function) New

    14/47

    the following statements are legal .tax = 135.86; where 135.86 is a numeric literaltax = incomeTax; where incomeTax is another identifiertax = 0.175*cost; where 0.175*cost is an expression

    the following statements are illegal .135.86 = tax ; this implies the syntax literal =identifier (wrong)

    tax = incomeTax statement delimiter ; missing (wrong)0.175*cost = tax; this implies expression = identifier (wrong)

  • 7/30/2019 2 Java Basic n Method(Function) New

    15/47

    Variable Declaration:data-type identifier ;data-type identifier-list ;

    int parkingTime;float balance;float costOfGas;

    int weightLimit, parkingTime;float balance, costOfGas, valueOfShares;

  • 7/30/2019 2 Java Basic n Method(Function) New

    16/47

    Variable Initialization :data-type identifier = literal ;

    char parkingSymbol= 'P';int weightLimit = 10;

    float balance = 1225.11f;

    Constant Declaration:

    final data-type identifier = literal ;

    final float SALES_TAX = 0.05f;

    final double PI = 3.14159;

  • 7/30/2019 2 Java Basic n Method(Function) New

    17/47

    Casting

    SYNTAXCast operation:

    (data-type ) expression ;

    float money = 158.05;

    int looseChange = 275;money = (float) looseChange;

  • 7/30/2019 2 Java Basic n Method(Function) New

    18/47

    Primitives Data types

    Type Size in bits Valuesboolean 8 true or false

    char 16 \u0000 - \uFFFF

    byte 8 -128 - 127short 16 -32,768 32,767

    int 32 -2,147,483,648 - +2,147,483,647

    long 64-9,223,372,036,854,775,808 -+9,223,372,036,854,775,807

    float 32 -3.40292347E+38 - -+3.40292347E+38

    double 64 -1.79769313486231570E+308 to -

    +1.79769313486231570E+308

  • 7/30/2019 2 Java Basic n Method(Function) New

    19/47

    Arithmetic Operations

    Operation Operator Java Expression

    Addition + a + 8Subtraction - b - 7Multiplication * p * 10Division / c / 9Modulus % b % 6

  • 7/30/2019 2 Java Basic n Method(Function) New

    20/47

    ArithmeticUnary Operators

    + unary plus- unary minus

    Binary Multiplicative Operators * multiplication

    / division% remainder

    Binary Additive Operators + addition- subtraction

  • 7/30/2019 2 Java Basic n Method(Function) New

    21/47

    Decision making operations

    Operation Operator Java Expression

    Equal to == if (x == 1)

    Not equal to != if (y != 5) Greater than > while (x > y)

    Less than < while (x < y)

    Greater than or equal >= if (X >= y)

    Less than or equal

  • 7/30/2019 2 Java Basic n Method(Function) New

    22/47

    Assignment Operators

    Operator Expression Equivalent to= c = 5; c = 5

    += a += 10 ; a = a + 10;-= a -= b; a = a b;*= c *= 13; c = c * 13;

    /= a /= b; a = a/b;%= b %= c ; b = b% c;

  • 7/30/2019 2 Java Basic n Method(Function) New

    23/47

    Increment /decrement

    operationOperator expression Equivalent to

    ++ count++;++count;

    count = count + 1;

    -- --count;count--;

    count = count - 1;

  • 7/30/2019 2 Java Basic n Method(Function) New

    24/47

    Logical OperatorsLogical operators allow more complex conditions&& (logical AND) Returns true if both conditions are true

    || (logical OR) Returns true if either of its conditions are true! (logical NOT, logical negation) Reverses the truth/falsity of its condition Unary operator, has one operand

    Short circuit evaluation Evaluate left operand, decide whether to evaluate right

    operand If left operand of &&is false , will not evaluate right

    operand

  • 7/30/2019 2 Java Basic n Method(Function) New

    25/47

    PrecedenceOperator Associativity( ) From left to right

    ++ -- From right to left

    * / % From left to right

    + - From left to right

    < >= From left to right== != From left to right

    & From left to right

    ^ From left to right

    |From left to right

    && From left to right

    || From left to right

    ?: From right to left

    = += -= *= /= From right to left

    High

    Low

  • 7/30/2019 2 Java Basic n Method(Function) New

    26/47

    Java Key words

    Ja va Keyw ord s

    abstract boolean break byte case

    catch char class continue default

    do double else extends false

    final finally float for if

    implements import instanceof int interface

    long native new null package

    private protected public return short

    static super switch synchronized this

    throw throws transient true try

    void volatile while

    Keywords that are reserved but not used by Javaconst goto

    Keywords are words reserved for Java and cannot beused as identifiers or variable names

  • 7/30/2019 2 Java Basic n Method(Function) New

    27/47

    If if/else structuresif statement looks like:if (condition){

    }Conditions areevaluated to either trueor false

    If/else statement lookslike:

    if (condition)

    {//do something.

    }else

    {//do something else.

    }

  • 7/30/2019 2 Java Basic n Method(Function) New

    28/47

    The switch Structure

    switch statements Useful to test a variable for different valuesswitch ( value ){

    case '1':actions

    case '2':actions

    default:actions

    } break; causes exit from structure

  • 7/30/2019 2 Java Basic n Method(Function) New

    29/47

    While Structure while repetition structure

    Repeat an action while some condition remains true while loop repeated until condition becomes false

    Body may be a single or compound statement If the condition is initially false then the body will never

    be executed Example :

    int product = 2; while ( product

  • 7/30/2019 2 Java Basic n Method(Function) New

    30/47

    The for Structure

    for "does it all" : initialization, condition, incrementGeneral formatfor ( initialization ; loopContinuationTest ; increment )

    statement

    If multiple statements needed, enclose in bracesControl variable only exists in body of for structureIf loopContinuationTest is initially false , bodynot executed

  • 7/30/2019 2 Java Basic n Method(Function) New

    31/47

    public void hitungNilaiV(int n){

    double nilaiV;for(int P=1000;P

  • 7/30/2019 2 Java Basic n Method(Function) New

    32/47

    MethodsMethods

    Modularize a program All variables declared inside methods are local variables

    Known only in method defined

    Parameters

    Communicate information between methods Local variables

    Benefits Divide and conquer

    Manageable program development

    Software reusability Existing methods are building blocks for new programs Abstraction - hide internal details (library methods)

    Avoids code repetition

  • 7/30/2019 2 Java Basic n Method(Function) New

    33/47

    Method DefinitionsMethod definition format return-value-type method-name ( parameter-list )

    { declarations and statements

    } Method-name: any valid identifier Return-value-type: data type of the result (default int )

    void - method returns nothing

    Can return at most one value Parameter-list: comma separated list, declares

    parameters.

  • 7/30/2019 2 Java Basic n Method(Function) New

    34/47

    Methods and Parameters

    SYNTAXMethod Signature:modifier(s) return-type methodName ( formal-parameter-

    list );

    modifier(s) usually indicates the visibility of the method,i.e., where it can be activated from. If you will notice that

    the modifier defined for those methods is public ; thisimplies that the methods are visible (accessible) anywherethe class is visible. public, private dan protected

  • 7/30/2019 2 Java Basic n Method(Function) New

    35/47

    return-type the return type specifies the data type of thevalue that is returned by the method. This can be a

    primitive data type or a class . If no data is returned bythe method, then the keyword void is used for thereturn type.

    methodName an identifier that defines the name of themethod.

    formal-parameter-list declares the data variables thatare passed to and used by the method. If no data ispassed to the method, then the parentheses remainempty.

  • 7/30/2019 2 Java Basic n Method(Function) New

    36/47

    return StatementWhen method call encountered Control transferred from point of invocation to

    method

    Returning control If nothing returned: return;

    Or until reaches right brace If value returned: return expression ;

    Returns the value of expression

    Example user-defined method: public int square( int y )

    {return y * y

    }

  • 7/30/2019 2 Java Basic n Method(Function) New

    37/47

    Calling methodsThree ways Method name and arguments

    Can be used by methods of same classsquare( 2 );

    Dot operator - used with references to objectsg.drawLine( x1, y1, x2, y2 );

    Dot operator - used with static methods of classes

    Integer.parseInt( myString );

  • 7/30/2019 2 Java Basic n Method(Function) New

    38/47

    Coercion of argumentsForces arguments to appropriate type for method Example:

    Math methods only take double Math.sqrt( 4 ) evaluates correctly

    Integer promoted to double before passed to Math.sqrt

    Promotion rules Specify how types can be converted without losing data If data will be lost (i.e. double to int), explicit cast must

    be used If y is a double ,

    square( (int) y );

  • 7/30/2019 2 Java Basic n Method(Function) New

    39/47

    Duration of Identifiers

    Duration (lifetime) of identifiers When exists in memory Automatic duration

    Local variables in a method

    Called automatic or local variables Exist in block they are declared When block becomes inactive, they are destroyed

    Static duration Created when defined Exist until program ends Does not mean can be referenced/used anywhere

    See Scope Rules

  • 7/30/2019 2 Java Basic n Method(Function) New

    40/47

    Scope Rules (1)

    Scope Where identifier can be referenced Local variable declared in block can only be

    used in that blockClass scope Begins at opening brace, ends at closing brace

    of class

    Methods and instance variables Can be accessed by any method in class

  • 7/30/2019 2 Java Basic n Method(Function) New

    41/47

    Scope Rules (2)

    Block scope Begins at identifier's declaration, ends at terminating

    brace

    Local variables and parameters of methods When nested blocks, need unique identifier names

    If local variable has same name as instance variable Instance variable "hidden"

    Method scope For labels (used with break and continue ) Only visible in method it is used

  • 7/30/2019 2 Java Basic n Method(Function) New

    42/47

    Method Overloading

    Method overloading Methods with same name and different parameters Overloaded methods should perform similar tasks

    Method to square int s and method to square double s

    public int square( int x ) { return x * x; } public float square( double x ) { return x * x; }

    Program calls method by signature Signature determined by method name and parameter types Overloaded methods must have different parameters

    Return type cannot distinguish method

  • 7/30/2019 2 Java Basic n Method(Function) New

    43/47

    Arrays Array Group of consecutive memory locations Same name and type Static(Remain same size)

    To refer to an element, specify Array name Position number

    Format : arrayname [ position number ] First element at position 0

    Every array knows its own lengthc.length

  • 7/30/2019 2 Java Basic n Method(Function) New

    44/47

    Declaring/Allocating ArraysDeclaring arrays Specify type, use new operator

    Allocate number of elements Place brackets after name in declaration

    Two steps:int c[]; //declarationc = new int[ 12 ]; //allocation

    One step:int c[] = new int[ 12 ]; Primitive elements are initialized to zero or

    false while Non-primitive references are

    initialized to null

  • 7/30/2019 2 Java Basic n Method(Function) New

    45/47

    References and Reference

    ParametersPassing arguments to methods Call-by-value: pass copy of argument Call-by-reference: pass original argument

    Improves performance, weakens security

    In Java, you cannot choose how to passarguments Primitive data types passed call-by-value References to objects passed call-by-reference

    Original object can be changed in method

    Arrays in Java treated as objects Passed call-by-reference

  • 7/30/2019 2 Java Basic n Method(Function) New

    46/47

    Passing Arrays to

    Functions Passing arrays Specify array name without brackets

    int myArray[ 24 ]; myFunction( myArray );

    Arrays passed call-by-reference Modifies original memory locations

    Header for method modifyArray might be

    void modifyArray( int b[] )Passing array elements Passed by call-by-value Pass subscripted name (i.e., myArray[3] ) to method

  • 7/30/2019 2 Java Basic n Method(Function) New

    47/47