csc238 - 2) java programming basics (part 2)

Upload: smile-smiley

Post on 14-Apr-2018

244 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    1/34

    1

    CSC238

    OBJECT ORIENTED PROGRAMMING

    Topic 2 :

    Java Programming Basic(Part 2)

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    2/34

    TOPIC COVERED

    Character and String

    String manipulation

    substring

    length indexOf

    concatenation

    Array of primitive

    Predefined package Date

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    3/34

    CHARACTER

    In Java, single characters are represented usingthe data type char.

    Character constants are written as symbolsenclosed in single quotes .

    Characters are stored in a computer memory usingsome form of encoding.

    ASCII, which stands forAmerican Standard Code

    for Information Interchange, is one of the documentcoding schemes widely used today.

    Java uses Unicode, which includes ASCII, forrepresenting charconstants.

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    4/34

    CHARACTER

    Declaration and

    initializationchar ch1, ch2 = X;

    Type conversion

    between int and

    char.

    System.out.print("ASCII code ofcharacter X is " + (int) 'X' );

    System.out.print("Character withASCII code 88 is " + (char)88 );

    This comparison

    returns true

    because ASCII

    value of'A' is 65

    while that of'c' is

    99.

    A < c

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    5/34

    STRING

    A stringis a sequence of characters that is

    treated as a single value. Instances of the String class are used to

    represent strings in Java.

    We can access individual characters of a stringby calling the charAt method of the Stringobject.

    There are close to 50 methods defined in the

    String class. Example: substring, length, andindexOf.

    More:http://docs.oracle.com/javase/6/docs/api/java/lan

    g/String.html

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    6/34

    STRING

    Contains operations to manipulate

    strings.

    String:

    Sequence of zero or more characters.

    Enclosed in double quotation marks .

    Is processed as a single unit .

    Null or empty strings have no characters.

    Every character in a string has a relative

    position in that string , the first character is in

    position 0 .

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    7/34

    STRING

    Length of the string is the number ofcharacters in it .

    Numeric strings consist of integers or decimal

    numbers.

    When determining the length of a string ,

    blanks count .

    Example :

    Empty String has length = 0

    abc has length = 3 , position of a = 0 ,b= 1 ,

    c= 2

    a boy has length = 5

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    8/34

    STRING

    More examples:

    String: The Mentalist

    Position of M: ? Position ofsecond e: ? Position of : ?

    Length of the String:?

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    9/34

    STRING

    String Indexing

    The position, or index, of

    the first character is 0.

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    10/34

    SUBSTRING

    Assume stris a String object and properlyinitialized to a string.

    str.substring( i, j ) will return a new string by

    extracting characters of str from position i toj-1where 0 i length of str, 0 j length of str,and i j.

    If str is programming , then str.substring(3, 7)will create a new string whose value is gram.

    The original string strremains unchanged.

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    11/34

    EXAMPLE

    String text = Espresso;

    text.substring(6,8)

    text.substring(0,8)

    text.substring(1,5)

    text.substring(3,3)

    text.substring(4,2)

    so

    Espresso

    spre

    error

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    12/34

    LENGTH

    Assume str is a String object and properly

    initialized to a string.

    str.length( ) will return the number of characters

    in str.

    If str is programming , then str.length( ) will

    return 11 because there are 11 characters in it.

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    13/34

    EXAMPLE

    String str1, str2, str3, str4;

    str1 = Hello ;

    str2 = Java ;

    str3 = ; //empty string

    str4 = ; //one space

    str1.length( )

    str2.length( )

    str3.length( )

    str4.length( )

    5

    4

    1

    0

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    14/34

    INDEXOF

    Assume str and substr are String objects andproperly initialized.

    str.indexOf(substr) will return the first position substr

    occurs in str.

    If stris programming and substris gram , then

    str.indexOf(substr) will return 3 because the position

    of the first character of substr in str is 3.

    If substr does not occur in str, then1 is returned.

    The search is case-sensitive.

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    15/34

    EXAMPLE

    String str;

    str = I Love Java and Java loves me. ;

    str.indexOf( J )

    str.indexOf( love )

    str.indexOf( ove )

    str.indexOf( Me )

    7

    21

    -1

    3

    3 7 21

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    16/34

    CONCATENATION

    Assume str1 and str2 are String objects and properlyinitialized.

    str1 + str2 will return a new string that is a

    concatenation of two strings.

    If str1 is pro and str2 is gram , then str1 + str2 will

    return program.

    Notice that this is an operator and not a method of the

    String class. The strings str1 and str2 remains the same.

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    17/34

    EXAMPLE

    String str1, str2;

    str1 = Jon ;

    str2 = Java ;

    str1 + str2

    str1 + + str2

    str2 + , + str1

    Are you + str1 + ?

    JonJava

    Jon Java

    Java, Jon

    Are you Jon?

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    18/34

    ARRAYSOF PRIMITIVES

    Array Declaration

    [ ] //variation 1

    [] //variation 2

    Array Creation

    = new [ ]

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    19/34

    ARRAYSOF PRIMITIVES

    Example

    double[ ] rainfall;

    rainfall = new double[12];

    Variation 1

    double rainfall [];

    rainfall = new double[12];

    Variation 2

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    20/34

    ACCESSING INDIVIDUAL ELEMENTS

    Individual elements in an array accessed with theindexed expression.

    double[] rainfall = newdouble[12];

    The index of the firstposition in an array is 0.

    rainfall 0 1 2 3 4 5 6 7 8 9 10 11

    rainfall[2] This indexed expressionrefers to the element at

    position #3

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    21/34

    ARRAY PROCESSING SAMPLE1

    double[] rainfall = newdouble[12];

    double annualAverage,sum = 0.0;

    for (int i = 0; i < rainfall.length; i++) {

    rainfall[i] = Double.parseDouble(

    JOptionPane.showinputDialog(null,

    "Rainfall for month " + (i+1) ));

    sum += rainfall[i];

    }

    annualAverage = sum / rainfall.length;

    The public constantlength returns the

    capacity of an array.

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    22/34

    ARRAY PROCESSING SAMPLE 2

    double[] rainfall = new double[12];

    String[] monthName = new String[12];

    monthName[0] = "January";

    monthName[1] = "February";

    double annualAverage, sum = 0.0;

    for(int i = 0; i < rainfall.length; i++) {

    rainfall[i] = Double.parseDouble(

    JOptionPane.showinputDialog(null,"Rainfall for "

    + monthName[i]));sum += rainfall[i];

    }

    annualAverage = sum / rainfall.length;

    The same pattern for

    the remaining ten

    months.

    The actual month

    name instead of a

    number.

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    23/34

    ARRAY INITIALIZATION

    Like other data types, it is possible to declare

    and initialize an array at the same time.

    int[] number = { 2, 4, 6, 8 };

    double[] samplingData = { 2.443, 8.99, 12.3, 45.009, 18.2,

    9.00, 3.123, 22.084, 18.08 };

    String[] monthName = {"January", "February", "March",

    "April", "May", "June", "July",

    "August", "September", "October","November", "December" };

    number.length

    samplingData.length

    monthName.length

    4

    9

    12

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    24/34

    VARIABLE-SIZE DECLARATION

    In Java, we are not limited to fixed-size array

    declaration.

    The following code prompts the user for the size of

    an array and declares an array of designated size:

    int size;

    int[] number;

    size=

    Integer.parseInt(JOptionPane.showInputDialog(null,

    "Size of an array:"));

    number = newint[size];

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    25/34

    PREDEFINED-PACKAGE

    A package is a JAVA class library a collection of classes andinterfaces in the same directory.

    Benefits :-

    Package can contain hidden classes that are used by the

    package but not visible or accessible outside the package. Classes in a package can have fields and methods that are

    visible by all classes within the same package but notoutside.

    Different packages can have classes with the same name.Example : java.awt.Frame and java.photo.Frame

    To use objects contained in a package, you need to import thepackage the use of keyword impor tat the beginning of theJAVA application. Example : impo rt java.uti l .*;

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    26/34

    PREDEFINED-PACKAGE

    java.lang package

    Most common Math class methods : pow(x,y),sq rt(x), round (x), PI

    Example : AreaCircle = Math.PI * Math.pow(r,2);

    java.util package Use of GregorianCalendar class to keep track of time

    Specifies data field values such as day, month and year canbe retrieved from GregorianCalendar object by using methodget().

    Method get() always returns an integer. Some of the possibleargument are :

    DAY_OF_YEAR = returns values from 1 to 366

    DAY_OF_MONTH = returns values from 1 to 31

    DAY_OF_WEEK = SUNDAY, MONDAY.. SATURDAY ,

    YEAR = current year

    MONTH = JANUARY, FEBRUARY DECEMBER

    HOUR = returns values from 1 to 12 AM or PM

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    27/34

    DATE

    The Date class from thejava.util package is

    used to represent a date.

    When a Date object is created, it is set to

    today (the current date set in the computer)

    The class has toString method that converts

    the internal format to a string.

    Date today;today = new Date( );

    System.out.println(today.toString( ) );

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    28/34

    SIMPLEDATE FORMAT

    The SimpleDateFormat class allows the Date

    information to be displayed with various format.

    Date today = new Date( );

    SimpleDateFormat sdf1, sdf2;

    sdf1 = new SimpleDateFormat( MM/dd/yy );

    sdf2 = new SimpleDateFormat( MMMM dd, yyyy );

    sdf1.format(today);

    sdf2.format(today);

    System.out.println(sdf1.format(today));

    System.out.println(sdf2.format(today));

    10/31/03

    October 31, 2003

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    29/34

    EXAMPLEOF GREGORIANCALENDAR

    CLASSimport java.util.*;

    public class AgeCalculator

    {

    public static void main (String args[])

    {

    GregorianCalendar Calendar = new GregorianCalendar();Scanner scanner = new Scanner(System.in);

    int nowYear;

    int birthYear;

    int yearsOld;

    System.out.println("In what year you were born?");

    birthYear = scanner.nextInt();

    nowYear = Calendar.get(Calendar.YEAR);

    yearsOld = nowYear - birthYear;

    System.out.println( "You are " + yearsOld + " years old");

    }

    }

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    30/34

    USERDEFINED PACKAGE

    1. Include a statement packagepackagename; asthe first statement of the source file for the classdefinition.

    2. The class declaration must have a visibility modifierpubl ic

    3. Create a folder/directory named the same name asyourpackagename. In JAVA, the package musthave a one-to-one correspondence with the folder.

    4. Place the classes and interfaces that you want toinclude in the package and compile it.

    How to create a package?

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    31/34

    INTRODUCTIONTO JAVA APPLET

    An applet

    JAVA program that is embedded in a Web page.

    Enables Web designers to develop pages that accept input,perform computations and display results.

    Enables web designers to create pages that can do anything

    a program can do.

    Java program that is called from within another application.

    Run on a local computer from within another program calledApplet Viewer. To view an applet, it must be called fromwithin another document written in HTML.

    Is programmed as a class, like JAVA application where itextends Applet class.

    Does not have mainmethod.

    Implements paintmethod

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    32/34

    EXAMPLEOF JAVA APPLETS

    import java.awt.*;

    import javax.swing.*;

    public class DisplayQuote extends JApplet

    {

    public void paint(Graphics g)

    {

    g.drawString(Anyone who spends their life on a computer is pretty unusual., 20, 30);

    }

    }

    Quotation

    Filename : DisplayQuote.java

    Filename : Quote.html

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    33/34

    TEST YOURSELF

    1. Declare an array of char.

    Initialize with value:

    p r o g r a m m i n g

    2. Declare two Strings withvalue :

    i. programming

    ii. program

    3. Find length char array in

    (1) and first String in (2).

    4. Find element/value for

    chararray[3] and first

    String using charAt(3).

    5. Substring firstString

    with (0,7)6. Compare (5) with

    second String.

    7. Concatenate second

    String and first String.

  • 7/30/2019 CSC238 - 2) Java Programming Basics (Part 2)

    34/34

    END.

    Thank you.