Java Programming. String Processing. 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
|
|
- Jacob Higgins
- 6 years ago
- Views:
Transcription
1 Java Programming String Processing 1 Copyright 2013, Oracle and/or its affiliates. All rights
2 Overview This lesson covers the following topics: Read, search, and parse Strings Use StringBuilder to create Strings Use regular expressions to search, parse, and replace Strings 2 Copyright 2013, Oracle and/or its affiliates. All rights
3 Strings The String object can be interpreted as a group of characters in a single memory location. Strings, like arrays, begin their index at 0 and end their index at StringName.length()-1. There are many different ways of approaching String manipulation. 3 Copyright 2013, Oracle and/or its affiliates. All rights
4 Using a FOR Loop One way to manipulate Strings is to use a FOR loop. This code segment initializes a String and increments through its characters, printing each one to the console. String str = Sample String ; for(int index=0;index<str.length();index++){ System.out.print(str.charAt(index));} 4 Copyright 2013, Oracle and/or its affiliates. All rights
5 Benefits to Using a FOR Loop Using the FOR loop method of incrementing through a String is beneficial if you desire to: Search for a specific character or String inside of the String. Read the String backwards (from last element to first element). Parse the String. 5 Copyright 2013, Oracle and/or its affiliates. All rights
6 Print String to Console An easier way to print a String to the console does not involve incrementing through the String. This code is shown below. System.out.print(str); 6 Copyright 2013, Oracle and/or its affiliates. All rights
7 Common String Methods A few other common String methods are: String Method length() Description Returns the number of characters in the String. chatat(int i) Returns the character at index i. substring(int start) substring(int start, int end) replace(char oldc, char newc) Returns part of the String from index start to the end of the String. Returns part of the String from index start to index end, but does not include the character at index end. Returns a String where all occurrences of character oldc have been replaced with newc. 7 Copyright 2013, Oracle and/or its affiliates. All rights
8 Searching and Strings There are a few different ways to search for a specific character or String inside of the String. The first is a for loop, which can be altered to search, count, or replace characters or Substrings contained in Strings. 8 Copyright 2013, Oracle and/or its affiliates. All rights
9 Searching and Strings Example The code below uses a for loop to count the number of spaces found in the String. String str = Searching for spaces ; int count=0; for(int i=0;i<str.length();i++){ if(str.charat(i)==' ') count++; } Since the index of a String begins at 0, we must begin searching for a ' ' at index 0. Search through the String until the index reaches the last element of the String, which is at index.strlength()-1. This means that i cannot be > or = to the str.length(). If it does exceed str.length()-1, an "index out of bounds" error will occur. 9 Copyright 2013, Oracle and/or its affiliates. All rights
10 Calling Methods on the String Other ways to search for something in a String is by calling any of the following methods on the String. These methods are beneficial when working with programming problems that involve the manipulation of Strings. String Method Description contains(charsequence s) Returns true if the String contains s. indexof(char ch) indexof(string str) Returns the index within this String of the first occurrence of the specified character and -1 if the character is not in the String. Returns the index within this String of the first occurrence of the specified Substring and -1 if the String does not contain the Substring str. 10 Copyright 2013, Oracle and/or its affiliates. All rights
11 Reading Strings Backwards Typically a String is read from left to right. To read a String backwards, simply change the starting index and ending index of the FOR loop that increments through the String. String str = Read this backwards ; String strbackwards = ; for(int i=str.length()-1; i>=0 ; i--){ strbackwards+=str.substring(i,i+1); } Start the FOR loop at the last index of the array (which is str.length()-1), and decrease the index all the way through to the first index (which is 0). 11 Copyright 2013, Oracle and/or its affiliates. All rights
12 Parsing a String Parsing means dividing a String into a set of Substrings. Typically, a sentence (stored as a String) is parsed by spaces to separate the words of the sentence rather than the whole sentence. This makes it easier to rearrange the words than if they were all together in one String. You may parse a String by any character or Substring. Below are two techniques for parsing a String: For loop Split 12 Copyright 2013, Oracle and/or its affiliates. All rights
13 Steps to Parsing a String with a For Loop 1. Increment through the for loop until you find the character or Substring where you wish to parse it. 2. Store the parsed components. 3. Update the String. 4. Manipulate the parsed components as desired. 13 Copyright 2013, Oracle and/or its affiliates. All rights
14 Steps to Parsing a String with a For Loop import java.util.*; public class StringParser { public static void main(string[] args) { String str = "Parse this String"; ArrayList<String> words = new ArrayList<String>(); } } while(str.length() > 0){ for(int i=0; i<str.length(); i++){ if(i==str.length()-1){ words.add(str.substring(0)); str = ""; break; } else if(str.charat(i)==' '){ words.add(str.substring(0,i)); str=str.substring(i+1); break; } } } for(string s : words) System.out.print(s + ' '); 14 Copyright 2013, Oracle and/or its affiliates. All rights
15 Parsing a String: Split Split is a method inside the String class that parses a String at specified characters, or if unspecified, spaces. It returns an array of Strings that contains the Substrings (or words) that parsing the String gives. How to call split on a String: String sentence = This is my sentence ; String[] words = sentence.split( ); //words will look like {This,is,my,sentence} String[] tokens = sentence.split( i ); //tokens will look like {Th,s,s my sentence} 15 Copyright 2013, Oracle and/or its affiliates. All rights
16 Split a String by More than One Character It is also possible to split a String by more than one specified character if you use brackets [ ] around the characters. Here is an example. String sentence = This is my sentence ; String[] tokens = sentence.split( [ie] ); //tokens will look like {Th,s,s my s,nt,nc} //each token is separated by any occurrence of //an i or any occurrence of an e. Notice how the brackets are used to include i and e. 16 Copyright 2013, Oracle and/or its affiliates. All rights
17 StringBuilder StringBuilder is a class that represents a String-like object. It is made of a sequence of characters, like a String. The difference between String and StringBuilder objects is that: StringBuilder includes methods that can modify the StringBuilder once it has been created by appending, removing, replacing, or inserting characters. Once created, a String cannot be changed. It is replaced by a new String instead. 17 Copyright 2013, Oracle and/or its affiliates. All rights
18 Strings Cannot be Modified It is not possible to make modifications to a String. Methods used to modify a String actually create a new String in memory with the specified changes, they do not modify the old one. This is why StringBuilders are much faster to work with: They can be modified and do not require you to create a new String with each modification. 18 Copyright 2013, Oracle and/or its affiliates. All rights
19 StringBuilder and String Shared Methods StringBuilder shares many of the same methods with String, including but not limited to: charat(int index) indexof(string str) length() substring(int start, int end) 19 Copyright 2013, Oracle and/or its affiliates. All rights
20 StringBuilder Methods StringBuilder also has some methods specific to its class, including the four below: Method append(type t) delete(int start, int end) insert(int offset, Type t) replace(int start, int end, String str) Description Is compatible with any Java type or object, appends the String representation of the Type argument to the end of the sequence. Removes the character sequence included in the Substring from start to end. Is compatible with any Java type, inserts the String representation of Type argument into the sequence. Replaces the characters in a Substring of this sequence with characters in str. 20 Copyright 2013, Oracle and/or its affiliates. All rights
21 Methods to Search Using a StringBuilder Searching using a StringBuilder can be done using either of the below methods: Method charat(int index) Description Returns the character at index. indexof(string str, int fromindex) Returns index of first occurrence of str. 21 Copyright 2013, Oracle and/or its affiliates. All rights
22 StringBuilder versus String StringBuilder Changeable Easier insertion, deletion, and replacement. Can be more difficult to use, especially when using regular expressions introduced on the next few slides. Use when memory needs to be conserved. String Immutable Easier concatenation. Visually simpler to use, similar to primitive types rather than objects. Use with simpler programs where memory is not a concern. 22 Copyright 2013, Oracle and/or its affiliates. All rights
23 Regular Expressions A regular expression is a character or a sequence of characters that represent a String or multiple Strings. Regular expressions: Are part of the java.util.regex package, thus any time regular expressions are used in your program you must import this package. Syntax is different than what you are used to but allows for quicker, easier searching, parsing, and replacing of characters in a String. 23 Copyright 2013, Oracle and/or its affiliates. All rights
24 String.matches(String regex) The String class contains a method matches(string regex) that returns true if a String matches the given regular expression. This is similar to the String method equals(string str). The difference is that comparing the String to a regular expression allows variability. For example, how would you write code that returns true if the String animal is cat or dog and returns false otherwise? 24 Copyright 2013, Oracle and/or its affiliates. All rights
25 Equals Versus Matches A standard answer may look something like this: if(animal.equals( cat )) return true; else if(animal.equals( dog )) return true; return false; An answer using regular expressions would look something like this: return animal.matches( cat dog ); The second solution is much shorter. The regular expression symbol allows for the method matches to check if animal is equal to cat or dog and return true accordingly. 25 Copyright 2013, Oracle and/or its affiliates. All rights
26 Square Brackets Square brackets are used in regular expression to allow for character variability. For example, if you wanted to return true if animal is equal to dog or Dog, but not dog, using equalsignorecase would not work and using equals would take time and multiple lines. If you use regular expression, this task can be done in one line as follows. This code tests if animal matches Dog or dog and returns true if it does. return animal.matches( [Dd]og ); 26 Copyright 2013, Oracle and/or its affiliates. All rights
27 Include Any Range of Characters Square brackets aren't restricted to two character options. They can be combined with a hyphen to include any range of characters. For example, you are writing code to create a rhyming game and you want to see if String word rhymes with banana. The definition of a rhyming word is a word that contains all the same letters except the first letter may be any letter of the alphabet. Your first attempt at coding may look like this: if(word.length()==6) if(word.substring(1,6).equals( anana )) return true; return false; 27 Copyright 2013, Oracle and/or its affiliates. All rights
28 Using Square Brackets and a Hyphen A shorter, more generic way to complete the same task is to use square brackets and a hyphen (regular expression) as shown below. return word.matches( [a-z]anana ); This code returns true if word begins with any lower case letter and ends in anana. To include upper case characters we would write: return word.matches( [a-za-z]anana ); 28 Copyright 2013, Oracle and/or its affiliates. All rights
29 Using Square Brackets and a Hyphen To allow the first character to be any number or a space in addition to a lower or upper case character, simply add 0-9 inside the brackets (note the space before 0). return word.matches( [ 0-9a-zA-Z]anana ); 29 Copyright 2013, Oracle and/or its affiliates. All rights
30 The Dot The dot (.) is a representation for any character in regular expressions. For example, you are writing a decoder for a top secret company and you think that you have cracked the code. You need to see if String element consists of a number followed by any other single character. This task is done easily with use of the dot as shown below. This code returns true if element consists of a number followed by any character. The dot matches any character. return element.matches( [0-9]. ); 30 Copyright 2013, Oracle and/or its affiliates. All rights
31 Repetition Operators A repetition operator is any symbol in regular expressions that indicates the number of times a specified character appears in a matching String. Repetition Operator * Definition Sample Code Code Meaning 0 or more occurrences return str.matches( A* ); Returns true if str consists of zero or more A's but no other letter.? 0 or 1 occurrence return str.matches( A? ); Returns true if str is or A. + 1 or more occurrences return str.matches( A+ ); Returns true if str is 1 or more A's in a sequence. 31 Copyright 2013, Oracle and/or its affiliates. All rights
32 More Repetition Operators Repetition Operator Definition Sample Code Code Meaning {x} X occurrences return str.matches( A{7} ); {x,y} {x,} Between x & y occurrences X or more occurrences return str.matches( A{7,9} ); Return str.matches( A{5,} ); Returns true if str is a sequence of 7 A's. Returns true if str is a sequence of 7, 8, or 9 A's. Returns true if str is a sequence of 5 or more A's. 32 Copyright 2013, Oracle and/or its affiliates. All rights
33 Combining Repetition Operators Example 1 In the code below: The dot represents any character. The asterisk represents any number of occurrences of the character preceding it. The.* means any number of any characters in a sequence will return true. return str.matches(.* ); 33 Copyright 2013, Oracle and/or its affiliates. All rights
34 Combining Repetition Operators Example 2 If the code below returns true, str must be a sequence of 10 digits (between 0 and 5) and may have 0 or 1 characters preceding the sequence. Remember, all symbols of regular expressions may be combined with each other, as shown below, and with standard characters. return str.matches(.?[0-5]{10} ); 34 Copyright 2013, Oracle and/or its affiliates. All rights
35 Pattern A Pattern is a class in the java.util.regex package that stores the format of the regular expression. For example, to initialize a Pattern of characters as defined by the regular expression [A-F]{5,}.* you would write the following code: Pattern p = Pattern.compile( [A-F]{5,}.* ); The compile method returns a Pattern as defined by the regular expression given in the parameter. 35 Copyright 2013, Oracle and/or its affiliates. All rights
36 Matcher A matcher is a class in the java.util.regex package that stores a possible match between the Pattern and a String. A Matcher is initialized as follows: Matcher match = patternname.matcher(stringname); The matcher method returns a Matcher object. The following code returns true if the regular expression given in the Pattern patternname declaration matches the String StringName. return match.matches(); 36 Copyright 2013, Oracle and/or its affiliates. All rights
37 Matcher: Putting it All Together To put it all together, we have: Pattern p = Pattern.compile( [A-F]{5,}.* ); Matcher match = patternname.matcher(stringname); return match.matches(); 37 Copyright 2013, Oracle and/or its affiliates. All rights
38 Benefits to Using Pattern and Matcher This seems like a very complex way of completing the same task as the String method matches. Although that may be true, there are benefits to using a Pattern and Matcher such as: Capturing groups of Strings and pulling them out, allowing to keep specific formats for dates or other specific formats without having to create special classes for them. Matches has a find() method that allows for detection of multiple instances of a pattern within the same String. 38 Copyright 2013, Oracle and/or its affiliates. All rights
39 Regular Expressions and Groups Segments of regular expressions can be grouped using parentheses, opening the group with ( and closing it with ). These groups can later be accessed with the Matcher method group(groupnumber). For example, consider reading in a sequence of dates, Strings in the format DD/MM/YYYY, and printing out each date in the format MM/DD/YYYY. Using groups would make this task quite simple. 39 Copyright 2013, Oracle and/or its affiliates. All rights
40 Regular Expressions and Groups Example import java.util.regex.pattern; import java.util.regex.matcher; import java.util.scanner; <Enter first-level introductory paragraph, sentence, or public class RegExpressionsPractice { phrase public static here.> void main(string[] (24 pt args) Arial { Regular) Group 1 Group 2 } Pattern datep; <Enter datep second-level = Pattern.compile("([0-9]{2})/([0-9]{2})/([0-9]{4})"); bullet text here.> (22 pt Arial Regular) Scanner in = new Scanner(System.in); <Enter System.out.println("Enter third-level bullet a Date: text (dd/mm/yyyy)"); here.> (20 pt Arial Regular) Group 3 } while(!date.equals("")){ <Enter fourth-level bullet text here.> (18 pt Arial Regular) 40 Copyright 2013, Oracle and/or its affiliates. All rights String date = in.nextline(); Matcher datem = datep.matcher(date); Recalls each group <Enter if(datem.matches()){ fifth-level bullet text here.> (16 pt Arial Regular) of the Matcher. String day = datem.group(1); String month = datem.group(2); String year = datem.group(3); System.out.println(month+"/"+day+"/"+year); } System.out.println("Enter a Date: (dd/mm/yyyy)"); date=in.nextline(); } Group 1 and Group 2 are defined to consist of 2 digits each. Group 3 (the year) is defined to consist of 4 digits. Note: It is still possible to get the whole Matcher by calling group (0).
41 Matcher.find() Matcher's find method will return true if the defined Pattern exists as a Substring of the String of the Matcher. For example, if we had a pattern defined by the regular expression [0-9], as long as we give the Matcher a String that contains at least one digit somewhere in the String, calling find() on this Matcher will return true. 41 Copyright 2013, Oracle and/or its affiliates. All rights
42 Parsing a String with Regular Expressions Recall the String method split() introduced earlier in the lesson, which splits a String by spaces and returns the split Strings in an array of Strings. The split method has an optional parameter, a regular expression that describes where the operator wishes to split the String. For example, if we wished to split the String at any sequence of one or more digits, we could write something like this: String[] tokens = str.split( [0-9]+ ); 42 Copyright 2013, Oracle and/or its affiliates. All rights
43 Replacing with Regular Expressions There are a few simple options for replacing Substrings using regular expressions. The following two are the most commonly used methods. For use with Strings, the method replaceall( insertregularexpressionhere, newsubstring) will replace all occurrences of the defined regular expression found in the String with the defined String newsubstring. 43 Copyright 2013, Oracle and/or its affiliates. All rights
44 replaceall Method This method works the same if called by a Matcher rather than a String. However, it does not require the regular expression. It will simply replace any matches of the Pattern you gave it when you initialized the Matcher. The method example shown below results in a replacement of all matches identified by Matcher with the String abc. MatcherName.replaceAll( abc ); 44 Copyright 2013, Oracle and/or its affiliates. All rights
45 Terminology Key terms used in this lesson included: Matcher Parsing Pattern Regular Expression Regular Expression Dot 45 Copyright 2013, Oracle and/or its affiliates. All rights
46 Terminology Key terms used in this lesson included: Regular Expression Groups Regular Expression Square Brackets Repetition Operator Split StringBuilder 46 Copyright 2013, Oracle and/or its affiliates. All rights
47 Summary In this lesson, you should have learned how to: Read, search, and parse Strings Use StringBuilder to create Strings Use regular expressions to search, parse, and replace Strings 47 Copyright 2013, Oracle and/or its affiliates. All rights
CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals
CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasketEnhanced { public static void main(string[]
More information"Hello" " This " + "is String " + "concatenation"
Strings About Strings Strings are objects, but there is a special syntax for writing String literals: "Hello" Strings, unlike most other objects, have a defined operation (as opposed to a method): " This
More informationH212 Introduction to Software Systems Honors
Introduction to Software Systems Honors Lecture #04: Fall 2015 1/20 Office hours Monday, Wednesday: 10:15 am to 12:00 noon Tuesday, Thursday: 2:00 to 3:45 pm Office: Lindley Hall, Room 401C 2/20 Printing
More informationCIS 1068 Design and Abstraction Spring 2017 Midterm 1a
Spring 2017 Name: TUID: Page Points Score 1 28 2 18 3 12 4 12 5 15 6 15 Total: 100 Instructions The exam is closed book, closed notes. You may not use a calculator, cell phone, etc. i Some API Reminders
More informationSTUDENT LESSON A10 The String Class
STUDENT LESSON A10 The String Class Java Curriculum for AP Computer Science, Student Lesson A10 1 STUDENT LESSON A10 The String Class INTRODUCTION: Strings are needed in many programming tasks. Much of
More informationActivity 9: Object-Oriented
Activity 9: Object-Oriented Internally, the library class java.lang.string stores an array of characters. It also provides a variety of useful methods for comparing, manipulating, and searching text in
More informationObject-Oriented Software Engineering CS288
Object-Oriented Software Engineering CS288 1 Regular Expressions Contents Material for this lecture is based on the Java tutorial from Sun Microsystems: http://java.sun.com/docs/books/tutorial/essential/regex/index.html
More informationStrings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.
Strings Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and
More informationActivity 9: Object-Oriented
Activity 9: Object-Oriented Internally, the library class java.lang.string stores an array of characters. It also provides a variety of useful methods for comparing, manipulating, and searching text in
More informationDiscover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.
Java SE11 Development Java is the most widely-used development language in the world today. It allows programmers to create objects that can interact with other objects to solve a problem. Explore Java
More informationSTRINGS AND STRINGBUILDERS. Spring 2019
STRINGS AND STRINGBUILDERS Spring 2019 STRING BASICS In Java, a string is an object. Three important pre-built classes used in string processing: the String class used to create and store immutable strings
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationIntro to Strings. Lecture 7 CGS 3416 Spring February 13, Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, / 16
Intro to Strings Lecture 7 CGS 3416 Spring 2017 February 13, 2017 Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, 2017 1 / 16 Strings in Java In Java, a string is an object. It is not a primitive
More informationStrings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics
Strings Strings and their methods Produced by: Dr. Siobhán Drohan Department of Computing and Mathematics http://www.wit.ie/ Topics list Primitive Types: char Object Types: String Primitive vs Object Types
More informationAP Computer Science. Strings. Credit: Slides are modified with permission from Barry Wittman at Elizabethtown College
Strings AP Computer Science Credit: Slides are modified with permission from Barry Wittman at Elizabethtown College This work is licensed under an Attribution-NonCommercial-ShareAlike 3.0 Unported License
More informationLecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8
Today... Java basics S. Bowers 1 of 8 Java main method (cont.) In Java, main looks like this: public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); Q: How
More information2. All the strings gets collected in a special memory are for Strings called " String constant pool".
Basics about Strings in Java 1. You can create Strings in various ways:- a) By Creating a String Object String s=new String("abcdef"); b) By just creating object and then referring to string String a=new
More informationThere are several files including the start of a unit test and the method stubs in MindNumber.java. Here is a preview of what you will do:
Project MindNumber Collaboration: Solo. Complete this project by yourself with optional help from section leaders. Do not work with anyone else, do not copy any code directly, do not copy code indirectly
More informationAssoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.
Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All Advanced Java This chapter discusses class String, class StringBuilder and class Character from the java.lang package. These classes provide
More informationCSE1710. Big Picture. Today is last day covering Ch 6. Tuesday, Dec 02 is designated as a study day. No classes. Thursday, Dec 04 is last lecture.
CSE1710 Click to edit Master Week text 12, styles Lecture 23 Second level Third level Fourth level Fifth level Fall 2014! Thursday, Nov 27, 2014 1 Big Picture Today is last day covering Ch 6 Tuesday, Dec
More informationArray Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)
Array Basics: Outline Arrays (Savitch, Chapter 7) TOPICS Array Basics Arrays in Classes and Methods Programming with Arrays Searching and Sorting Arrays Multi-Dimensional Arrays Static Variables and Constants
More informationIntro to Strings. Lecture 7 COP 3252 Summer May 23, 2017
Intro to Strings Lecture 7 COP 3252 Summer 2017 May 23, 2017 Strings in Java In Java, a string is an object. It is not a primitive type. The String class is used to create and store immutable strings.
More informationCONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2
CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,
More informationCh. 6. User-Defined Methods
Ch. 6 User-Defined Methods Func5onal Abstrac5on Func5onal regarding func5ons/methods Abstrac5on solving a problem in a crea5ve way Stepwise refinement breaking down large problems into small problems The
More information- Thus there is a String class (a large class)
Strings - Strings in Java are objects - Thus there is a String class (a large class) - In a statement like this: System.out.println( Hello World ); the Java compiler creates a String object from the quoted
More informationInterpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled
Interpreted vs Compiled Python 1 Java Interpreted Easy to run and test Quicker prototyping Program runs slower Compiled Execution time faster Virtual Machine compiled code portable Java Compile > javac
More informationIntroduction to Java & Fundamental Data Types
Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains
More informationTop-Down Program Development
Top-Down Program Development Top-down development is a way of thinking when you try to solve a programming problem It involves starting with the entire problem, and breaking it down into more manageable
More informationMore on variables and methods
More on variables and methods Robots Learning to Program with Java Byron Weber Becker chapter 7 Announcements (Oct 12) Reading for Monday Ch 7.4-7.5 Program#5 out Character Data String is a java class
More informationCreating Java Programs with Greenfoot
Creating Java Programs with Greenfoot Using Loops, Variables, and Strings 1 Copyright 2012, Oracle and/or its affiliates. All rights Overview This lesson covers the following topics: Create a while loop
More informationA variable is a name for a location in memory A variable must be declared
Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;
More informationLesson 4 Utility classes: Math, String, I/O
Lesson 4 Utility classes: Math, String, I/O Programming Grade in Computer Engineering Outline 1. Math class 2. Wrapper classes 3. String management 4. Input and output Printing on the screen Reading from
More informationCOMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string
COMP 202 Built in Libraries and objects CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Objects and Built in Libraries 1 Classes and Objects An object is an
More informationLecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4
Assignments Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4 Lecture 6 Complete for Lab 4, Project 1 Note: Slides 12 19 are summary slides for Chapter 2. They overview much of what we covered but are not complete.
More informationLab 14 & 15: String Handling
Lab 14 & 15: String Handling Prof. Navrati Saxena TA: Rochak Sachan String Handling 9/11/2012 22 String Handling Java implements strings as objects of type String. Once a String object has been created,
More informationSTUDENT LESSON A12 Iterations
STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of
More informationString. Other languages that implement strings as character arrays
1. length() 2. tostring() 3. charat() 4. getchars() 5. getbytes() 6. tochararray() 7. equals() 8. equalsignorecase() 9. regionmatches() 10. startswith() 11. endswith() 12. compareto() 13. indexof() 14.
More informationLecture Set 4: More About Methods and More About Operators
Lecture Set 4: More About Methods and More About Operators Methods Definitions Invocations More arithmetic operators Operator Side effects Operator Precedence Short-circuiting main method public static
More informationAssoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.
Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All This chapter discusses class String, from the java.lang package. These classes provide the foundation for string and character manipulation
More informationCSE 114 Computer Science I
CSE 114 Computer Science I Iteration Cape Breton, Nova Scotia What is Iteration? Repeating a set of instructions a specified number of times or until a specific result is achieved How do we repeat steps?
More informationCOMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette
COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.
More informationFaculty of Science Midterm. COMP-202B - Introduction to Computing I (Winter 2008)
Student Name: Student Number: Section: Faculty of Science Midterm COMP-202B - Introduction to Computing I (Winter 2008) Friday, March 7, 2008 Examiners: Prof. Jörg Kienzle 18:15 20:15 Mathieu Petitpas
More informationYork University Fall 2001 / Test #1 Department of Computer Science
York University all 2001 / est #1 Department of Computer Science COSC1020.01 his is a closed book, 90-minute test. ill in your personal data below and wait. You may use pen or pencil but answers written
More informationCMSC 132: Object-Oriented Programming II
CMSC 132: Object-Oriented Programming II Regular Expressions & Automata Department of Computer Science University of Maryland, College Park 1 Regular expressions Notation Patterns Java support Automata
More informationCS212 Midterm. 1. Read the following code fragments and answer the questions.
CS1 Midterm 1. Read the following code fragments and answer the questions. (a) public void displayabsx(int x) { if (x > 0) { System.out.println(x); return; else { System.out.println(-x); return; System.out.println("Done");
More informationObject-Oriented Programming
Data structures Object-Oriented Programming Outline Primitive data types String Math class Array Container classes Readings: HFJ: Ch. 13, 6. GT: Ch. 13, 6. Đại học Công nghệ - ĐHQG HN Data structures 2
More informationStrings. Strings and their methods. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics
Strings Strings and their methods Produced by: Mairead Meagher Dr. Siobhán Drohan Department of Computing and Mathematics http://www.wit.ie/ Topics list Primitive Types: char Object Types: String Primitive
More informationclass Ideone { public static void main (String[] args) throws java.lang.exception {
1. wap to enter a string then convert it into upper case Input:- san deep output : SaN DEEp import java.util.*; import java.lang.*; class Ideone public static void main (String[] args) throws java.lang.exception
More informationComputational Expression
Computational Expression Variables, Primitive Data Types, Expressions Janyl Jumadinova 28-30 January, 2019 Janyl Jumadinova Computational Expression 28-30 January, 2019 1 / 17 Variables Variable is a name
More informationCHAPTER 7 OBJECTS AND CLASSES
CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and
More informationUsing Java Classes Fall 2018 Margaret Reid-Miller
Using Java Classes 15-121 Fall 2018 Margaret Reid-Miller Today Strings I/O (using Scanner) Loops, Conditionals, Scope Math Class (random) Fall 2018 15-121 (Reid-Miller) 2 The Math Class The Math class
More informationGetting started with Java
Getting started with Java Magic Lines public class MagicLines { public static void main(string[] args) { } } Comments Comments are lines in your code that get ignored during execution. Good for leaving
More informationCreating Strings. String Length
Strings Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and
More informationFull file at
Chapter 1 Primitive Java Weiss 4 th Edition Solutions to Exercises (US Version) 1.1 Key Concepts and How To Teach Them This chapter introduces primitive features of Java found in all languages such as
More informationCourse Outline. Introduction to java
Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.
More informationTEST (MODULE:- 1 and 2)
TEST (MODULE:- 1 and 2) What are command line arguments? Write a program in JAVA to print Fibonacci series using command line arguments? [10] Create a class employee with data members empid, empname, designation
More informationSchool of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15
Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL
More informationwww.thestudycampus.com Methods Let s imagine an automobile factory. When an automobile is manufactured, it is not made from basic raw materials; it is put together from previously manufactured parts. Some
More informationRepetition. Chapter 6
Chapter 6 Repetition Goals This chapter introduces the third major control structure repetition (sequential and selection being the first two). Repetition is discussed within the context of two general
More informationRepetition. Chapter 6
Chapter 6 Repetition Goals This chapter introduces the third major control structure repetition (sequential and selection being the first two). Repetition is discussed within the context of two general
More informationData Structures COE 312 ExamII Preparation Exercises
Data Structures COE 312 ExamII Preparation Exercises 1. Patrick designed an algorithm called search2d that can be used to find a target element x in a two dimensional array A of size N = n 2. The algorithm
More informationCOE 212 Engineering Programming. Welcome to Exam I Tuesday November 11, 2014
1 COE 212 Engineering Programming Welcome to Exam I Tuesday November 11, 2014 Instructors: Dr. Bachir Habib Dr. George Sakr Dr. Joe Tekli Dr. Wissam F. Fawaz Name: Student ID: Instructions: 1. This exam
More informationLecture Set 4: More About Methods and More About Operators
Lecture Set 4: More About Methods and More About Operators Methods Definitions Invocations More arithmetic operators Operator Side effects Operator Precedence Short-circuiting main method public static
More informationChapter 9 Lab Text Processing and Wrapper Classes
Lab Objectives Chapter 9 Lab Text Processing and Wrapper Classes Use methods of the Character class and String class to process text Be able to use the StringTokenizer and StringBuffer classes Introduction
More informationWe now start exploring some key elements of the Java programming language and ways of performing I/O
We now start exploring some key elements of the Java programming language and ways of performing I/O This week we focus on: Introduction to objects The String class String concatenation Creating objects
More informationAppendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method
Appendix 3 Java - String charat() Method This method returns the character located at the String's specified index. The string indexes start from zero. public char charat(int index) index -- Index of the
More informationFollow this and additional works at: https://scholarlycommons.obu.edu/honors_theses Part of the Programming Languages and Compilers Commons
Ouachita Baptist University Scholarly Commons @ Ouachita Honors Theses Carl Goodson Honors Program 5-2018 Project Emerald Addison Bostian Ouachita Baptist University Follow this and additional works at:
More informationMethod OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters
Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split() Method from String Class Integer & Double Wrapper
More informationLoops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)
Loops! Flow of Control: Loops (Savitch, Chapter 4) TOPICS while Loops do while Loops for Loops break Statement continue Statement CS 160, Fall Semester 2014 2 An Example while Loop Step- by- step int count
More informationLast Class. While loops Infinite loops Loop counters Iterations
Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();
More informationNetbeans tutorial:
COE808 Lab2 Prelab preparation Before coming to the lab you should: 1. Read the lab. The most recent version can be found at the URL: www.ee.ryerson.ca/~courses/coe808 2. Try to prepare any questions you
More informationComputer Components. Software{ User Programs. Operating System. Hardware
Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point
More informationProgramming with Java
Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules
More informationAP Computer Science Unit 1. Writing Programs Using BlueJ
AP Computer Science Unit 1. Writing Programs Using BlueJ 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save
More informationLecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4
Assignments Lecture 6 Complete for Project 1 Reading: 3.1, 3.2, 3.3, 3.4 Summary Program Parts Summary - Variables Class Header (class name matches the file name prefix) Class Body Because this is a program,
More informationRegular Expressions & Automata
Regular Expressions & Automata CMSC 132 Department of Computer Science University of Maryland, College Park Regular expressions Notation Patterns Java support Automata Languages Finite State Machines Turing
More informationIntroduction to Programming (Java) 4/12
Introduction to Programming (Java) 4/12 Michal Krátký Department of Computer Science Technical University of Ostrava Introduction to Programming (Java) 2008/2009 c 2006 2008 Michal Krátký Introduction
More informationThe for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming
The for Loop, Accumulator Variables, Seninel Values, and The Random Class CS0007: Introduction to Computer Programming Review General Form of a switch statement: switch (SwitchExpression) { case CaseExpression1:
More informationObject-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018
Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 1: Types and Control Flow http://courses.cs.cornell.edu/cs2110/2018su Lecture 1 Outline 2 Languages Overview Imperative
More informationappreciate the difference between a char and a string understand and use the String class methods
1 8 THE STRING CLASS Terry Marris 16 April 2001 8.1 OBJECTIVES By the end of this lesson the student should be able to appreciate the difference between a char and a string understand and use the String
More informationMr. Monroe s Guide to Mastering Java Syntax
Mr. Monroe s Guide to Mastering Java Syntax Getting Started with Java 1. Download and install the official JDK (Java Development Kit). 2. Download an IDE (Integrated Development Environment), like BlueJ.
More informationJava Coding 3. Over & over again!
Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java
More informationCS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.
Methods There s a method in my madness. Sect. 3.3, 8.2 1 Example Class: Car How Cars are Described Make Model Year Color Owner Location Mileage Actions that can be applied to cars Create a new car Transfer
More informationChapter 8: Strings and Things
Chapter 8: Strings and Things Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Word Of Fortune Program this will be cleared when it's working 1-2 Chapter Topics Chapter 8 discusses
More informationImportant Java terminology
1 Important Java terminology The information we manage in a Java program is either represented as primitive data or as objects. Primitive data פרימיטיביים) (נתונים include common, fundamental values as
More informationCSC 222: Object-Oriented Programming. Spring 2017
CSC 222: Object-Oriented Programming Spring 2017 Simulations & library classes HW3: RouletteWheel, RouletteGame, RouletteTester javadoc java.lang classes: String, Character, Integer java.util.random for
More informationSelec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program
More informationIntroduction to Java Applications
2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use
More informationUnit 14. Passing Arrays & C++ Strings
1 Unit 14 Passing Arrays & C++ Strings PASSING ARRAYS 2 3 Passing Arrays As Arguments Can we pass an array to another function? YES!! Syntax: Step 1: In the prototype/signature: Put empty square brackets
More informationAP Computer Science Unit 1. Writing Programs Using BlueJ
AP Computer Science Unit 1. Writing Programs Using BlueJ 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save
More informationCOMP 110 Programming Exercise: Simulation of the Game of Craps
COMP 110 Programming Exercise: Simulation of the Game of Craps Craps is a game of chance played by rolling two dice for a series of rolls and placing bets on the outcomes. The background on probability,
More informationJava Identifiers, Data Types & Variables
Java Identifiers, Data Types & Variables 1. Java Identifiers: Identifiers are name given to a class, variable or a method. public class TestingShastra { //TestingShastra is an identifier for class char
More informationProgramming with Java
Programming with Java String & Making Decision Lecture 05 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives By the end of this lecture you should be able to : Understand another
More information2.8. Decision Making: Equality and Relational Operators
Page 1 of 6 [Page 56] 2.8. Decision Making: Equality and Relational Operators A condition is an expression that can be either true or false. This section introduces a simple version of Java's if statement
More informationDr. Sarah Abraham University of Texas at Austin Computer Science Department. Regular Expressions. Elements of Graphics CS324e Spring 2017
Dr. Sarah Abraham University of Texas at Austin Computer Science Department Regular Expressions Elements of Graphics CS324e Spring 2017 What are Regular Expressions? Describe a set of strings based on
More informationAP Computer Science A
AP Computer Science A 1st Quarter Notes Table of Contents - section links Click on the date or topic below to jump to that section Date : 9/8/2017 Aim : Java Basics Objects and Classes Data types: Primitive
More informationAbout Codefrux While the current trends around the world are based on the internet, mobile and its applications, we try to make the most out of it. As for us, we are a well established IT professionals
More informationPreview from Notesale.co.uk Page 9 of 108
The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names. abstract assert boolean break byte case catch char class
More informationCSE 143 Au03 Midterm 2 Page 1 of 7
CSE 143 Au03 Midterm 2 Page 1 of 7 Question 1. (4 points) (a) If a precondition is not true when a method is called, two possible ways to detect and handle the situation are to use an assert statement
More informationCHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS
CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS Computers process information and usually they need to process masses of information. In previous chapters we have studied programs that contain a few variables
More information