09 Objects III: String and StringBuffer, Singly (Doubly) Linked Lists
|
|
- Briana Lindsey
- 6 years ago
- Views:
Transcription
1 Exercises Software Development I 09 Objects III: String and StringBuffer, Singly (Doubly) Linked Lists December 10th, 2014 Software Development I Winter term 2014/2015 Priv.-Doz. Dipl.-Ing. Dr. Andreas Riener Institute for Pervasive Computing Johannes Kepler University Linz riener@pervasive.jku.at
2 I Strings: Introduction A String in Java is a complex data type (call by reference) that stores/ contains a sequence of characters (data type char) Notation Character sequence is enclosed in double quotes "..." Example: "this is a string" Basic operations on strings Comparison of strings, e.g., is greater, smaller, equal (lexicographical; as like in a telephone book) Concatenation of two or more strings ( + -operator) Searching for substrings Conversions (to lower case, to upper case characters) And many more (see class description) Software Development I // Exercises // 09 Strings & Lists // 3
3 Strings: Class String If not otherwise specified, you should use the existing class String in the Java API (java.lang.string) and its predefined and implemented methods public final class String extends Object implements Serializable {... // end String Objects of the class String are immutable Sometimes it seems that applying certain methods to a string does change the object, but actually a new object is created and the existing one remains unchanged (Use the StringBuffer or StringBuilder classes to store character sequences that are subject to change. Instances of these classes are optimized for operations that modify the contained string.) Software Development I // Exercises // 09 Strings & Lists // 4
4 I Strings: Immutability Example public class ImmutableStrings { public static void main (String[] args) { String str = new String("SWE1 2014/15"); String str2 = str; System.out.println(str2==str); str = "SWE1 2014/15"; System.out.println(str2==str); Program output? true false Software Development I // Exercises // 09 Strings & Lists // 5
5 Strings: Constructors Constructors of the class String are called whenever the compiler (javac) encounters a character sequence enclosed in double quotes. public class String extends Object implements Serializable { public String() { public String(String value) { public String(char[] value) { public String(char[] value, int offset, int count) { public String(byte[] ascii, int hibyte, int offset, int count) { public String(byte[] ascii, int hibyte) { public String(byte[] bytes, int offset, int length, String enc) throws UnsupportedEncodingException { public String(byte[] bytes, String enc) throws UnsupportedEncodingException { public String(byte[] bytes, int offset, int length) { public String(byte[] bytes) { public String(StringBuffer buffer) { Software Development I // Exercises // 09 Strings & Lists // 6
6 Strings: Class methods The following methods are implemented as class methods, i.e., can be accessed statically by qualifying the call with the class name (String). public final class String extends Object implements Serializable { static String copyvalueof(char[] data) static String copyvalueof(char[] data, int offset, int count) static String valueof(boolean b) static String valueof(char c) static String valueof(char[] data) static String valueof(char[] data, int offset, int count) static String valueof(double d) static String valueof(float f) static String valueof(int i) static String valueof(long l) static String valueof(object obj)... // end String Software Development I // Exercises // 09 Strings & Lists // 7
7 Strings: Instance methods The following methods can be invoked on every instance of class String (String object) public final class String extends Object implements Serializable { char charat(int index) int compareto(object o) int compareto(string anotherstring) int comparetoignorecase(string str) String concat(string str) boolean endswith(string suffix) boolean equals(object anobject) boolean equalsignorecase(string anotherstring) byte[] getbytes() void getbytes(int srcbegin, int srcend, byte[] dst, int dstbegin) byte[] getbytes(string enc) void getchars(int srcbegin, int srcend, char[] dst, int dstbegin) int hashcode()... Software Development I // Exercises // 09 Strings & Lists // 8
8 Strings: Instance methods The following methods can be invoked on every instance of class String (String object) public final class String extends Object implements Serializable { int indexof(int ch) int indexof(int ch, int fromindex) int indexof(string str) int indexof(string str, int fromindex) String intern() int lastindexof(int ch) int lastindexof(int ch, int fromindex) int lastindexof(string str) int lastindexof(string str, int fromindex) int length() boolean regionmatches(boolean ignorecase, int toffset, String other, int offset, int len) boolean regionmatches(int toffset, String other, int ooffset, int len)... Software Development I // Exercises // 09 Strings & Lists // 9
9 Strings: Instance methods The following methods can be invoked on every instance of class String (String object) public final class String extends Object implements Serializable { String replace(char oldchar, char newchar) boolean startswith(string prefix) boolean startswith(string prefix, int toffset) String substring(int beginindex) String substring(int beginindex, int endindex) char[] tochararray() String tolowercase() String tolowercase(locale locale) String tostring() String touppercase() String touppercase(locale locale) String trim() // end String Software Development I // Exercises // 09 Strings & Lists // 10
10 Strings: Creation What s this? Interned String object is stored at a central place (in memory) and whenever the same literal is used/created again, the JVM will not create a new String object, but use the reference of the 'cached' String. There are several different ways (why?) to create a String object String constants or literals (interned String object) String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Conversion from a character (or byte) array String s1 = new String(new char[] {'A','B','C'); String s2 = new String(s1); // copy constructor; copy of s1 Conversion of other primitive data types: // int, double, long, float, boolean, short... String s3 = String.valueOf(x == 2.4); String pi = String.valueOf( ); Concatenation of multiple strings String firstname = new String("Andreas"); String lastname = "Riener"; // short form (String literal) String name = firstname + " " + lastname; // new object System.out.println("Name: " + name); Software Development I // Exercises // 09 Strings & Lists // 11
11 Strings: Method Usage Declaration (String constant) String name = "Andreas"; // Declaration of a new string String length name.length(); // output = 7 "Andreas".length(); // output = 7 Character operations name.charat(2); // output = d name.indexof("a"); // output = 5 Substrings String s1 = name.substring(0, 2); String s2 = name.substring(3); // output = An // output = reas String concatenation String s = s1 + s2; s.startswith("andr"); // output = Anreas // false Software Development I // Exercises // 09 Strings & Lists // 12
12 Strings: String Constants // String Objects Different behavior (internal representation) Example for String constants/literals (Interned String object) String a = "strange"; String b = "strange"; At time of creation of String b, the compiler checks if already an object with same signature (i.e., character sequence) exists in the memory; if true, in b a reference to the already existing String object is stored (reasons: immutability of strings; allows compiler optimizations) Real String objects String c = new String("strange"); String d = new String("strange"); System.out.println((a == b) + " " + (c == d)); Output: true false A and B reference the same String object (literal) Software Development I // Exercises // 09 Strings & Lists // 14 C and D are two different String objects
13 I Strings: Array of Strings So far we have looked at arrays of primitive types (int, float, double, etc.) private int[] numbers = new int[] {12,4,7,17,21,8,8,3,16,2; numbers Array of Strings (special case of array of objects) Declaration of the String array: private String[] countries; Creation (initialization) of the array: countries = new String[10]; // allocates memory to hold references to 10 String objects Create String objects and add them to the array: countries[0] = new String("Canada"); countries[5] = new String("Australia"); String literals/constants: countries[1] = "Austria"; countries[2] = "Austria"; countries System.out.println( countries[1]==countries[2]); Output: true Canada Australia Italy recall: jagged 2 dimensional array Software Development I // Exercises // 06 Arrays (Declaration, Initialization, Usage; Multidim. Arrays) // 15
14 I Strings: Classes StringBuffer, StringBuilder Strings are immutable and cannot be modified at runtime; StringBuffer and StringBuilder objects can change its length dynamically and are modifiable. StringBuilder vs. StringBuffer The only difference between StringBuffer and StringBuilder is, that operations on a StringBuilder object are unsynchronized and operations on instances of the class StringBuffer are synchronized. Single-threaded applications: Use of StringBuilder is more efficient... Constructors (example StringBuilder) public StringBuilder() Creates an empty string (no characters in it) with an initial length of 16 characters; buffer will be automatically enlarged if necessary public StringBuilder(int length) Creates an empty string with the given length (space to hold length chars) public StringBuilder(String str) Creates a new StringBuffer object and initializes it with the String str. The initial capacity of the string builder is str.length() Software Development I // Exercises // 09 Strings & Lists // 16
15 Strings: Class StringBuilder Example: Common usage of Stringbuilders StringBuilder a = new StringBuilder("Merry!"); // Append a String to the existing sequence a.append("!!!"); // Merry!!!! // Append an int value to the existing sequence; will be converted into corresponding characters a.append(3); // Merry!!!!3 // Append a double to the existing sequence a.append(3.14); // Merry!!!!33.14 // Delete characters in the string a.delete(6, 20); // Merry! // Insert a character sequence at a certain position a.insert(5, " Christmas"); // Merry Christmas! Software Development I // Exercises // 09 Strings & Lists // 17
16 Strings: Class StringBuilder Example: Common usage of Stringbuilders (continued) // Replace a certain character sequence a.replace(6, 12, "X"); // Merry Xmas! // Delete a character at a certain position a.deletecharat(10); // Merry Xmas // Cut the string at a certain position a.setlength(5); // Merry // Reverse the string a.reverse(); // yrrem // create an immutable String String s1 = a.tostring(); // yrrem // Create a new string with a certain substring String s2 = a.substring(0, 1); // y Software Development I // Exercises // 09 Strings & Lists // 18
17 I StringBuffer: Example Anagram We are looking for an algorithm (Java program) that reads in two words from the user and checks, whether or not the second word is an anagram of the first. The second word is an anagram of the first word if it can be created by permutation of the first word (not to be confused with palindromes!) Examples item time anagram acres caress not an anagram scare cares anagram react crater not an anagram Software Development I // Exercises // 09 Strings & Lists // 19
18 StringBuffer: Example Anagram public class Anagram { public static void main(string[] arg) { String s1, s2; System.out.println ("first word? "); s1 = Input.readString(); System.out.println ("second word? "); s2 = Input.readString(); System.out.print ("The words are "); if (!isanagram(s1, s2)) System.out.print("NOT "); System.out.print("anagrams."); // end main // end Anagram Software Development I // Exercises // 09 Strings & Lists // 20
19 StringBuffer: Example Anagram (2) static boolean isanagram (String s1, String s2) { boolean isanagram = false; if (s1.length() == s2.length()) { // create editable copy of s2 StringBuffer sb2 = new StringBuffer(s2); // strike out letters of s1 in sb2 for (int i = 0; i < s1.length(); i++) { int pos = sb2.tostring().indexof(s1.charat(i)); if (pos!= -1) sb2.setcharat(pos, (char)0); // mark with non-print char // end for // check if all letters are striked out int i = 0; while (i < sb2.length() && sb2.charat(i) == (char)0) i++; isanagram = (i == sb2.length()); // end if return isanagram; // end isanagram Software Development I // Exercises // 09 Strings & Lists // 21
20 Strings: Summary How to decide which class (String, StringBuffer, or StringBuilder) to use for String objects? 1) If the text is not likely to be modified in the future, one should select String (String objects are immutable); in addition, usage of string literals is preferred over String objects (compiler optimization) 2) If the text is likely to be modified but will be accessed by a single thread only, one should use StringBuilder (unsynchronized) 3) If the string object is likely to be modified and more than one thread have access to it, one should use StringBuffer (synchronized) Software Development I // Exercises // 09 Strings & Lists // 22
21 Lists and Vectors in Java
22 I (Linked) Lists: Introduction As objects (variables of complex data type) in Java are accessed per reference, an object can store a reference to another object. This reference can also refer to an instance of the same class This fact makes it possible to link objects with each other ( list of objects) Advantage of lists The major benefit of linked lists is that you do not have to specify a fixed size for your list (like arrays). You can have an arbitrary number of nodes and its number can be dynamically modified at runtime (adding and removing nodes) Types of lists: There is more than one type of a linked list Singly linked lists (the simplest type). The root node links one way through all the nodes. Last node links to null. Circular lists. All nodes are linked together forming a circle. Very effective for some list operations (shifting elements, etc.) Doubly linked lists. Every node stores a reference to its previous node a well as its next. Good if you need to move back by a few nodes, and don t want to run from the beginning of the list. Software Development I // Exercises // 09 Strings & Lists // 24
23 I (Linked) Lists: Introduction Linking objects with each other ( lists of objects) List of objects can be created by declaring a variable referencing the first element of the list (head). Each element in the list stores another reference pointing to the following element in the list. For this concept, it is necessary to somehow identify which element is the last one in the list (tail) null reference, i.e., the last element does not reference any other object Software Development I // Exercises // 09 Strings & Lists // 25
24 I (Linked) Lists: Introduction Arrays versus Linked Lists (1) 1) Create an empty integer array 2) Fill it partially with data. The last element is allocated but not used (wastes memory) 3) Add another element. The array is now full, no further elements can be added (elements can be deleted or replaced) 4) Arrays have a fixed size. If the array is full, no more elements can be added (linked lists are not fixed size!) 5) If you delete an element from the middle, and want no holes in the array, you will need to shift everything after the deleted element down. (same applies to inserting in the middle) Underlying source: Software Development I // Exercises // 09 Strings & Lists //
25 I (Linked) Lists: Introduction Arrays versus Linked Lists (2) head 1) This is what an empty linked list lookes like. Since we don t have any nodes, its reference/ pointer is null. head 2) Linked list with three elements/nodes. Each node points to the next node in the chain. head is a node with a reference to the first node, the next reference of the last node is null. head 3) Linked list with deleted element [2]. Element [1] (with value 1), previously pointing to [2], is now pointing to [3]. References need to be updated! If forgotten, unreferenced elements are lost and will get automatically garbage collected. head 4) The second node [2] can be added back at a later time between [1] and [3], and another 1 node added at the end of the list. The next-reference of [1] is set to [2] and the next-reference of [2] is set to the old next-reference of [1], which is [3] Software Development I // Exercises // 09 Strings & Lists // 27 null node=new Node(1); head=node; 3 [1].next=[3]; 4 [2].next=[1].next; [1].next=[2]; [3].next=[4];
26 I Lists: Structure Example: List of House objects public class House { int floors, noflifts; Person owner;...; House next; 54 house1 floors noflifts owner next = #67 67 house2 floors noflifts owner next = #80 80 house3 93 house4 floors noflifts owner next = #93 floors noflifts owner next = null Software Development I // Exercises // 09 Strings & Lists // 28
27 Lists: Inserting To access elements in the list, the reference to the first element has to be known. Given the head of the list, all the other elements can be reached by following the "next" references House first;... House house = first; while (house!= null) { // do something with the house house = house.next; Inserting a new house object at the beginning to the list requires to change the reference to the first element: house = new House(); house.next = first; first = house; // house initialization To append a new (house) object at the end of the list, the "next" reference has to be followed until reaching the last element (tail) of the list, and the new objects has to be inserted at the very end; other option: keep a reference to the last element in advance (e.g., House last;) Software Development I // Exercises // 09 Strings & Lists // 29
28 I SWE1 UE09 Lists.zip Lists: Example NumberList NumberList represents a linked list which stores an ascending list of integer numbers. Each node is an instance of the class NumberNode. class NumberNode { public int num; public NumberNode next; // next node in list public NumberNode(int num) { // constructor this.num = num; head Task: Implement two methods add(int num) adds a number to the list (ensure that the list remains sorted) getfrequency(int num) returns the number of occurrences of the given integer number num. Make sure that you do not iterate through the entire list but make use of the fact that the list is sorted. Software Development I // Exercises // 09 Strings & Lists // 30
29 SWE1 UE09 Lists.zip Lists: Example NumberList public class NumberList { NumberNode head; // adds the new number at the correct position of the sorted list public void add(int num) { NumberNode q = new NumberNode(num); NumberNode p = head, prev = null; while (p!= null && p.num < num) { // find the location to insert prev = p; // the new node p = p.next; q.next = p; Remember: Short-circuit evaluation (SCE) if (p == head) { // check if the head needs to be changed... head = q; else { prev.next = q; // continued on next slide... Software Development I // Exercises // 09 Strings & Lists // 31
30 SWE1 UE09 Lists.zip Lists: Example NumberList // continuing from previous slide... // counts the number of occurrences of the given number public int getfrequency(int num) { int count = 0; NumberNode p = head; // go through the list, increase counter if the number is found while (p!= null && p.num <= num) { if (p.num == num) { count++; p = p.next; return count; Software Development I // Exercises // 09 Strings & Lists // 32
31 Lists: Predefined List Classes (Java API) In Java there are already some classes in different libraries predefined to maintain objects in lists, e.g., Class String characters only Class Stack arbitrary objects (data types) LIFO (Last In First Out) Class Vector (better: ArrayList) arbitrary objects (data types) like arrays, but growable/shrinkable size random access to elements (via index) Class LinkedList arbitrary objects (data types) implementation of a doubly-linked list (implements List and Deque interfaces) Software Development I // Exercises // 09 Strings & Lists // 33
32 O SWE1 UE09 Lists.zip Example: ArrayList The implemented class should maintain an arbitrary number of lines, each of them containing character sequences (String). The end of the list is denoted by the predefined string quit. Input user enters lines with text stopper sign to end read-in Output (on the command line) total number of entered lines; print out the middle line all entered lines in reverse order Think of a solution with the ArrayList class, i.e. import java.util.arraylist; ArrayList lines = new ArrayList(); Software Development I // Exercises // 09 Strings & Lists // 34
33 I SWE1 UE09 Lists.zip Example: ArrayList Parametrization If not parametrized, 'lines' can contain arbitrary elements (of type Object) Warning message - ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized - Type safety: The method add(object) belongs to the raw type ArrayList. References to generic type ArrayList<E> should be parameterized public class ArrayListExercise { public static void main(string[] args) { final String STOPPER = "quit"; java.util.arraylist lines = new java.util.arraylist(); java.util.arraylist<string> lines = new java.util.arraylist<string>(); System.out.println("Enter lines. Use " + STOPPER + " to end the program."); String line = Input.readString(); while (!line.equals(stopper)) { lines.add(line); line = Input.readString(); System.out.println("Number of lines: " + lines.size()); System.out.println("Middle line: " + (String) lines.get(lines.size()/2)); Software Development I // Exercises // 09 Strings & Lists // 35 // Print the lines in reverse order System.out.println("Lines in reverse order:"); for (int i = lines.size() - 1; i >= 0; i--) { System.out.println((String) lines.get(i));
34 I SWE1 UE09 Lists.zip Example: ArrayList Sample output Enter lines. Use quit to end the program: Hi, how are you today? quit Number of lines: 5 Middle line: are Lines in reverse order: today? you are how Hi, Software Development I // Exercises // 09 Strings & Lists // 36
35 I SWE1 UE09 Lists.zip Example: LinkedList<String> import java.util.*; public class LinkedListExercise { public static void main(string args[]) { // create a linked list (type of elements: String) LinkedList<String> list= new LinkedList<String>(); // add elements to the linked list list.add("roland"); list.add("thomas"); list.add("verena"); list.add("christian"); list.add("jürgen"); list.addlast("wolfgang"); list.addfirst("alexander"); list.add(1, "Andreas"); System.out.println("Contents of the list: " + list); // remove elements from the linked list list.remove("jürgen"); System.out.println("Contents of list after deletion: " + list); list.remove(2); // remove 3rd element (0...len-1) System.out.println("Contents of list after deletion: " + list); Software Development I // Exercises // 09 Strings & Lists // 37
36 I SWE1 UE09 Lists.zip Example: LinkedList<String> // continued java.lang.indexoutofboundsexception: Index: 20, Size: 6 at java.util.linkedlist.checkelementindex(linkedlist.java:553) at java.util.linkedlist.remove(linkedlist.java:523) at LinkedListExercise.main(LinkedListExercise.java:34) // what happens in case of removing inexistent object (out of bounds)? list.remove(20); // remove first and last elements list.removefirst(); list.removelast(); System.out.println("list after deleting first and last: " + list); list.remove(list.size()-1); // equivalent to list.removelast(); System.out.println("list after additional deleting of last: " + list); // get and set a value Object val = list.get(2); list.set(2, (String) val + " Changed"); System.out.println("list after change: " + list); Contents of the list: [Alexander, Andreas, Roland, Thomas, Verena, Christian, Jürgen, Wolfgang] Contents of list after deletion: [Alexander, Andreas, Roland, Thomas, Verena, Christian, Wolfgang] Contents of list after deletion: [Alexander, Andreas, Thomas, Verena, Christian, Wolfgang] list after deleting first and last: [Andreas, Thomas, Verena, Christian] list after additional deleting of last: [Andreas, Thomas, Verena] list after change: [Andreas, Thomas, Verena Changed] Software Development I // Exercises // 09 Strings & Lists // 38
37 SWE1 UE09 cinema example g1,2,4,5.zip SWE1 UE09 cinema example g3.zip Object-oriented Programming: Assignment 07 Live coding session
38 Exercises Software Development I 09 Objects III: String and StringBuffer, Singly (Doubly) Linked Lists December 10th, 2014 Software Development I Winter term 2014/2015 Priv.-Doz. Dipl.-Ing. Dr. Andreas Riener Institute for Pervasive Computing Johannes Kepler University Linz riener@pervasive.jku.at
SOFTWARE DEVELOPMENT 1. Strings and Enumerations 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)
SOFTWARE DEVELOPMENT 1 Strings and Enumerations 2018W (Institute of Pervasive Computing, JKU Linz) CHARACTER ENCODING On digital systems, each character is represented by a specific number. The character
More informationLecture Notes K.Yellaswamy Assistant Professor K L University
Lecture Notes K.Yellaswamy Assistant Professor K L University Building Strings and Exploring String Class: -------------------------------------------- The String class ------------------- String: A String
More informationBuilding Strings and Exploring String Class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 Lecture Notes K.Yellaswamy Assistant Professor CMR College of Engineering & Technology Building Strings and Exploring
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 informationMathematics for Computer Graphics - Lecture 12
Mathematics for Computer Graphics - Lecture 12 Dr. Philippe B. Laval Kennesaw State University October 6, 2003 Abstract This document is about creating Java Applets as they relate to the project we are
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 informationClass Library java.lang Package. Bok, Jong Soon
Class Library java.lang Package Bok, Jong Soon javaexpert@nate.com www.javaexpert.co.kr Object class Is the root of the class hierarchy. Every class has Object as a superclass. If no inheritance is specified
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 informationOverloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters
Overloaded Methods Sending Messages Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Initialization & Cleanup 2 Overloaded Constructors Sending Parameters accessor method 3 4 Sending Parameters
More informationDEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Internal Examination 1 Answer Key DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Branch & Sec : CSE Date : 08.08.2014 Semester : V Sem Max Marks : 50 Marks Sub Code& Title : CS2305 Programming Paradigms
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 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 informationJAVA NUMBERS, CHARS AND STRINGS
JAVA NUMBERS, CHARS AND STRINGS It turned out that all Workstation in the classroom are NOT set equally. This is why I wil demonstrate all examples using an on line web tool http://www.browxy.com/ Please
More informationClass definition. complete definition. public public class abstract no instance can be created final class cannot be extended
JAVA Classes Class definition complete definition [public] [abstract] [final] class Name [extends Parent] [impelements ListOfInterfaces] {... // class body public public class abstract no instance can
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 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 informationFaculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination
First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination Thursday, December 11, 2008 Examiners: Mathieu Petitpas [Section 1] 14:00
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 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 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 informationStrings, StringBuffer, StringBuilder
Strings, StringBuffer, StringBuilder STRINGS, STRINGBUFFER, STRINGBUILDER... 1 1. What is a string... 1 String() IMMUTABLE... 2 2. using the new operator to invoke the constructor in the String class...
More informationJava Strings Java, winter semester
Java Strings 1 String instances of java.lang.string compiler works with them almost with primitive types String constants = instances of the String class immutable!!! for changes clases StringBuffer, StringBuilder
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 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 informationUtilities (Part 2) Implementing static features
Utilities (Part 2) Implementing static features 1 Goals for Today learn about preventing class instantiation learn about methods static methods method header method signature method return type method
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 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 informationFaculty of Science COMP-202B - Introduction to Computing I (Winter 2009) - All Sections Final Examination
First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202B - Introduction to Computing I (Winter 2009) - All Sections Final Examination Wednesday, April 29, 2009 Examiners: Mathieu Petitpas
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 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 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 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 informationExercises Software Development I. 08 Objects II. Generating and Releasing Objects (Constructors/Destructors, this, Object cloning) December 3rd, 2014
Exercises Software Development I 08 Objects II Generating and Releasing Objects (Constructors/Destructors, this, Object cloning) December 3rd, 2014 Software Development I Winter term 2014/2015 Priv.-Doz.
More informationClass Libraries and Packages
Class Libraries and Packages Wolfgang Schreiner Research Institute for Symbolic Computation (RISC) Johannes Kepler University, Linz, Austria Wolfgang.Schreiner@risc.jku.at http://www.risc.jku.at Wolfgang
More informationCHAPTER 6 MOST COMMONLY USED LIBRARIES
LIBRARY CHAPTER 6 - A set of ready-made software routines (class definitions) that can be reused in new programs, is called a Library. - Some commonly used java libraries are : Math Library String Library
More informationExercises Software Development I. 06 Arrays. Declaration, Initialization, Usage // Multi-dimensional Arrays. November 14, 2012
Exercises Software Development I 06 Arrays Declaration, Initialization, Usage // Multi-dimensional Arrays November 4, 202 Software Development I Winter term 202/203 Institute for Pervasive Computing Johannes
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 informationChapter 10: Text Processing and More about Wrapper Classes
Chapter 10: Text Processing and More about Wrapper Classes Starting Out with Java: From Control Structures through Objects Fourth Edition by Tony Gaddis Addison Wesley is an imprint of 2010 Pearson Addison-Wesley.
More informationJ.43 The length field of an array object makes the length of the array available. J.44 ARRAYS
ARRAYS A Java array is an Object that holds an ordered collection of elements. Components of an array can be primitive types or may reference objects, including other arrays. Arrays can be declared, allocated,
More informationAns: Store s as an expandable array of chars. (Double its size whenever we run out of space.) Cast the final array to a String.
CMSC 131: Chapter 21 (Supplement) Miscellany Miscellany Today we discuss a number of unrelated but useful topics that have just not fit into earlier lectures. These include: StringBuffer: A handy class
More informationExercises Software Development I. 03 Data Representation. Data types, range of values, internal format, literals. October 22nd, 2014
Exercises Software Development I 03 Data Representation Data types, range of values, ernal format, literals October 22nd, 2014 Software Development I Wer term 2013/2014 Priv.-Doz. Dipl.-Ing. Dr. Andreas
More informationJava s String Class. in simplest form, just quoted text. used as parameters to. "This is a string" "So is this" "hi"
1 Java s String Class in simplest form, just quoted text "This is a string" "So is this" "hi" used as parameters to Text constructor System.out.println 2 The Empty String smallest possible string made
More informationChapter 8 Strings. Chapter 8 Strings
Chapter 8 Strings Chapter 6 Arrays Chapter 7 Objects and Classes Chapter 8 Strings Chapter 9 Inheritance and Polymorphism GUI can be covered after 10.2, Abstract Classes Chapter 12 GUI Basics 10.2, Abstract
More informationChapter 29: String and Object References Bradley Kjell (Revised 06/15/2008)
Chapter 29: String and Object References Bradley Kjell (Revised 06/15/2008) In previous chapters, methods were called with parameters that were primitive data types. This chapter discusses how to use object
More informationLesson:9 Working with Array and String
Introduction to Array: Lesson:9 Working with Array and String An Array is a variable representing a collection of homogeneous type of elements. Arrays are useful to represent vector, matrix and other multi-dimensional
More informationClass. Chapter 6: Data Abstraction. Example. Class
Chapter 6: Data Abstraction In Java, there are three types of data values primitives arrays objects actually, arrays are a special type of object Class In Java, objects are used to represent data values
More informationCS112 Lecture: Characters and Strings
CS112 Lecture: Characters and Strings Objectives: Last Revised 3/21/06 1. To introduce the data type char and related basic information (escape sequences, Unicode). 2. To introduce the library classes
More informationExercises Software Development I. 05 Conversions and Promotions; Lifetime, Scope, Shadowing. November 5th, 2014
Exercises Software Development I 05 Conversions and Promotions; Lifetime, Scope, Shadowing November 5th, 2014 Software Development I Winter term 2014/2015 Priv.-Doz. Dipl.-Ing. Dr. Andreas Riener Institute
More informationSSE3052: Embedded Systems Practice
SSE3052: Embedded Systems Practice Minwoo Ahn minwoo.ahn@csl.skku.edu Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu SSE3052: Embedded Systems Practice, Spring 2018, Jinkyu Jeong
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 informationChapter 12 Strings and Characters. Dr. Hikmat Jaber
Chapter 12 Strings and Characters Dr. Hikmat Jaber 1 The String Class Constructing a String: String message = "Welcome to Java ; String message = new String("Welcome to Java ); String s = new String();
More informationJava Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing
Java Programming MSc Induction Tutorials 2011 Stefan Stafrace PhD Student Department of Computing s.stafrace@surrey.ac.uk 1 Tutorial Objectives This is an example based tutorial for students who want to
More informationChapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9
CHAPTER 8 STRINGS Chapter 6 Arrays Chapter 7 Objects and Classes Chapter 8 Strings Chapter 9 Inheritance and Polymorphism GUI can be covered after 10.2, Abstract Classes Chapter 12 GUI Basics 10.2, Abstract
More informationReview Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:
More informationCISC 370: Introduction to Java
CISC 370: Introduction to Java Instructor: Sara Sprenkle sprenkle@cis cis.udel.eduedu TA: Ke Li kli@cis cis.udel.eduedu 1 What is Java? and, why should I learn it? Sara Sprenkle - CISC370 2 What is Java?
More informationJava Intro 3. Java Intro 3. Class Libraries and the Java API. Outline
Java Intro 3 9/7/2007 1 Java Intro 3 Outline Java API Packages Access Rules, Class Visibility Strings as Objects Wrapper classes Static Attributes & Methods Hello World details 9/7/2007 2 Class Libraries
More informationCOMP-202 Unit 5: Basics of Using Objects
COMP-202 Unit 5: Basics of Using Objects CONTENTS: Concepts: Classes, Objects, and Methods Creating and Using Objects Introduction to Basic Java Classes (String, Random, Scanner, Math...) Introduction
More informationString is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents
String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents character strings. All string literals in Java programs,
More informationCS321 Languages and Compiler Design I. Winter 2012 Lecture 2
CS321 Languages and Compiler Design I Winter 2012 Lecture 2 1 A (RE-)INTRODUCTION TO JAVA FOR C++/C PROGRAMMERS Why Java? Developed by Sun Microsystems (now Oracle) beginning in 1995. Conceived as a better,
More informationGenerics. IRS W-9 Form
Generics IRS W-9 Form Generics Generic class and methods. BNF notation Syntax Non-parametrized class: < class declaration > ::= "class" < identifier > ["extends" < type >] ["implements" < type list >]
More informationJava Language Features
Java Language Features References: Object-Oriented Development Using Java, Xiaoping Jia Internet Course notes by E.Burris Computing Fundamentals with Java, by Rick Mercer Beginning Java Objects - From
More informationJava Programming. String Processing. 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Java Programming String Processing 1 Copyright 2013, Oracle and/or its affiliates. All rights Overview This lesson covers the following topics: Read, search, and parse Strings Use StringBuilder to create
More informationEnough java.lang.string to Hang Ourselves...
Enough java.lang.string to Hang Ourselves... Dr Heinz M. Kabutz Last Updated 2018-06-19 2018 Heinz Kabutz, All Rights Reserved !2 Converting int val to a String? 1."" + val 2.Integer.toString(val) 3.Integer.valueOf(val)
More informationAdvanced Object Oriented Programming EECS2030Z
Advanced Object Oriented Programming EECS2030Z 1 Academic Support Programs: Bethune having trouble with your FSC and LSE courses? consider using the Academic Support Programs at Bethune College PASS free,
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 informationCS 231 Data Structures and Algorithms, Fall 2016
CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard
More informationLinked Lists. private int num; // payload for the node private Node next; // pointer to the next node in the list }
Linked Lists Since a variable referencing an object just holds the address of the object in memory, we can link multiple objects together to form dynamic lists or other structures. In our case we will
More informationBM214E Object Oriented Programming Lecture 8
BM214E Object Oriented Programming Lecture 8 Instance vs. Class Declarations Instance vs. Class Declarations Don t be fooled. Just because a variable might be declared as a field within a class that does
More informationEng. Mohammed Abdualal
Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2124) Lab 2 String & Character Eng. Mohammed Abdualal String Class In this lab, you have
More information1 Shyam sir JAVA Notes
1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write
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 informationContents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix
PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring
More informationCS 1301 Ch 8, Part A
CS 1301 Ch 8, Part A Sections Pages Review Questions Programming Exercises 8.1 8.8 264 291 1 30 2,4,6,8,10,12,14,16,18,24,28 This section of notes discusses the String class. The String Class 1. A String
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 informationFaculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Final Examination
First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Final Examination Wednesday, December 16, 2009 Examiners: Mathieu Petitpas
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 informationProgramming. Syntax and Semantics
Programming For the next ten weeks you will learn basic programming principles There is much more to programming than knowing a programming language When programming you need to use a tool, in this case
More informationArrays. Arrays. Wolfgang Schreiner Research Institute for Symbolic Computation (RISC) Johannes Kepler University, Linz, Austria
Arrays Wolfgang Schreiner Research Institute for Symbolic Computation (RISC) Johannes Kepler University, Linz, Austria Wolfgang.Schreiner@risc.jku.at http://www.risc.jku.at Wolfgang Schreiner RISC Arrays
More informationIntro to Computer Science II
Intro to Computer Science II CS112-2012S-04 Strings David Galles Department of Computer Science University of San Francisco 04-0: Types in Java Primative Types Hold simple values Can be stored on the stack
More informationTEXT-BASED APPLICATIONS
Objectives 9 TEXT-BASED APPLICATIONS Write a program that uses command-line arguments and system properties Write a program that reads from standard input Write a program that can create, read, and write
More informationCSC 1051 Algorithms and Data Structures I. Midterm Examination March 1, Name: KEY A
CSC 1051 Algorithms and Data Structures I Midterm Examination March 1, 2018 Name: KEY A Question Value Score 1 20 2 20 3 20 4 20 5 20 TOTAL 100 Please answer questions in the spaces provided. If you make
More informationCMPT 125: Lecture 3 Data and Expressions
CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,
More informationStacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)
Outline stacks stack ADT method signatures array stack implementation linked stack implementation stack applications infix, prefix, and postfix expressions 1 Stacks stacks of dishes or trays in a cafeteria
More informationMore non-primitive types Lesson 06
CSC110 2.0 Object Oriented Programming Ms. Gnanakanthi Makalanda Dept. of Computer Science University of Sri Jayewardenepura More non-primitive types Lesson 06 1 2 Outline 1. Two-dimensional arrays 2.
More informationOhad Barzilay and Oranit Dror
The String Class Represents a character string (e.g. "Hi") Implicit constructor: String quote = "Hello World"; string literal All string literals are String instances Object has a tostring() method More
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 informationCOE318 Lecture Notes Week 4 (Sept 26, 2011)
COE318 Software Systems Lecture Notes: Week 4 1 of 11 COE318 Lecture Notes Week 4 (Sept 26, 2011) Topics Announcements Data types (cont.) Pass by value Arrays The + operator Strings Stack and Heap details
More informationJava String Java String provides a lot of concepts that can be performed on a string such as compare, concat, equals, split, length, replace,
Java String Java String provides a lot of concepts that can be performed on a string such as compare, concat, equals, split, length, replace, compareto, intern, substring etc. In java, string is basically
More informationReview: Python Transi,on Warning
Objec,ves More Java fundamentals Ø java.lang classes: Math and String class Ø Control Structures Ø Arrays Sept 14, 2016 Sprenkle - CSCI209 1 Review: Python Transi,on Warning OK: You cannot redeclare a
More informationNews and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!
True object-oriented programming: Dynamic Objects Reference Variables D0010E Object-Oriented Programming and Design Lecture 3 Static Object-Oriented Programming UML" knows-about Eckel: 30-31, 41-46, 107-111,
More informationBrief Summary of Java
Brief Summary of Java Java programs are compiled into an intermediate format, known as bytecode, and then run through an interpreter that executes in a Java Virtual Machine (JVM). The basic syntax of Java
More informationJava characters Lecture 8
Java characters Lecture 8 Waterford Institute of Technology January 31, 2016 John Fitzgerald Waterford Institute of Technology, Java characters Lecture 8 1/33 Presentation outline Estimated duration presentation
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 information5/23/2015. Core Java Syllabus. VikRam ShaRma
5/23/2015 Core Java Syllabus VikRam ShaRma Basic Concepts of Core Java 1 Introduction to Java 1.1 Need of java i.e. History 1.2 What is java? 1.3 Java Buzzwords 1.4 JDK JRE JVM JIT - Java Compiler 1.5
More informationJava and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer
Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 2 Agenda Ø Quizzes Ø More quizzes Ø And even more quizzes 2 Quiz 1. What will be printed? Ø Integers public class
More informationIndex COPYRIGHTED MATERIAL
Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes
More informationBASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I
BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment
More informationAdvanced Java Concepts Unit 2: Linked Lists.
Advanced Java Concepts Unit 2: Linked Lists. The List interface defines the structure of a linear collection. Here are some of its methods. boolean add( E element ) Appends the element to the end of the
More informationPrelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion
Prelim 1 CS 2110, October 1, 2015, 5:30 PM 0 1 2 3 4 5 Total Question Name True Short Testing Strings Recursion False Answer Max 1 20 36 16 15 12 100 Score Grader The exam is closed book and closed notes.
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 information