+ All Categories
Home > Documents > W01-Javabasic

W01-Javabasic

Date post: 03-Jun-2018
Category:
Upload: hien-vu
View: 219 times
Download: 0 times
Share this document with a friend

of 43

Transcript
  • 8/12/2019 W01-Javabasic

    1/43

    3/23/2014 1Java Fundamental

    Java Fundamentals

    1. Introduction to Java2. Basic Java Syntax3. Array4. String5. Flow Control

  • 8/12/2019 W01-Javabasic

    2/43

    1.Introduction to Java

    3/23/2014 Java Fundamental 2

    A programming language that was introduced by Sun Microsystems in 1995Originally for intelligent consumer-electronic

    devicesThen used for creating Web pages withdynamic content

  • 8/12/2019 W01-Javabasic

    3/43

    Now also used for:o Develop large-scale enterprise applicationso Enhance WWW server functionalityo Provide applications for consumer devices

    (cell phones, etc.) Object-oriented programming Java Tutorial Online at

    http://download.oracle.com/javase/tutorial/java/index.html

    3/23/2014 Java Fundamental 3

    1. Introduction to Java

    http://download.oracle.com/javase/tutorial/java/index.htmlhttp://download.oracle.com/javase/tutorial/java/index.htmlhttp://download.oracle.com/javase/tutorial/java/index.htmlhttp://download.oracle.com/javase/tutorial/java/index.html
  • 8/12/2019 W01-Javabasic

    4/43

    Java Principles

    3/23/2014 Java Fundamental 4

    It should be " simple, object oriented, andfamiliar ".It should be " robust and secure ".

    It should have " an architecture-neutral and portable environment ".It should execute with " high performance ".It should be " interpreted, threaded, anddynamic ".

  • 8/12/2019 W01-Javabasic

    5/43

    Java Platform

    3/23/2014 Java Fundamental 5

  • 8/12/2019 W01-Javabasic

    6/43

    Basics of a Typical Java Environment

    3/23/2014 Java Fundamental 6

    PrimaryMemory

    ..

    .

    .

    ..

    Disk

    Disk

    Disk

    Editor

    Compiler

    Class Loader

    Program is created in an editor and storedon disk in a file ending with .java .

    Compiler creates bytecodes and storesthem on disk in a file ending with .class .

    Class loader reads .class filescontaining bytecodes from disk andputs those bytecodes in memory.

    Phase 1

    Phase 2

    Phase 3

    PrimaryMemory

    .

    .

    .

    .

    .

    .

    Bytecode Verifier Bytecode verifier confirms that allbytecodes are valid and do not violateJavas security restrictions.

    Phase 4

    PrimaryMemory

    .

    .

    .

    .

    .

    .

    InterpreterInterpreter reads bytecodes andtranslates them into a language thatthe computer can understand,possibly storing data values as theprogram executes.

    Phase 5

  • 8/12/2019 W01-Javabasic

    7/43

    3/23/2014 Java Fundamental 7

    First Sample: Printing a Line of Text

    // This is a simple programcalled First.java

    class First {

    public static void main (String [] args) {System.out.println ("My first program in

    Java ");

    }

    }

  • 8/12/2019 W01-Javabasic

    8/43

  • 8/12/2019 W01-Javabasic

    9/43

    2.Basic Java Syntax - code Comment

    3/23/2014 Java Fundamental 9

    /*

    * Multi line

    */

    // Single line

    /**

    * Special comment for Javadocs*/

  • 8/12/2019 W01-Javabasic

    10/43

    Name Styles

    3/23/2014 Java Fundamental 10

    Names are case-sensitive, may contains letter,number, the dollar sign "$", or the underscorecharacter "_".

    Some convention name styles:Class names: CustomerInfoVariable, function names: basicAnnualSalaryConstants name:MAXIMUM_NUM_OF_PARTICIPANTS

  • 8/12/2019 W01-Javabasic

    11/43

    Naming best practice

    Name should be meaningfulAvoid very sort name, except for temporary"throwaway" variables: a, i, j

    Avoid confuse name: TransferAction class andDoTransferAction class, so which one willreally performs the action?

    Class name should be a noun, use whole words,avoid acronyms and abbreviations: Student

    3/23/2014 Java Fundamental 11

  • 8/12/2019 W01-Javabasic

    12/43

    Variable name should begin with a noun:numberOfFilesVariable names should not start with underscore('_') or dollar sign ('$') characters, even though

    both are allowed.Distinguish singular - plural: Student - Students

    3/23/2014 Java Fundamental 12

    Naming best practice

  • 8/12/2019 W01-Javabasic

    13/43

    Method name should begin with verb:countNumberOfFiles ()As clear as possible: annualSalary instead ofsalaryAvoid mixed-language, ex Vietnamese +English + Japanese .

    3/23/2014 Java Fundamental 13

    Naming best practice

  • 8/12/2019 W01-Javabasic

    14/43

  • 8/12/2019 W01-Javabasic

    15/43

    Standard Java Output

    3/23/2014 Java Fundamental 15

    System.out is standard out in Java System.err is error out in Java

  • 8/12/2019 W01-Javabasic

    16/43

    Escape characters

    3/23/2014 Java Fundamental 16

  • 8/12/2019 W01-Javabasic

    17/43

    Basic Data Types (cont.)

    3/23/2014 Java Fundamental 17

  • 8/12/2019 W01-Javabasic

    18/43

    Operations

    Simple Assignment Operator= Simple assignment operator

    Arithmetic Operators+ Additive operator- Subtraction operator

    * Multiplication operator/ Division operator% Remainder operator

    Unary Operators

    + Unary plus operator; indicates positive value- Unary minus operator; negates an expression++ Increment operator; increments a value by 1-- Decrement operator; decrements a value by 1! Logical compliment operator; inverts the value of a boolean

    3/23/2014 Java Fundamental 18

  • 8/12/2019 W01-Javabasic

    19/43

    Operations (cont)

    Equality and Relational Operators== Equal to!= Not equal to> Greater than>= Greater than or equal to< Less than

  • 8/12/2019 W01-Javabasic

    20/43

    Type Casting

    3/23/2014 Java Fundamental 20

    In type casting, a data type is converted intoanother data type.

    Examplefloat c = 34.89675f;

    int b = (int)c + 10;

  • 8/12/2019 W01-Javabasic

    21/43

    Automatic type and Casting

    3/23/2014 Java Fundamental 21

    Two type of data conversion: automatic type conversion andcasting.

    When one type of data is assigned to a variable of anothertype then automatic type conversion takes place provided itmeets the conditions specified:

    The two types are compatible

    The destination type is larger than the source type. Casting is used for explicit type conversion.

    It loses information above the magnitude of the value being

    converted.

  • 8/12/2019 W01-Javabasic

    22/43

    Variables

    3/23/2014 Java Fundamental 22

    Three components of a variable declaration are:

    Data type

    Name

    Initial value to be assigned (optional) Syntax

    datatype identifier [=value][,

    identifier[=value]...]; class DynVar {

    public static void main(String[] args) {double len = 5.0, wide = 7.0;double num = Math.sqrt(len * len + wide * wide);System.out.println("Value of num after dynamic initialization is "

    + num);}

    }

  • 8/12/2019 W01-Javabasic

    23/43

    Scope and Lifetime of Variables

    3/23/2014 Java Fundamental 23

    o Variables can be declared inside a block.o The block begins with an opening curly brace

    and ends with a closing curly brace.

    o A block defines a scope.o A new scope is created every time a new block

    is created.o Scope specifies what objects are visible to

    other parts of the program.o It also determines the life of an object.

  • 8/12/2019 W01-Javabasic

    24/43

    Arrays

    3/23/2014 Java Fundamental 24

    ArraysData structuresRelated data items of same type

    Remain same size once created Fixed-length entries

  • 8/12/2019 W01-Javabasic

    25/43

    Array structure

    3/23/2014 Java Fundamental 25

    Name of array(note that allelements of thisarray have thesame name, c )

    Index (or subscript)of the element inarray c, beginfrom 0

    c[ 0 ]c[ 1 ]c[ 2 ]

    c[ 3 ]

    c[ 4 ]c[ 5 ]

    c[ 6 ]

    c[ 7 ]

    c[ 8 ]c[ 9 ]

    c[ 10 ]

    c[ 11 ]

    -456

    0

    72

    1543-89

    0

    62

    -31

    6453

    78

    Value of eachelement

  • 8/12/2019 W01-Javabasic

    26/43

    Array Index

    Also called subscript Position number in square brackets

    Always begin from zero Must >= 0 and < arrays length a = 5;

    b = 6;c[a + b] += 2;Adds 2 to c[11]

    3/23/2014 Java Fundamental 26

  • 8/12/2019 W01-Javabasic

    27/43

    Examine an array

    Examine array cc is the array name

    c.length accesses array cs lengthc has 12 elements ( c[0], c[1], c[11] )

    The value of c[0] is 45

    3/23/2014 Java Fundamental 27

  • 8/12/2019 W01-Javabasic

    28/43

    Array Declarations

    3/23/2014 Java Fundamental 28

    Three ways to declare an array are:datatype[] identifier;

    datatype[] identifier = new

    datatype[size];datatype[] identifier ={value1,value2,valueN};You can also place the square brackets afterthe array's name:datatype identifier[]; // thisform is discouraged

  • 8/12/2019 W01-Javabasic

    29/43

    Multidimensional Arrays

    3/23/2014 Java Fundamental 29

    Multidimensional arrays Tables with rows and columns

    Two-dimensional array Declaring two-dimensional array b[2][2]

    int[][] b = { { 1, 2 }, { 3, 4 } }; 1 and 2 initialize b[0][0] and b[0][1] 3 and 4 initialize b[1][0] and b[1][1]

    3-by-4 arrayint[][] b;

    b = new int[3][4];

  • 8/12/2019 W01-Javabasic

    30/43

  • 8/12/2019 W01-Javabasic

    31/43

    Example

    3/23/2014 Java Fundamental 31

    public class MultidimensionArrayDemo {

    public static void main(String[] args){

    String[][] names = {{"Mr. ", "Mrs. ", "Ms. "},

    {"Smith", "Jones"}};

    System.out.println(names[0][0] + names[1][0]);

    System.out.println(names[0][2] + names[1][1]);}

    }

    The output from this program is:

    Mr. Smith

    Ms. Jones

  • 8/12/2019 W01-Javabasic

    32/43

    Java Strings

    3/23/2014 Java Fundamental 32

    String is a Class Strings are Constants Declaration:

    String greeting = "Hello world!";

    char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};

    String helloString = new String(helloArray);

  • 8/12/2019 W01-Javabasic

    33/43

    Concatenating Strings

    3/23/2014 Java Fundamental 33

    The String class includes a method for concatenatingtwo strings:string1.concat(string2);

    This returns a new string that is string1 with string2added to it at the end.

    Strings are more commonly concatenated with theoperator, as in

    "Hello," + " world" + "!"

    which results in

    "Hello, world!"

  • 8/12/2019 W01-Javabasic

    34/43

    Control Flow Structures in Java

    3/23/2014 Java Fundamental 34

    Decision-making if-else statement switch-case statement

    Loops while loop do-while loop for loop

    Branching break continue return

  • 8/12/2019 W01-Javabasic

    35/43

  • 8/12/2019 W01-Javabasic

    36/43

    Example

    3/23/2014 Java Fundamental 36

    class CheckNum {public static void main(String[] args) {

    int num = 10;if (num % 2 == 0) {

    System.out.println(num + " is an even number");} else {

    System.out.println(num + " is an odd number");}

    }}

  • 8/12/2019 W01-Javabasic

    37/43

    switch case statement

    3/23/2014 Java Fundamental 37

    The switch case statement can be used inplace of if-else-if statement.

    It is used in situations where the expression

    being evaluated results in multiple values. The use of the switch-case statement

    leads to simpler code, and better

    performance.

  • 8/12/2019 W01-Javabasic

    38/43

    Example

    3/23/2014 Java Fundamental 38

    public class SwitchDemo {

    public static void main(String[] args) {

    int month = 8;String monthString;

    switch (month) {

    case 1: monthString = "January"; break;

    case 2: monthString = "February"; break;

    case 3: monthString = "March"; break;

    case 4: monthString = "April"; break;

    case 5: monthString = "May"; break;case 6: monthString = "June"; break;

    case 7: monthString = "July"; break;

    case 8: monthString = "August"; break;

    case 9: monthString = "September"; break;

    case 10: monthString = "October"; break;

    case 11: monthString = "November"; break;

    case 12: monthString = "December"; break;

    default: monthString = "Invalid month"; break;

    }

    System.out.println(monthString);

    }

    }

    Output will be: August

  • 8/12/2019 W01-Javabasic

    39/43

    while Loop

    3/23/2014 Java Fundamental 39

    while loops are used for situations when a loop hasto be executed as long as certain condition is True.

    The number of times a loop is to be executed is notpre-determined, but depends on the condition.

    The syntax is: while (condition) {action statements;

    }

  • 8/12/2019 W01-Javabasic

    40/43

    Example

    3/23/2014 Java Fundamental 40

    class FactDemo {public static void main(String[] args) {

    int num = 5, fact = 1;while (num >= 1) {

    fact *= num;num--;

    }System.out.println("The factorial of 5 is : " + fact);

    }}

  • 8/12/2019 W01-Javabasic

    41/43

  • 8/12/2019 W01-Javabasic

    42/43

    Example

    3/23/2014 Java Fundamental 42

    class DoWhileDemo {public static void main(String[] args) {

    int count = 1, sum = 0;do {

    sum += count;count++;

    } while (count

  • 8/12/2019 W01-Javabasic

    43/43

    for Loop All loops have some common features: a counter variable that is

    initialized before the loop begins, a condition that tests the countervariable and a statement that modifies the value of the countervariable.

    The for loop provides a compact format for incorporating thesefeatures.

    Syntax:for (initialization; loopContinuationCondition; increment) {

    statement;}

    class ForDemo {public static void main(String[] args) {

    int count = 1, sum = 0;for (count = 1; count


Recommended