04-TCP2103-JAVA BASIC

Embed Size (px)

Citation preview

  • 8/7/2019 04-TCP2103-JAVA BASIC

    1/57

    JAVA Basics

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

  • 8/7/2019 04-TCP2103-JAVA BASIC

    2/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Content

    PART I

    Comments

    Reserved words

    Modifiers Statements

    Blocks

    Classes Methods

    The main method

  • 8/7/2019 04-TCP2103-JAVA BASIC

    3/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Content

    PART II

    Data Basics

    Variable & Constant

  • 8/7/2019 04-TCP2103-JAVA BASIC

    4/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Comments

    These are the used of comments

    documents what the program is and

    how the program is constructed.helps programmers and users to

    communicate and understand the

    program.

  • 8/7/2019 04-TCP2103-JAVA BASIC

    5/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Comments

    There are three types of comments

    line comment

    paragraph comment

    javadoc comments

  • 8/7/2019 04-TCP2103-JAVA BASIC

    6/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Comments : line comment

    preceded by two slash (//) on a

    line.

    compiler ignores all text after // on

    the same line.

    Example :

    weight *= 2.2046; //Convert to kilograms

  • 8/7/2019 04-TCP2103-JAVA BASIC

    7/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Comments : block comment

    enclosed between /* and */ onone or several lines.

    when the compiler sees /*, it

    scans for the next */ and ignoresany text between /* and */.

    Example

    /* Exercise 5-2 for Java MethodsAuthor: NurkhairizanDate: 21/11/2007Rev. 1.0 */

  • 8/7/2019 04-TCP2103-JAVA BASIC

    8/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Comments : Javadoc comment

    begins with /** and end with */.

    Are used for documenting

    classes, data and method.

    They can be extracted into a

    HTML file using JDKs javadoc

    command.

  • 8/7/2019 04-TCP2103-JAVA BASIC

    9/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    JavadocComments (contd)

    /*** Returns total sales from all vendors;* sets totalSales* to 0.*

    * @return total amount of sales from all vendors

    */

    /** indicates ajavadoccomment

    Can useHTML tags

    Commonstyle

  • 8/7/2019 04-TCP2103-JAVA BASIC

    10/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Reserved Word (Keyword)

    Have a specific meaning to the compiler andcannot be used for other purpose in theprogram

    Reserved words use only lowercase letters.

    Reserved words include:

    primitive data types: int, double, char,boolean, etc.

    storage modifiers: public, private,static, final, etc.

    control statements: if, else, switch,while, for, etc.

    built-in constants: true, false, null

    There are about 50 reserved words total.

  • 8/7/2019 04-TCP2103-JAVA BASIC

    11/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Modifier

    Reserved words called modifiers specifythe properties of the data, methods andclasses and how they can be used.

    Example of modifier are public,static private, final,abstract andprotected

    Apublic modifiers for method andclass can be access by other classes.

    A private datum or method cannot be

    accessed by other classes.

  • 8/7/2019 04-TCP2103-JAVA BASIC

    12/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Statements

    A statement represents an action or asequence of actions

    Example

    System.out.println(Welcome to Java!);

    is a statement to display the greetingWelcome to Java!.

    Every statement in Java ends with asemicolon (;)

  • 8/7/2019 04-TCP2103-JAVA BASIC

    13/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Blocks

    Ablockis a group of zero or morestatements between balancedbraces ( { } )

    The braces form a block thatgroups the component of theprogram

    each block begins with an openingbrace({ ) and ends with a closingbrace ( })

  • 8/7/2019 04-TCP2103-JAVA BASIC

    14/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    The useof Blocks

  • 8/7/2019 04-TCP2103-JAVA BASIC

    15/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Classes

    The program is defined by usingone or more classes.;

    Only one public class can beused in a program file.

    The file name must be same as

    class name (public class)

  • 8/7/2019 04-TCP2103-JAVA BASIC

    16/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Sample JAVA Application Program

    File name Class name

    Only ONE publicclass is allowedin a file!!

    File name = class name

    Main Method

    Welcome

    Class

    statement

  • 8/7/2019 04-TCP2103-JAVA BASIC

    17/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Method

    Consider the following statement

    System.out.println(Hello);

    System.out is known as the standard

    output object.

    println is a method in the object, which

    consists of a collection of statement thatperform a sequence of operations to display amessage to the standard output devices.

    The method can be used even without fullyunderstanding the details of how it works.

  • 8/7/2019 04-TCP2103-JAVA BASIC

    18/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Themain method

    Every Java application must have amainmethod that defines where the program begins.

    The main method provides the control ofprogram flow.

    The Java interpreter executes the applicationby invoking the main method.

    main method must be placed in class block

  • 8/7/2019 04-TCP2103-JAVA BASIC

    19/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Identifier

    Programming languages use

    special symbols called identifiersto name such programmingentities as variables, constants,variables, constants,

    methods, classes and packagemethods, classes and package.

  • 8/7/2019 04-TCP2103-JAVA BASIC

    20/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Identifier

    The rules for naming identifiers: An identifiers is a sequence of characters that

    consists of letters, digits, underscores (_), anddollar signs ($).

    An identifier must start with a letter, anunderscore(_), or dollar sign($). It cannot startwith a digit.

    An identifier cannot be a reserved word.

    An identifier cannot be true, false or null.

    An identifier can be of any length. It cannotcontain space

  • 8/7/2019 04-TCP2103-JAVA BASIC

    21/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Identifier

    Example for valid identifiers

    myName

    number1

    num1

    No34

    Ctr

    fahrenheitToCelcius

    celciusToFahrenheit

    _myClassNumber

    $noOfStudentInClass

    totalPrice

  • 8/7/2019 04-TCP2103-JAVA BASIC

    22/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Identifier

    Example for invalid identifiers My Name : contain space

    Number 1 :contain space

    Num%123 : contain special symbol %

    static : reserved word My-Name : contain special symbol -

    Fahrenheit To Celcius contain space

    Celcius-To-Fahrenheit contain specialsymbol -

    45number start with digit public contain special symbol

    int contain special symbol

  • 8/7/2019 04-TCP2103-JAVA BASIC

    23/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Java Programming Data Types

    Definition : A setof values togetherwith a set

    ofoperations on those values

    Primitive Data Types

    Integral

    Floating-point

    Boolean

  • 8/7/2019 04-TCP2103-JAVA BASIC

    24/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Data Types

    Primitive Data Types

    integral

    char

    byte

    short

    int

    long

    Data types thatdeals with

    integer,ornumberwithout adecimal part

    Floating-

    point

    Boolea

    n

    Assign short,int orlong data types when you aresure a variableis a whole number(NO decimal

    points). Whichtypeyou choosedepends upon the size

    ofthe numbers.

  • 8/7/2019 04-TCP2103-JAVA BASIC

    25/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Data Types

    Primitive Data Types

    Integra

    l Floating-

    point

    Boolea

    n

    float

    double

    Data types thatdeals withdecimal numbers

    Assign float ordouble when decimals are needed. Which

    typeyou choosedepends upon the sizeofthe numbers

  • 8/7/2019 04-TCP2103-JAVA BASIC

    26/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Data Types

    Primitive Data Types

    Integra

    l Floating-

    point

    Boolea

    n

    true

    false

    Data types thatdeals with

    logical value

    Assign charifthe variablewill always contain only

    ONE characterofdata

  • 8/7/2019 04-TCP2103-JAVA BASIC

    27/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Primitive

    TypeSize Minimum Value Maximum Value Wrapper Type

    char 16-bit Unicode 0 Unicode 216-1 Character

    byte 8-bit -128 +127 Byte

    short 16-bit-215

    (-32,768)

    +215-1

    (32,767)Short

    int 32-bit-231

    (-2,147,483,648)

    +231-1

    (2,147,483,647)Integer

    long 64-bit

    -263

    (-

    9,223,372,036,85

    4,775,808)

    +263-1

    (9,223,372,036,854

    ,775,807)

    Long

    float 32-bit 32-bit IEEE 754 floating-pointnumbers

    Float

    double 64-bit64-bit IEEE 754 floating-point

    numbersDouble

    boolean 1-bit true orfalse Boolean

  • 8/7/2019 04-TCP2103-JAVA BASIC

    28/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Review Question

    Are the following identifiers valid? If no, statethe reason

    applet, Applet, a++, --a, 4#R, $4,

    #44, apps

    Which of the following are Java keywords?

    class, public, int, x, y, radius

  • 8/7/2019 04-TCP2103-JAVA BASIC

    29/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Variables & Constant Variable

    Avariableis a named memory location whichtemporarily stores data that can change while theprogram is running.

    Constant Variable : is a named memorylocation which temporarily stores data thatremains the same throughout the execution of theprogram.

    Variable & Constant variable only canbe used after it has been declare.

  • 8/7/2019 04-TCP2103-JAVA BASIC

    30/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Variable

    The syntax :

    dataType identifier1;

    dataType identifier1 = 3;

    dataType identifier1, identifier2,

    identifierN;

    Example :

    double amount;

    int counter = 3;

    char ch1, ch2, ch3;

    int num1, num2;

  • 8/7/2019 04-TCP2103-JAVA BASIC

    31/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Variables

    A variable must be declared before it can beused:

    int count;double x, y;

    JButton go;

    Walker amy;

    String firstName;

    Type

    Name(s)

  • 8/7/2019 04-TCP2103-JAVA BASIC

    32/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Variables

    The assignment operator = sets thevariables value:

    count = 5;x = 0;myName = (Nurkhairizan);firstName = args[0];

  • 8/7/2019 04-TCP2103-JAVA BASIC

    33/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Variables (contd)

    A variable can be initialized in itsdeclaration:

    int count = 5;

    String firstName = Ahmad;

  • 8/7/2019 04-TCP2103-JAVA BASIC

    34/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    When you declare a variable, Java reservesmemory locations of sufficient size to store thevariable type.

    The actual data values will be stored in these

    memory locations.

  • 8/7/2019 04-TCP2103-JAVA BASIC

    35/57

  • 8/7/2019 04-TCP2103-JAVA BASIC

    36/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Variable declaration

    Where to declare the variables

    Inside theclass, but

    outside themethods

    Inside the

    method

  • 8/7/2019 04-TCP2103-JAVA BASIC

    37/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Variables (contd)

    Common mistakes:

    public void someMethod (...)

    {int x = 0;...int x = 5; // should be: x = 5;

    ...Variable declared twicewithin the same scope syntax error

  • 8/7/2019 04-TCP2103-JAVA BASIC

    38/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Constant Variable

    The syntax :

    final dataType identifier = value;

    Example :

    final double CM_PER_INCH = 2.54;

    final intNO_OF_STUDENT = 40;final double PAY_RATE = 15.57;

    Keyword finalindicatetheconstant

    variable

  • 8/7/2019 04-TCP2103-JAVA BASIC

    39/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Constant Variable

    Using final you can define variableswhose values never change.

    You MUST place an initial value

    into such a "constant" variable.

    If you do not place this initial value,Java will never let you assign a

    value at a later time because youcannot do anything to change thevalue of a final (constant) variable.

  • 8/7/2019 04-TCP2103-JAVA BASIC

    40/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Constant Variable declaration

    Where to declare constant variables

    Itcan beinsidethe

    class orinsidethe

    method

  • 8/7/2019 04-TCP2103-JAVA BASIC

    41/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Printing Variables

    Remember: The basic output statementin Java is

    System.out.println ( );

    System.out.

    println(" text " );will print what is between the double

    quotes and move the printing cursorto the nextline.

    System.out.print ( text );will print what is between the doublequotes and leave the printing cursor onthe same line

  • 8/7/2019 04-TCP2103-JAVA BASIC

    42/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Printing Variables

    When dealingwith variables:

    System.out.println( The total pay is + totalPay);

    what is surrounded by " " is referred to as a "literalprint" and gets printed exactly. The "+" sign is theconcatenator operator and concatenates the string

    with the value that is stored in the variabletotalPay. totalPay is declared as a double, but isautomatically converted to a String for the purposeof printing out.

    C O C O O OG G

  • 8/7/2019 04-TCP2103-JAVA BASIC

    43/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Printing Variable

    The code :

    double totalPay = 1006.5;System.out.println("The total payis " + totalPay);

    On the screen:

    Thetotal payis 1006.5

    TCP2103 INTRODUCTION TO PROGRAMMING

  • 8/7/2019 04-TCP2103-JAVA BASIC

    44/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Review Question

    1. The nameof a variableis known as its:

    [a] identifier

    [b] constant

    [c] data type

    [d] base

    2. All variables must bedeclared beforethey

    can be used. [a] true [b] false3. Variable names may begin with a

    number. [a] true [b] false

    TCP2103 INTRODUCTION TO PROGRAMMING

  • 8/7/2019 04-TCP2103-JAVA BASIC

    45/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Review Question

    4. When a data type mustcontain decimal

    numbers, assign thetype

    [a] int [b] char [c] double [d] long int

    5. Variables that aredeclared, but notinitialized,contain

    [a] blank spaces

    [b] zeros

    [c] "garbage" values

    [d] nothing - they are empty

    TCP2103 INTRODUCTION TO PROGRAMMING

  • 8/7/2019 04-TCP2103-JAVA BASIC

    46/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Review Question

    6. A variableis given a valuethrough

    [a] a comparison statement

    [b] as assignment statement

    [c] the import statements

    [d] the public class declarations

    TCP2103 INTRODUCTION TO PROGRAMMING

  • 8/7/2019 04-TCP2103-JAVA BASIC

    47/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Review Question

    7. Declare an int variable

    count withinitial value 100,anddeclare an int constantSIZE with value 20

    TCP2103 INTRODUCTION TO PROGRAMMING

  • 8/7/2019 04-TCP2103-JAVA BASIC

    48/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Using Variable in Program

    Write a program to read the followinginformation:

    Name

    Age

    IC Number Semester

    Pointer

    After that display all the information by using asuitable labels.

    TCP2103 : INTRODUCTION TO PROGRAMMING

  • 8/7/2019 04-TCP2103-JAVA BASIC

    49/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    1st Step : identify variables used

    There are 5 input declare/create 5 single variablewith appropriate data type.

    Name string

    Age integer

    ICNumberstring

    Semester integer

    Pointer float

    String name;

    int age;

    String ICNo;

    int Semester;

    float pointer;

    Capitalletter

    Lowercaseletter

    Identifier

    TCP2103 : INTRODUCTION TO PROGRAMMING

  • 8/7/2019 04-TCP2103-JAVA BASIC

    50/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    2nd Step : Write Program

    1st style

    2nd style

    Declareeach variablein a

    singleline

    Group variable basedon

    data type

    Dont forget semicolon(;) foreach statement

    TCP2103 : INTRODUCTION TO PROGRAMMING

  • 8/7/2019 04-TCP2103-JAVA BASIC

    51/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    3rd Step : Prompt & accept

    Use output statement to prompt user for information :

    System.out.print(the prompt goes here :);

    System.out.println(the prompt goes here :);

    semicolon(;) indicates endof statement

    Input (from keyboard) appears here

    TCP2103 : INTRODUCTION TO PROGRAMMING

  • 8/7/2019 04-TCP2103-JAVA BASIC

    52/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    4th Step : acceptthe information

    Syntax to accept from various type of input (the inputstatement)

    name = io.readLine();

    age = Integer.parseInt(io.readLine());

    price = Double.parseDouble(io.readLine());

    point = Float.parseFloat(io.readLine());

    bolF= Boolean.parseBoolean(io.readLine());

    chGrade = (char)io.read();

    string

    integer

    double

    float

    boolean

    char

    TCP2103 : INTRODUCTION TO PROGRAMMING

  • 8/7/2019 04-TCP2103-JAVA BASIC

    53/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    4th Step : acceptthe information(cont)

    Before you can use the input statement, followthese steps

    1

    2

    3

  • 8/7/2019 04-TCP2103-JAVA BASIC

    54/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

  • 8/7/2019 04-TCP2103-JAVA BASIC

    55/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Displaythe information

    \n : new line

    \t : tab

    TCP2103 : INTRODUCTION TO PROGRAMMING

  • 8/7/2019 04-TCP2103-JAVA BASIC

    56/57

    TCP2103 : INTRODUCTION TO PROGRAMMING

    Nurkhairizan07

    Theoutput

    TCP2103 : INTRODUCTION TO PROGRAMMING

  • 8/7/2019 04-TCP2103-JAVA BASIC

    57/57

    The End

    TCP2103 : INTRODUCTION TO PROGRAMMING