Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3 : Basic Concept Of Java

Similar presentations


Presentation on theme: "Chapter 3 : Basic Concept Of Java"— Presentation transcript:

1 Chapter 3 : Basic Concept Of Java
Prepared By Madam Zanariah Idrus

2 CONTENT Identifiers in Java Data types Wrapper classes
The ‘+’ operator How to design main class Control structures

3 Identifiers in Java An identifier is a sequence of characters that can be used to name entities such as variables, methods, classes and packages in a java program. Rules for naming identifiers in java: must start with an alphabet or the underscore symbol. the remaining characters must be letters, digit, or the underscore symbol. spaces and other special characters are not permitted. keywords are also not allowed to be used as identifiers. identifiers are also case-sensitive, that is Number and NumBer are treated as two different identifiers. Examples: MySalaryRM Number19 computeDiscount

4 Data Types There are two categories of data types which are:
Primitive data types Predefined class

5 Primitive Data type Primitive data types
When writing programs we need to specify the data types that we are working with. Examples java primitive data types are: int, double, float, char and boolean.

6 Predefined Class Predefined class
Predefined class is the class that provide by Java program. String data type is not a primitive data type in Java. A string is sequence of character enclosed by the double quotes (“ “). Java provides the String class, the StringBuffer class and StringTokenizer class for storing and processing strings. Examples creating a string: String message= “Welcome to UiTM!”; String message= new String (“Welcome to UiTM!”);

7 Intro to OOP with Java, C. Thomas Wu
Characters In Java, single characters are represented using the data type char. Character constants are written as symbols enclosed in single quotes. Characters are stored in a computer memory using some form of encoding. ASCII, which stands for American Standard Code for Information Interchange, is one of the document coding schemes widely used today. Java uses Unicode, which includes ASCII, for representing char constants. ©The McGraw-Hill Companies, Inc.

8 Intro to OOP with Java, C. Thomas Wu
ASCII Encoding For example, character 'O' is 79 (row value 70 + col value 9 = 79). O 9 70 Characters can be stored in a computer memory using the ASCII encoding. The ASCII codes range from 0 to 127. The character 'A' is represented as 65, for example. The ASCII values from 0 to 32 are called nonprintable control characters. For example, ASCII code 04 eot stands for End of Transmission. We can use this character to signal the end of transmission of data when sending data over a communication line. ©The McGraw-Hill Companies, Inc.

9 Intro to OOP with Java, C. Thomas Wu
Unicode Encoding The Unicode Worldwide Character Standard (Unicode) supports the interchange, processing, and display of the written texts of diverse languages. Java uses the Unicode standard for representing char constants. char ch1 = 'X'; System.out.println(ch1); System.out.println( (int) ch1); ASCII works well for English-language documents because all characters and punctuation marks are included in the ASCII codes. But ASCII codes cannot be used to represent character sets of other languages. To overcome this limitation, unicode encoding was proposed. Unicode uses two bytes to represent characters and adopts the same encoding for the first 127 values as the ASCII codes. Encoding value of a character can be accessed by converting it to an int as the sample code illustrates. X 88 ©The McGraw-Hill Companies, Inc.

10 Intro to OOP with Java, C. Thomas Wu
Character Processing Declaration and initialization char ch1, ch2 = ‘X’; Type conversion between int and char. System.out.print("ASCII code of character X is " + (int) 'X' ); System.out.print("Character with ASCII code 88 is " + (char)88 ); This comparison returns true because ASCII value of 'A' is 65 while that of 'c' is 99. ‘A’ < ‘c’ ©The McGraw-Hill Companies, Inc.

11 Intro to OOP with Java, C. Thomas Wu
Strings A string is 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 string by calling the charAt method of the String object. We introduced the String class in Chapter 2. We will study additional String methods. ©The McGraw-Hill Companies, Inc.

12 Accessing Individual Elements
Intro to OOP with Java, C. Thomas Wu Accessing Individual Elements Individual characters in a String accessed with the charAt method. String name = "Sumatra"; 1 2 3 4 5 6 S u m a t r name This variable refers to the whole string. name.charAt( 3 ) The method returns the character at position # 3. ©The McGraw-Hill Companies, Inc.

13 Example: Counting Vowels
Intro to OOP with Java, C. Thomas Wu Example: Counting Vowels char letter; String name = JOptionPane.showInputDialog(null,"Your name:"); int numberOfCharacters = name.length(); int vowelCount = 0; for (int i = 0; i < numberOfCharacters; i++) { letter = name.charAt(i); if ( letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' || letter == 'i' || letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U' ) { vowelCount++; } System.out.print(name + ", your name has " + vowelCount + " vowels"); Here’s the code to count the number of vowels in the input string. This sample code counts the number of vowels in a given input. Using the toUpperCase method, that converts all alphabetic characters to uppercase, we can rewrite the code as char letter; String name = inputBox.getString("What is your name?"); int numberOfCharacters = name.length(); int vowelCount = 0; String nameUpper = name.toUpperCase(); for (int i = 0; i < numberOfCharacters; i++) { letter = nameUpper.charAt(i); if ( letter == 'A' || letter == 'E' || letter == 'I' || letter == 'O' || letter == 'U' ) { vowelCount++; } System.out.print(name + ", your name has " + vowelCount + " vowels"); ©The McGraw-Hill Companies, Inc.

14 Example: Counting ‘Java’
Intro to OOP with Java, C. Thomas Wu Example: Counting ‘Java’ int javaCount = 0; boolean repeat = true; String word; while ( repeat ) { word = JOptionPane.showInputDialog(null,"Next word:"); if ( word.equals("STOP") ) { repeat = false; } else if ( word.equalsIgnoreCase("Java") ) { javaCount++; } Continue reading words and count how many times the word Java occurs in the input, ignoring the case. Notice how the comparison is done. We are not using the == operator. This sample code counts the number of times the word 'Java' is entered. Notice that we wrote word.equals( “STOP”) not word == “STOP” We described the differences in Lesson 5-2. In this situation, we need to use 'equals' because we are testing whether two String objects have the same sequence of characters. ©The McGraw-Hill Companies, Inc.

15 Other Useful String Operators
Intro to OOP with Java, C. Thomas Wu Other Useful String Operators Method Meaning compareTo Compares the two strings. str1.compareTo( str2 ) substring Extracts the a substring from a string. str1.substring( 1, 4 ) trim Removes the leading and trailing spaces. str1.trim( ) valueOf Converts a given primitive data value to a string. String.valueOf( ) startsWith Returns true if a string starts with a specified prefix string. str1.startsWith( str2 ) endsWith Returns true if a string ends with a specified suffix string. str1.endsWith( str2 ) Here are some examples: String str1 = “Java”, str2 = “ Wow “; str1.compareTo( “Hello” ); //returns positive integer //because str1 >= “Hello” str1.substring( 1, 4 ); //returns “ava” str2.trim( ) //returns “Wow”, str2 stays same str1.startsWith( “Ja” ); //returns true str1.endsWith( “avi” ); //returns false See the String class documentation for details. ©The McGraw-Hill Companies, Inc.

16 Intro to OOP with Java, C. Thomas Wu
Pattern Example Suppose students are assigned a three-digit code: The first digit represents the major (5 indicates computer science); The second digit represents either in-state (1), out-of-state (2), or foreign (3); The third digit indicates campus housing: On-campus dorms are numbered 1-7. Students living off-campus are represented by the digit 8. The 3-digit pattern to represent computer science majors living on-campus is We can use a pattern to represent a range of valid codes succintly. Without using the sample 3-digit pattern for computer science majors living on-campus, we must spell out 21 separate codes. 5[123][1-7] first character is 5 second character is 1, 2, or 3 third character is any digit between 1 and 7 ©The McGraw-Hill Companies, Inc.

17 Intro to OOP with Java, C. Thomas Wu
Regular Expressions The pattern is called a regular expression. Rules The brackets [ ] represent choices The asterisk symbol * means zero or more occurrences. The plus symbol + means one or more occurrences. The hat symbol ^ means negation. The hyphen – means ranges. The parentheses ( ) and the vertical bar | mean a range of choices for multiple characters. Regular expression allows us to express a large set of “words” (any sequence of symbols) succinctly. We use specially designated symbols such as the asterisk to formulate regular expressions. ©The McGraw-Hill Companies, Inc.

18 Regular Expression Examples
Intro to OOP with Java, C. Thomas Wu Regular Expression Examples Expression Description [013] A single digit 0, 1, or 3. [0-9][0-9] Any two-digit number from 00 to 99. [0-9&&[^4567]] A single digit that is 0, 1, 2, 3, 8, or 9. [a-z0-9] A single character that is either a lowercase letter or a digit. [a-zA-z][a-zA-Z0-9_$]* A valid Java identifier consisting of alphanumeric characters, underscores, and dollar signs, with the first character being an alphabet. [wb](ad|eed) Matches wad, weed, bad, and beed. (AZ|CA|CO)[0-9][0-9] Matches AZxx,CAxx, and COxx, where x is a single digit. Here are some examples of regular expressions. ©The McGraw-Hill Companies, Inc.

19 Data Types Predefined class Some method in the class String
Method Name Description 1 int length( ) Return the length of string message.length( ) return 16 2 charAt(index) Return the character at a particular index in a string. Note that the index of first character is 0. message.charAt(0)  returns the letter W message.charAt(11)  returns the letter U 3 substring (startIndex) Gets more than one consecutive character from a string. Returns a new string begins at the specified startindex until the end of the string. substring(11)  returns the string UiTM 4 substring(startIndex, endIndex) Returns a new string begins at the specified startindex until the character at index endindex -1 substring(11,15)  returns the string UiTM

20 Data Types Predefined class Some method in the class String
Method Name Description 5 equals(String2) Returns true if the calling object and string2 are identical, otherwisw returns false. String greeting1=“Hai”; String greeting2= “Hello”; greeting1.equals(greeting2) returns false greeting1.equals(“Hai”) returns true greeting1.equals(“HAi”) returns false 6 equalsIgnoreCase (String2) Returns true if the calling object is equal (ignoring whether the characters are lower case or uppercase). greeting1.equalsIgnoreCase(“HAI”) returns true

21 Data Types Predefined class Some method in the class String
Method Name Description 7 toLowerCase() Converts and returns all the characters in the string to lower case letter. message.toLowerCase() returns welcome to uitm 8 toUpperCase() Converts and returns all the characters in the string to upper case letter. message.toLowerCase() returns WELCOME TO UITM

22 Predefined class Usage Package Method Example Dialog Box javax.swing
showInputDialog(String) showMessageDialog(String) String w = JOptionPane.showInputDialog(null, “Enter name”); showMessageDialog(null, “Good Morning!”); Format output java.text class name = DecimalFormat format(String) DecimalFormat n = new DecimalFormat(“00.00”) To diplay decimal placeholder Mathematical Methods Static methods in class Math are used. abs(n) pow(n1, n2) sqrt(n1) round(n) min(x, y) int x = Math.pow(4,2);

23 Example:

24 Intro to OOP with Java, C. Thomas Wu
The replaceAll Method The replaceAll method replaces all occurrences of a substring that matches a given regular expression with a given replacement string. Replace all vowels with the String originalText, modifiedText; originalText = ...; //assign string modifiedText = ©The McGraw-Hill Companies, Inc.

25 The StringBuffer Class
Intro to OOP with Java, C. Thomas Wu The StringBuffer Class In many string processing applications, we would like to change the contents of a string. In other words, we want it to be mutable /changeable. Manipulating the content of a string, such as replacing a character, appending a string with another string, deleting a portion of a string, and so on, may be accomplished by using the StringBuffer class. If the situation calls for directing changing the contents of a string, then we use the StringBuffer class. ©The McGraw-Hill Companies, Inc.

26 Intro to OOP with Java, C. Thomas Wu
StringBuffer Example word : StringBuffer Java Before word : StringBuffer Diva After Changing a string Java to Diva This sample code illustrates how the original string is changed. Notice that the String class does not include the setCharAt method. The method is only defined in the mutable StringBuffer class. StringBuffer word = new StringBuffer("Java"); word.setCharAt(0, 'D'); word.setCharAt(1, 'i'); ©The McGraw-Hill Companies, Inc.

27 Intro to OOP with Java, C. Thomas Wu
Sample Processing char letter; String inSentence = JOptionPane.showInputDialog(null, "Sentence:"); StringBuffer tempStringBuffer = new StringBuffer(inSentence); int numberOfCharacters = tempStringBuffer.length(); for (int index = 0; index < numberOfCharacters; index++) { letter = tempStringBuffer.charAt(index); if ( letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' || letter == 'i' || letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U' ) { tempStringBuffer.setCharAt(index,'X'); } JOptionPane.showMessageDialog(null, tempStringBuffer ); Replace all vowels in the sentence with ‘X’. Notice how the input routine is done. We are reading in a String object and converting it to a StringBuffer object, because we cannot simply assign a String object to a StringBuffer variable. For example, the following code is invalid: StringBuffer strBuffer = inputBox.getString( ); We are required to create a StringBuffer object from a String object as in String str = "Hello"; StringBuffer strBuf = new StringBuffer( str ); You cannot input StringBuffer objects. You have to input String objects and convert them to StringBuffer objects. ©The McGraw-Hill Companies, Inc.

28 Wrapper Classes Java provides routine for converting String to a primitive data types or vice versa It is called wrapper classes because the classes constructed by wrapping a class structure around the primitive data types

29 Wrapper Classes Wrapper Class Method Description Example Integer
parseInt(String) Converts a string to int int x = Integer.parseInt(s); toString(x) Converts an int to string String s = Integer.toString(x); Long parseLong(string) Converts a string to long int Long x = Long.parseLong(s); Converts a long int to string String s = Long.toString(x); Float parseFloat(s) Converts a string to float float x = Float.parseFloat(s); Converts a float to string String s = Float.toString(x); Double parseDouble(s) Converts a string to double double x = Double.parseDouble(s); Converts a double to string String s = Double.toString(x);

30 Wrapper Classes

31 The “+” Operator The + operator denotes concatenation when used with Strings. Examples: String string1 = “Hello”; String string2= “Students”; The statement string1 + string2  Hello Students If one of the operands is a String, the other is not, then the non-string operand will be converted to a String. int integer1 = 122; string2 + integer1  “Students122” integer1 + string2  “122Students” “$” integer1  “$3122”

32 How to design main class
Design main/ application class Step 1: Define import statement package. The import statement package contains classes that perform input and output process. There are three import statements package that you can choose: import java.io.*; // for bufferedReader package import javax.swing.JOptionPane; //for GUI (pop up) interface import java.util.Scanner; // for Scanner package OR OR

33 How to design main class
Design main/ application class Step 2: Define main class name public class mainApp( you can choose your own name) { Step 3: Define main method public static void main ( String args [ ]) If you choose bufferedReader package for your input/output process, your main method must required to handle/throw the IOException: Examples: public static void main ( String args [ ]) throws IOException

34 How to design main class
Design main/ application class Step 4: Declare variable to hold input data String insert Step 5: Create object if you used bufferedReader or Scanner package BufferedReader package BufferedReader input = new BufferedReader ( new InputStreamReader ( System.in)); Scanner package Scanner sc = new Scanner ( System.in);

35 How to design main class
Design main/ application class Step 6: Input statement. If you choose: BufferedReader System.out.print(“Enter num 1: ”) //hold the input line insert = input. readLine( ); //read first line //data conversion num1= Integer.parseInt (insert); System.out.print(“Enter num 2: ”) num2= Integer.parseInt (insert);

36 How to design main class
Design main/ application class Step 6: Input statement. If you choose: JOptionPane insert= JOptionPane.showInputDialog (“Enter num1: ”); num1= Integer.parseInt(insert); insert= JOptionPane.showInputDialog (“Enter num2: ”); num2= Integer.parseInt(insert); Scanner System.out.print(“Enter num1:”); num1= sc.nextInt( ); System.out.print(“Enter num2:”); num2= sc.nextInt( );

37 How to design main class
Design main/ application class Step 7: Process/calculation total = num1 + num2; Step 8: Output statement. If you choose: BufferedReader OR Scanner System.out.println (num1 + “+” + num2 + “=“ + total); JOptionPane JOptionPane.showMessageDialog( null, num1 + “ +” num2 + “=“ + total);

38 How to design main class

39 Example main class definition
BufferedReader package

40 Example main class definition
JOptionPane package

41 Example main class definition
Scanner package

42 Control Structures There are three control structures 1. Sequence
Program start from the left to right, top to bottom statements in main ( ). 2. Selection/decision Program will carry out different actions depending on the nature of the inputs (condition). One-way, two-ways and multiple-ways. Including switch-case ( round number and character only). 3. Repetition/iteration Program will repeatedly execute one or more statements while the condition is true. Three types of repetition  while loop, do..while loop and for loop.

43 Control Structures

44 Examples of using control structures

45 Example program selection

46 Example program selection (switch)

47 Example program selection (switch)

48 Example program repetition

49 THE END


Download ppt "Chapter 3 : Basic Concept Of Java"

Similar presentations


Ads by Google