Strings Java PDF
Document Details
Uploaded by DeliciousHazel7074
STI
Tags
Related
- ADP262S-Prac 8-Exception-2024 PDF, Cape Peninsula University of Technology, 17 Apr 2024
- IP_Lecture_08_Latex PDF - SLIIT University
- Java Programming Fifth Edition - Characters, Strings, and the StringBuilder PDF
- Java Programming Fifth Edition: Characters, Strings, and StringBuilder - PDF
- Lecture 2 (Chapter 2) Introduction to Java Programming PDF
- Java Strings Learning Sheet - Programming 1 PDF
Summary
This document is a Java programming handout on Strings. It covers creating strings, comparing strings, String methods, and the immutability of the String class. It's likely part of a course or textbook on Java programming.
Full Transcript
IT1708 Strings Java provides the String class from the java.lang package to create and manipulate strings. String has its own methods for working with strings. The String class is not a primitive data type. A string is a sequence of characters. Every character in a string has a specific position in...
IT1708 Strings Java provides the String class from the java.lang package to create and manipulate strings. String has its own methods for working with strings. The String class is not a primitive data type. A string is a sequence of characters. Every character in a string has a specific position in the string, and the position of the first character starts at index 0. The length of a string is the number of characters in it. For example: String “Hello World” Character in the string ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘ ’ ‘W’ ‘o’ ‘r’ ‘l’ ‘d’ Index 0 1 2 3 4 5 6 7 8 9 10 The length of the string “Hello World” is 11. Creating Strings A String can be constructed by either of the following: directly assigning a string literal to a String object; or using the new keyword and String constructor to create a String object. The following statements are the most direct ways to create a string in Java: String strGreeting = “Hello World!”; String strName; strName = “Jess Diaz”; In the example statements, “Hello World!” and “Jess Diaz” are both string literals (note: string literals in Java are series of characters that will appear in output exactly as entered. String literals are constants.). Whenever the JVM encounters a string literal in a program, it creates a String object with its value. The following statement creates a String object in Java using the new keyword and the String constructor: String strGreeting = new String(“Hello World!”); The string literals with the same contents share the same memory location, while the constructed strings using the new keyword are stored in different memory locations. Consider the following String declarations: String str1 = “Computer”; String str2 = “Computer”; String str3 = new String(“Computer”); String str4 = new String(“Computer”); The String method, equals(), is used to compare the content of two (2) strings. The relational operator (==) is used to compare the references of two (2) objects. The following example statements compare the string literals and String objects: str1 == str2 // returns true, same memory location and same content str1 == str3 // returns false, different memory locations str1.equals(str3) // returns true, same contents str3 == str4 // returns false, different memory locations str3.equals(str4) // returns true, same contents Unlike primitive data types, the String class is immutable; once it is created, its contents cannot be changed. For example, consider the statements: int num = 0; num++; The variable, num, changed its value from 0 to 1, but in a String variable, its content cannot be changed by a method. 09 Handout 1 *Property of STI Page 1 of 3 IT1708 String Methods The String class provides methods to perform operations on strings. Table 1 shows the list of some commonly used String methods in Java. These methods can only create and return a new string that contains the result of the operation. Table 1: Some Methods in the Class String (Savitch, 2014) Method Description Example for String str = “Java”; Returns the character of a string based on str.charAt(2); charAt(index) the specified index //returns char ‘v’ Compares a string with another string. The str.compareTo(“Java’s”); method returns 0 if the string is equal to string (less characters) and a value greater than 0 if the string is greater than the other string (more characters). Returns a new string concatenated with str.concat(“ program”); concat(string) the value of the parameter Returns true if this string and the str.equals(“Java”); equals(string) specified string are equal; otherwise, Returns true if this string and the str.equals(“java”); specified string are equal, considering the letter to be the same; otherwise, returns false. Returns the index of the first occurrence str.indexOf(“a”); indexOf(string) of the specified string within this string. If //returns int value 1 not found, the method returns -1. Returns the index of the last occurrence of str.lastIndexOf(“a”); lastIndexOf(string) the specified string within this string. If //returns int value 3 not found, the method returns -1. Returns the length of the string in int str.length(); //returns 4 length() type Returns a new string having the same str.toLowerCase(); characters as this string, but with any unchanged. Returns a new string having the same str.toUpperCase(); characters as this string, but with any //returns a new string “JAVA” toUpperCase() uppercase letters converted to uppercase. The content of this String object is unchanged. Returns a new string having the same str.replace(‘a’, ‘o’); characters as this string, but with each //returns a new string “Jovo” replace(old_Char, new_Char) occurrence of specified old_char replaced by new_char. The content of this String object is unchanged. Returns a new string having the same str.substring(2); substring(start_index) characters as the substring begins at //returns a new string “va” specified start index through to the end of 09 Handout 1 *Property of STI Page 2 of 3 IT1708 Method Description Example for String str = “Java”; the string. The content of this String object is unchanged. Returns a new string having the same str.substring(1, 3); characters as the substring that begins at //returns a new string “av” specified index start through to but not substring(start, end) including the character at index end. The content of this String object is unchanged. Returns a new string having the same String str = “ Java Java ”; trim() characters as this string, but with leading str.trim(); Note: You can use a variable to specify the parameters of a method. For example: String str1 = “Java”, str2 = “ program”; System.out.println(str1.concat(str2)); REFERENCES: Baesens, B., Backiel, A., & Broucke, S. (2015). Beginning java programming: The object-oriented approach. Indiana: John Wiley & Sons, Inc. Farrell, J. (2014). Java programming, 7th edition. Boston: Course Technology, Cengage Learning. Savitch, W. (2014). Java: An introduction to problem solving and programming, 7th edition. California: Pearson Education, Inc. Strings (The Java™ Tutorials > Learning the Java Language > Numbers and Strings). (n.d.) Strings. Retrieved from docs.oracle.com website: https://docs.oracle.com/javase/tutorial/java/data/strings.html 09 Handout 1 *Property of STI Page 3 of 3 IT1708 Control Structure (Repetition) Java provides three (3) repetition (or looping) structures that are used to execute a block of statements repeatedly: while, for, and do…while loop. while, for, and do are all reserved words. while Loop The while loop repeats a block of statements while a given condition evaluates to true. It evaluates the condition before executing the loop body. The general form of the while loop in Java is: while (expression) { //statements } The expression is a loop condition enclosed in parentheses. The expression can be a relational or a logical expression that returns either true or false value. The statements enclosed in curly braces is called the loop body. The loop body can be either a simple or a compound statement. When executing the while loop, the expression provides an entry condition. If it evaluates to true, the loop body executes and the expression is reevaluated. If it evaluates again to true, the loop body continues to execute until the expression evaluates to false. A loop that continues to execute endlessly is called an infinite loop. To avoid an infinite loop, make sure that the loop body contains one (1) or more statements that ensure that the loop condition will eventually be false. Example: //this loop prints whole numbers from 0 to 10 int num = 0; while ( num = 80) { System.out.println(“The grade is B”); } else if (score >= 70) { System.out.println(“The grade is C”); } else if (score >= 60) { System.out.println(“The grade is D”); } else { System.out.println(“The grade is F”); } and if (temperature >= 50) { if (temperature >= 110) { System.out.println(“hot”); } else { System.out.println(“warm”); } } else { System.out.println(“cold”); } 07 Handout 1 *Property of STI Page 2 of 4 IT1708 Short-Circuit Evaluation Logical expressions in Java are evaluated using an efficient algorithm: short-circuit evaluation. Short-Circuit Evaluation – is a process in which the computer evaluates a logical expression from left to right and stops as soon as the value of the expression is determined. The logical AND (&&) and OR (||) are short-circuit operators. A short- circuit operator does not necessarily evaluate all of its operands. For example, consider the following statements: int a = 0, b = 1, c = 4, d = 4; if (a == b && c == d) { System.out.println(“Example statement.”); } In the example, Java evaluates the expression from left to right and does the following: Evaluates a == b to false. The evaluation stops, and the entire expression returns false without evaluating the expression, c == d because the && operator wants both its operands to be true. The same process happens with the OR (||) operator when the value of its left operand is true, then the evaluation stops, and the entire expression return true without evaluating its right operand. For example: int a = 0, b = 1, c = 4, d = 4; if (c == d || a == b) { System.out.println(“Example statement.”); } The short-circuit evaluation is used to make the operation faster. The switch Statement A switch statement allows a single variable to be tested for equality against a list of values and, depending on its value, executes a certain block of statements. Each value is called a case, and the variable being switched on is checked for each case. The general syntax of a switch statement is: switch (expression) { case value1: //statements break; case value2: //statements break;... case valuen: //statements break; default: //statements } In Java, switch, case, break, and default are all reserved words. The following rules are applied to a switch statement: The variable used in a switch statement can only be type: int, byte, short, char, and String. There can be any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. The value in the case statement must be the same data type as the variable in the switch statement. When the variable being switched on is equal to a case, then the statements following that case will execute until a break statement is reached. 07 Handout 1 *Property of STI Page 3 of 4 IT1708 When a break statement is reached, the switch terminates, and the flow control jumps to the next line following the switch statement. (Note: The break statement can only terminate the process of an enclosing switch statement or any repetition structures in which it appears.) Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. A switch statement may or may not have the default statement, which must appear at the end of the switch. The default statement is used for performing a task when none of the cases is true. No break is needed in the default statement. Consider the following example: char grade = ‘A’; switch (grade) { case ‘A’: System.out.println(“Excellent”); break; case ‘B’: System.out.println(“Very Good”); break; case ‘C’: System.out.println(“Good”); break; case ‘D’: System.out.println(“Satisfactory”); break; case ‘F’: System.out.println(“Failed”); break; default: System.out.println(“Invalid letter of grade.”); } In the example, the expression in the switch statement is a variable identifier. The variable grade is of char type. The valid values of grade are listed as cases. Each case specifies different statements to execute, depending on the value of grade. REFERENCES: Baesens, B., Backiel, A., & Broucke, S. (2015). Beginning java programming: The object-oriented approach. Indiana: John Wiley & Sons, Inc. Farrell, J. (2014). Java programming, 7th edition. Boston: Course Technology, Cengage Learning. Savitch, W. (2014). Java: An introduction to problem solving and programming, 7th edition. California: Pearson Education, Inc. 07 Handout 1 *Property of STI Page 4 of 4