Sunteți pe pagina 1din 34

CSC238 OBJECT ORIENTED PROGRAMMING

Topic 2 : Java Programming Basic (Part 2)


1

TOPIC COVERED
Character and String String manipulation

substring length indexOf concatenation

Array of primitive Predefined package

Date

CHARACTER
In

Java, single characters are represented using the data type char. constants are written as symbols enclosed in single quotes . are stored in a computer memory using some form of encoding. which stands for American Standard Code for Information Interchange, is one of the document coding schemes widely used today. uses Unicode, which includes ASCII, for representing char constants.

Character

Characters ASCII,

Java

CHARACTER

char ch1, ch2 = X;

Declaration and initialization

System.out.print("ASCII code of character X is " + (int) 'X' ); System.out.print("Character with ASCII code 88 is " + (char)88 );

Type conversion between int and char.

A < c

This comparison returns true because ASCII value of 'A' is 65 while that of 'c' is 99.

STRING
A

string is a sequence of characters that is treated as a single value. of the String class are used to represent strings in Java. can access individual characters of a string by calling the charAt method of the String object. are close to 50 methods defined in the String class. Example: substring, length, and indexOf. http://docs.oracle.com/javase/6/docs/api/java/lan g/String.html

Instances We

There

More:

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 .

STRING
Length

of the string is the number of characters 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

STRING

More examples:

The Mentalist Position of M: ? Position of second e: ? Position of : ? Length of the String: ?


String:

STRING

String Indexing

The position, or index, of the first character is 0.

SUBSTRING
Assume

str is a String object and properly initialized to a string. i, j ) will return a new string by extracting characters of str from position i to j-1 where 0 i length of str, 0 j length of str, and i j. str is programming , then str.substring(3, 7) will create a new string whose value is gram. original string str remains unchanged.

str.substring(

If

The

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

LENGTH
Assume

str is a String object and properly initialized to a string. ) will return the number of characters

str.length(

in str.
If

str is programming , then str.length( ) will return 11 because there are 11 characters in it.

EXAMPLE
String str1 = str2 = str3 = str4 = str1, str2, str3, str4; Hello ; Java ; ; //empty string ; //one space
5 4 0 1

str1.length( ) str2.length( ) str3.length( ) str4.length( )

INDEXOF
Assume

str and substr are String objects and properly initialized. will return the first position substr occurs in str.

str.indexOf(substr)

If

str is programming and substr is gram , then str.indexOf(substr) will return 3 because the position of the first character of substr in str is 3. substr does not occur in str, then 1 is returned. search is case-sensitive.

If

The

EXAMPLE
String str; str = I Love Java and Java loves me. ;

21

str.indexOf( J ) str.indexOf( love ) str.indexOf( ove ) str.indexOf( Me )

7
21 3 -1

CONCATENATION

Assume str1 and str2 are String objects and properly initialized. 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.

EXAMPLE

String str1, str2; str1 = Jon ; str2 = Java ;

str1 + str2 str1 + + str2

JonJava Jon Java Java, Jon Are you Jon?

str2 + , + str1
Are you + str1 + ?

ARRAYS OF PRIMITIVES

Array Declaration
<data type> [ ] <variable> //variation 1 <data type> <variable>[] //variation 2

Array Creation
<variable> = new <data type> [ <size> ]

ARRAYS OF PRIMITIVES

Example

Variation 1
double[ ] rainfall;

rainfall = new double[12];

Variation 2
double rainfall [ ]; rainfall = new double[12];

ACCESSING INDIVIDUAL ELEMENTS

Individual elements in an array accessed with the indexed expression.


double[] rainfall = new double[12];

rainfall

10

11

rainfall[2] The index of the first position in an array is 0.

This indexed expression refers to the element at position #3

ARRAY PROCESSING SAMPLE1


double[] rainfall = new double[12];

double

annualAverage,sum = 0.0;

The public constant length returns the capacity of an array.

for (int i = 0; i < rainfall.length; i++) { rainfall[i] = Double.parseDouble(

JOptionPane.showinputDialog(null,
); } annualAverage = sum / rainfall.length; "Rainfall for month " + (i+1) ) sum += rainfall[i];

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;
The same pattern for the remaining ten months.

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 actual month name instead of a number.

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

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 = new int[size];

PREDEFINED-PACKAGE

A package is a JAVA class library a collection of classes and interfaces 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 not outside. 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 the package the use of keyword import at the beginning of the JAVA application. Example : import java.util.*;

PREDEFINED-PACKAGE

java.lang package Most common Math class methods : pow(x,y),


sqrt(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 can be retrieved from GregorianCalendar object by using method get(). Method get() always returns an integer. Some of the possible argument 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

DATE

The Date class from the java.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( ) );

SIMPLE DATE 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);
10/31/03 October 31, 2003

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

EXAMPLE OF GREGORIANCALENDAR CLASS


import 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"); } }

USER DEFINED PACKAGE

How to create a package?


1. Include a statement package packagename; as the first statement of the source file for the class definition.

2. The class declaration must have a visibility modifier public


3. Create a folder/directory named the same name as your packagename. In JAVA, the package must have a one-to-one correspondence with the folder. 4. Place the classes and interfaces that you want to include in the package and compile it.

INTRODUCTION TO 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 called Applet Viewer. To view an applet, it must be called from within another document written in HTML. Is programmed as a class, like JAVA application where it extends Applet class. Does not have main method. Implements paint method

EXAMPLE OF JAVA APPLETS


Filename : DisplayQuote.java
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); } }

Filename : Quote.html

<html> <title> Quotation </title> <applet code = DisplayQuote.class width=400 height=200 > </applet> </html>

TEST YOURSELF
Declare an array of char. Initialize with value: p r o g r a m m i n g
1. 2. 4.

Find element/value for char array[3] and first String using charAt(3). Substring first String with (0,7) Compare (5) with second String. Concatenate second String and first String.

5.

Declare two Strings with value :


i. ii.

programming program

6.

7.

3.

Find length char array in (1) and first String in (2).

END.
Thank you.

S-ar putea să vă placă și