Chapter 3 : Basic Concept Of Java

Slides:



Advertisements
Similar presentations
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 9 Characters and Strings.
Advertisements

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Java Programming Strings Chapter 7.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 9: Characters * Character primitives * Character Wrapper class.
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
Intro to OOP with Java, C. Thomas Wu Characters and Strings
Fundamental Programming Structures in Java: Strings.
Lab session 3 and 4 Topics to be covered Escape sequences Escape sequences Variables /identifiers Variables /identifiers Constants Constants assignment.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter Chapter 8 Characters and Strings.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
JavaScript, Third Edition
Characters and Strings. Representation of single characters Data type char is the data type that represents single characters, such as letters, numerals,
Lesson 3 – Regular Expressions Sandeepa Harshanganie Kannangara MBCS | B.Sc. (special) in MIT.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Characters, String and Regular expressions. Characters char data type is used to represent a single character. Characters are stored in a computer memory.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 9 Characters and Strings.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Characters In Java, single characters are represented.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (adapted from.
Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 1 Regular Expressions and String processing Animated Version.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
 Character set is a set of valid characters that a language can recognise.  A character represents any letter, digit or any other sign  Java uses the.
Introduction to Java Java Translation Program Structure
Java Overview. Comments in a Java Program Comments can be single line comments like C++ Example: //This is a Java Comment Comments can be spread over.
Introduction to Programming
Chapter 7: Characters, Strings, and the StringBuilder.
1 Textual Data Many computer applications manipulate textual data word processors web browsers online dictionaries.
Copyright Curt Hill Variables What are they? Why do we need them?
Jaeki Song JAVA Lecture 07 String. Jaeki Song JAVA Outline String class String comparisons String conversions StringBuffer class StringTokenizer class.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
String Definition A string is a set of characters that behaves as a single unit. The characters in a string include upper-case and lower- case letters,
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Data Types References:  Data Type:  In computer science and computer programming, a data type or simply type is a.
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
Strings A string is a sequence of characters that is treated as a single value. Strings are objects. We have been using strings all along. For example,
Crash course in the Java Programming Language
BASIC ELEMENTS OF A COMPUTER PROGRAM
Strings, Characters and Regular Expressions
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
String class.
2.5 Another Java Application: Adding Integers
Chapter 4 Intermediate (part 1)
Java Programming: From Problem Analysis to Program Design, 4e
Primitive Types Vs. Reference Types, Strings, Enumerations
Advanced Programming Behnam Hatami Fall 2017.
Chapter 7: Strings and Characters
MSIS 655 Advanced Business Applications Programming
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Chapter 2 - Introduction to Java Applications
Chapter 2: Basic Elements of Java
Chapter 2 Variables.
Strings A string is a sequence of characters that is treated as a single value. Strings are objects. We have been using strings all along. Every time.
elementary programming
Chapter 2: Introduction to C++.
Primitive Types and Expressions
Chap 2. Identifiers, Keywords, and Types
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

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

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

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

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

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.

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!”);

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.

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.

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.

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.

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.

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.

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.

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.

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( 123.4565 ) 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.

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.

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.

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.

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

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

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

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);

Example:

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 symbol @ String originalText, modifiedText; originalText = ...; //assign string modifiedText = originalText.replaceAll("[aeiou]","@"); ©The McGraw-Hill Companies, Inc.

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.

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.

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.

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

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);

Wrapper Classes

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” “$” + 3 + integer1  “$3122”

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

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

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);

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);

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( );

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);

How to design main class

Example main class definition BufferedReader package

Example main class definition JOptionPane package

Example main class definition Scanner package

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.

Control Structures

Examples of using control structures

Example program selection

Example program selection (switch)

Example program selection (switch)

Example program repetition

THE END