Topic 2 Part1

download Topic 2 Part1

of 49

Transcript of Topic 2 Part1

  • 7/30/2019 Topic 2 Part1

    1/49

  • 7/30/2019 Topic 2 Part1

    2/49

    Upon completion of this course, the students should be ableto:

    1. Describe the features and basic concepts of Java language.

    2. Write, compile Java source code and interpret Java byte code usingJava Development Kit (JDK).

    3. Implement the key of OOP concepts: classes and objects, inheritanceand polymorphism.

    4. Incorporate exception handling in Java Programming.

  • 7/30/2019 Topic 2 Part1

    3/49

    Identify identifiers, variables and constants in Javaprogram.Define assignment and expression statements in JavaprogramList numeric data types in Java programImplement numeric data types in Java programExplain character data types in Java program :

    Unicode and ASCII codeEscape sequence for special character

    Implement character and Boolean data types,operator precedence in Java programs.Define typecasting in Java programsImplement typecasting in Java programs

  • 7/30/2019 Topic 2 Part1

    4/49

    Identifiers :The name given to the variables,constants and method.

    Rules to naming Identifiers : An identifier must start with a character (A-Z, a-z),an underscore (_) or a dollar sign ($).In an identifier, the letters other than the first one

    can be any character except the operators or keywords in Java (Examples: +, -, switch).The special characters such as #, !, @ and ^cannot be used.

  • 7/30/2019 Topic 2 Part1

    5/49

    The special characters such as #, !, @ and ^cannot be used.

    Blank and tab space cannot be used.

    Java is case-sensitive.Keywords listed in Java cannot be used asidentifiers.

  • 7/30/2019 Topic 2 Part1

    6/49

    Identifiers Valid/Invalid Reason Quantity Valid Identifier should start with

    an alphabet.

    1amount Invalid Identifier must not beginwith a number.

    $price Valid Identifier can start with a $.my car Invalid Blank spaces not allowed in

    an identifier.Total_Price Valid Special symbol underscore

    ( _ ) can be used in anidentifier.

  • 7/30/2019 Topic 2 Part1

    7/49

    Identifiers Valid/Invalid Reason First! Invalid Special character

    exclamation mark ( ! )

    cannot be used in anidentifier.Number5 Valid Identifier can have

    numbers.

    Price# Invalid Identifier name must notend with the hash ( # )symbol.

  • 7/30/2019 Topic 2 Part1

    8/49

    Identify which of the following are valididentifiers. If it is invalid, explain why.

    a. bite the cakeb. troublec. 1stnamed. Bubblee. good-byef. Second!

  • 7/30/2019 Topic 2 Part1

    9/49

    Variables :Is the name given to the memory location where avalue is stored.

    The name given to the variable is called as identifier.Each variable has :

    NameTypeHolds a value that you assign to them

    The value can change during programexecution

  • 7/30/2019 Topic 2 Part1

    10/49

    Declaration :A Java variable may refer to an object, anarray, or an item of primitive.

    Syntax to define a variable : ;

    E.g :char grade; // defines a character

    int [] grade; // defines a reference to array of intsint age = 25; // defines an integerVector v; // reference to a Vector object

  • 7/30/2019 Topic 2 Part1

    11/49

    InitializationsVariables may be initialized as follow :

    Primitive type :int i = 3;boolean g = true;

    Objects :Button b = null;Employee e = new Employee();

    Arrays :int[] a={1,2,3,4};

  • 7/30/2019 Topic 2 Part1

    12/49

    Is a value that does not change throughoutprogram execution.Every constant has :

    NameTypeValues that are set to them

    Variables modified by the static finalkeywords are constant

  • 7/30/2019 Topic 2 Part1

    13/49

    Example of a constant value for each datatype is listed as follows:

    Integer (Example: 12)Floating-point (Example: 3.1438)Boolean (Example: true/false)Character (Example: a)

    String (Example: I go to school)

  • 7/30/2019 Topic 2 Part1

    14/49

    Defines the type of the value to be stored in thememory.Data types in Java can be classified into two

    groups:Primitive or Built-in data typesReference or User-defined data types

  • 7/30/2019 Topic 2 Part1

    15/49

    Java defines eightbasic primitive datatypes.

    They are:byteshort

    longint

    floatdouble

    charBoolean

  • 7/30/2019 Topic 2 Part1

    16/49

    Primitive Type Description

    boolean true/false 1-bit. May take on the valuestrue and false only

    byte 8 bits 1 signed bytes (twoscomplement). Covers valuesfrom -128 to 127

    char 16 bits(UNICODE)

    2 bytes, unsigned, Unicode, 0 to65,535.A char is a single characterwhich can contains a letter, a

    digit, a punctuation mark, a tab,a space, or something similar.Char can be implemented by asingle one character enclosed insingle qoute marks such as :

    char MyChar =g;

  • 7/30/2019 Topic 2 Part1

    17/49

    Primitive Type Description

    short 16 bits 2 bytes, signed (twoscomplement), covers value from -32,768 to 32,767

    int 32 bits 4 bytes, signed (twoscomplement), covers value from -2,147,483,648 to 2,147,483,647.All numeric types in may be castinto other numerictypes(byte,short,long,float,double).

    When lossy casts are done(e.g:intto byte), the conversion is donedepends to the length of thesmaller type.

  • 7/30/2019 Topic 2 Part1

    18/49

    Primitive Type Descriptionlong 64 bits 8 bytes, signed (twos complement).

    Ranges from-9,223,372,036,854,775,808 to+9,223,372,036,854,775,807

    float 32 bits IEEE754-1985 4 bytes, IEEE 754. Covers a rangefrom 1.40129846432481707e-45 to3.40282346638528860e+38(posotive or negative).Like all numeric types, floats alsocan be cast into other numeric

    types(byte,short,long,float,double).When lossy casts to integer type aredone(e.g:float to short), thefractional part is truncated andignored depends to the length of thesmaller type.

  • 7/30/2019 Topic 2 Part1

    19/49

    Primitive Type Description

    double 64 bits IEEE754-1985

    8 bytes IEEE 754. Covers a rangefrom 4.94065645841246544e-324dTo 1.79769313486231570e+308d(positive or negative)

  • 7/30/2019 Topic 2 Part1

    20/49

    Are the reserved words available in Javalanguage.

    The functions of each of the keywords arepredefined.

  • 7/30/2019 Topic 2 Part1

    21/49

    Types Keywords Data types, modifiers,class and access

    specifiers

    abstract, Boolean, byte,char, double, extends,

    final, float, implements,import, int, inner, long,new, native, package,

    private, protected, public,short, static, super, this,transient, var, volatile

  • 7/30/2019 Topic 2 Part1

    22/49

    Types Keywords User defined data typesand type related

    class, cast, instanceof,void, synchronized

    Conditional if, else, switch, case,default

    Flow control for, while, do, break,continue, goto and return

    Exception handling Catch, finally, try, throw,throws

  • 7/30/2019 Topic 2 Part1

    23/49

    Identify the keywords from the following:bytevariablegoodfor valuevoid

  • 7/30/2019 Topic 2 Part1

    24/49

    1. Write a program to declare two variableshours_worked and pay_rate of integer data type and assign the values 8 and300. Print the value of the variableshours_worked and pay_rate.

    2. Write a program to declare a variabletotal_classroom of integer data type andassign the value 30. Print the value.

  • 7/30/2019 Topic 2 Part1

    25/49

    Is the conversion of a value of one datatype into another data type.Typecasting is of two types:

    Implicit conversionExplicit conversion

  • 7/30/2019 Topic 2 Part1

    26/49

    Implicit ConversionWhen a value of data type with lower range isassigned to a variable of data type with higher range.Java automatically makes the conversion.E.g :

    double x; // Size is 8 byteint y=2; //Size is 4 bytesfloat z=2.2f;x=y+z;//Implicit conversion

  • 7/30/2019 Topic 2 Part1

    27/49

    Explicit ConversionWhen a value of data type with higher rangeis assigned to a variable of data type withlower range, the user needs to make explicitconversion.

    Explicit conversion leads to data loss.

    E. g:int total_value;double book1 = 300.40;total_value=(int)book1; // Explicit conversion

  • 7/30/2019 Topic 2 Part1

    28/49

    Write a Java program to declare a variabled of type double. Assign the value 102.5 to d . Declare a float variable fl . Assign thevalue of d to fl by performing an explicitconversion and print the value on thescreen.

  • 7/30/2019 Topic 2 Part1

    29/49

    Is a symbol that instructs Java compiler toperform an operation, or action.Mathematical Operator :

    Are operators that are used for performingsimple mathematical calculations such asaddition, subtraction, multiplication and

    division.

  • 7/30/2019 Topic 2 Part1

    30/49

    Write the resultant value of the followingexpressions.

    Expression Result

    14-4

    14+4

    14* 4

    14/4

    14%4

  • 7/30/2019 Topic 2 Part1

    31/49

    Calculate the total marks for the given fivesubjects. Declare appropriate variables, assignvalues as given below, and calculate the total

    marks:English = 85Maths = 100History = 75Geography = 70

    Art = 85

  • 7/30/2019 Topic 2 Part1

    32/49

    Assignment operatorExample 1

    x = 3;

    Syntax

    = ;

  • 7/30/2019 Topic 2 Part1

    33/49

    Assignment operatorExample 2

    x = x + 3; x += 3;

    Syntax

    = ;

  • 7/30/2019 Topic 2 Part1

    34/49

    Increment Operator

    Increments the existing value by one.

    Examplenum++;

    Prefix :++a a=a+1; OR a+=1;

    Postfix :a++ a=a+1; OR a+=1;

  • 7/30/2019 Topic 2 Part1

    35/49

    Decrement Operator

    Decrements the existing value by one.

    Examplenum--;

    Prefix :--a a=a-1; OR a-=1;

    Postfix :a-- a=a-1; OR a-=1;

  • 7/30/2019 Topic 2 Part1

    36/49

    Relational Operator Are used to perform a logical comparison of values,which results in a value that is either true or false .

    Usually controls other statements

    Used to compare data

    Example

    x = 10; x < 20;

  • 7/30/2019 Topic 2 Part1

    37/49

    Operator Description Example

    > Greater than a > b

    < Less than a < b>= Greater than or equal to a >= b

  • 7/30/2019 Topic 2 Part1

    38/49

    Expression Result

    15 < 20.75 True

    15 > 20.75 False

    15 == 15 True

    15 =20.75 False15 != 15 True

  • 7/30/2019 Topic 2 Part1

    39/49

    Expression Result 4.5 = 0

  • 7/30/2019 Topic 2 Part1

    40/49

    Logical Operator Are used to combine two or more logical expressionsto form a more complex logical expression.

    To combine relational operator into better datatesting statements

    Example

    (number100)

  • 7/30/2019 Topic 2 Part1

    41/49

    Operators Description

    && Logical AND

    || Logical OR

    ! Logical NOT

  • 7/30/2019 Topic 2 Part1

    42/49

    Condition1 Condition2 && ||

    true true true false

    true false false true

    false true false true

    false false false false

  • 7/30/2019 Topic 2 Part1

    43/49

    Conditional OperatorIs used to construct conditional expressions.

    Exampleint aggregate = 95;char grade = (aggregate>90)?'A': 'B';

  • 7/30/2019 Topic 2 Part1

    44/49

    Operator PresedenceDetermines the order in which mathematicalcomputations and operations are performed in

    an expression.

  • 7/30/2019 Topic 2 Part1

    45/49

  • 7/30/2019 Topic 2 Part1

    46/49

    Result = a + b * 2 / c 5 \\a=b=5, c=2Result = 5 + 5 * 2 / 2 5Result = 5 + 10 / 2 5Result = 5 + 5 5Result = 10 5Result = 5.

  • 7/30/2019 Topic 2 Part1

    47/49

    Is any combination of operators andoperands that evaluates to a value.The expressions can be classified into

    three main categories:Numerical Expressions - Combine variables,numbers and mathematical operators.

    Assignment Expressions - Assign values tovariables.Logical Expression - Results in true or false.

  • 7/30/2019 Topic 2 Part1

    48/49

    S. No. a b c d Expression Result 1 24 2 8 - a/b-c

    2 4 2 5 - a-b+c

    3 2 4 2 1 a+b/c+d

    4 3.5 2.0 - (a+b)*c

    5 -34 6 - - a/b6 -34 6 - - a%b

  • 7/30/2019 Topic 2 Part1

    49/49

    Next.Prepare for subtopic 2.2 Input and Output Stream