Class T{ public static int id; public static int num = 5; public int n; public boolean c; public static void setNumberOfBicycles(int val) { num=val; //

Slides:



Advertisements
Similar presentations
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Advertisements

Strings in Java 1. strings in java are handled by two classes String &
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Working with String Duo Wei CS110A_ Empty Strings An empty string has no characters; its length is 0. Not to be confused with an uninitialized.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Strings.
Java Programming Strings Chapter 7.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
Chapter 10 Review. Write a method that returns true is s1 and s2 end with the same character; otherwise return false. Sample Answer: public boolean lastChar(String.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
CIS 234: Strings. What Is a String? series of characters enclosed in double quotes characters can include letters (lower case and upper case), digits,
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
Fundamental Programming Structures in Java: Strings.
Lab session 3 and 4 Topics to be covered Escape sequences Escape sequences Variables /identifiers Variables /identifiers Constants Constants assignment.
28-Jun-15 String and StringBuilder Part I: String.
The String Class. Objectives: Learn about literal strings Learn about String constructors Learn about commonly used methods Understand immutability of.
1 Strings and String Operations  What is a Strings?  Internal Representation of Strings  Getting Substrings from a String  Concatenating Strings 
Recitation 2 Main Method, API & Packages, Java Basics.
String Class in Java java.lang Class String java.lang.Object java.lang.String java.lang.Object We do not have to import the String class since it comes.
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
Primitive Types Java offers a number of primitive types eg.) int, short, long double, float char A variable which is declared as a primitive type stores.
String Class. Objectives and Goals Identify 2 types of Strings: Literal & Symbolic. Learn about String constructors and commonly used methods Learn several.
From C++ to Java A whirlwind tour of Java for C++ programmers.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Strings Carol Yarbrough AP Computer Science Instructor Alabama School of Fine Arts.
Java Overview. Comments in a Java Program Comments can be single line comments like C++ Example: //This is a Java Comment Comments can be spread over.
Chapter 7: Characters, Strings, and the StringBuilder.
Strings JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
Strings Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and.
String Definition A String is a set of characters that behaves as a single unit. The characters in a String include upper-case and lower-case letters,
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
String Class. Variable Holds a primitive value or a reference to an object. Holds a primitive value or a reference to an object. A reference lets us know.
String Processing Word processing term papers, writing memoirs, sending messages, responding to surveys, placing online orders and registering products.
Coding Bat: Ends in ly Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string.
CSC Programming I Lecture 9 September 11, 2002.
Strings and ArrayLists April 23, 2012 ASFA AP CS.
CSI 3125, Preliminaries, page 1 String. CSI 3125, Preliminaries, page 2 String Class Java provides the String class to create and manipulate strings.
Chapter 3A Strings. Using Predefined Classes & Methods in a Program To use a method you must know: 1.Name of class containing method (Math) 2.Name of.
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
17-Feb-16 String and StringBuilder Part I: String.
Computer Programming 2 Lab (1) I.Fatimah Alzahrani.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
Data Types References:  Data Type:  In computer science and computer programming, a data type or simply type is a.
Strings A string is a sequence of characters that is treated as a single value. Strings are objects. We have been using strings all along. For example,
The Methods and What You Need to Know for the AP Exam
Java String Methods - Codehs
The String Class.
Strings, Characters and Regular Expressions
String class.
String Class.
Strings Chapter 6.
String Handling in JAVA
Primitive Types Vs. Reference Types, Strings, Enumerations
Modern Programming Tools And Techniques-I Lecture 11: String Handling
String and StringBuilder
MSIS 655 Advanced Business Applications Programming
String and StringBuilder
String and Lists Dr. José M. Reyes Álamo.
16 Strings.
String and StringBuilder
String.
String methods 26-Apr-19.
JAVA – String Function PROF. S. LAKSHMANAN,
String Class.
In Java, strings are objects that belong to class java.lang.String .
Pre-AP® Computer Science Quiz
Unit-2 Objects and Classes
Presentation transcript:

class T{ public static int id; public static int num = 5; public int n; public boolean c; public static void setNumberOfBicycles(int val) { num=val; // Class method used to access static fields } } public class Example1 { public static void main(String[] args) { T t=new T(); T t1=new T(); System.out.println(t.id); //0 System.out.println(t.num);//5 System.out.println(t.c);//false t.id=9; t1.id=3; t.num=7; t1.num=2; t.c=false; t1.c=true; System.out.println(t.id);//3 System.out.println(t.num);//2 System.out.println(t.c);//false t.setNumberOfBicycles(40); t1.setNumberOfBicycles(50); System.out.println(t.num);//50 } Example on static Keyword

The String Class

String class facts An object of the String class represents a string of characters. The String class belongs to the java.lang package, which does not require an import statement. Like other classes, String has constructors and methods. Unlike other classes, String has two operators, + and += (used for concatenation).

Literal String examples //assign a literal to a String variable String name = “Robert”; //calling a method on a literal String char firstInitial = “Robert”.charAt(0); //’R’ //calling a method on a String variable char firstInitial = name.charAt(0); // ‘R’

Immutability Once created, a string cannot be changed: none of its methods changes the string. Such objects are called immutable.

Advantages Of Immutability Uses less memory. String word1 = "Java"; String word2 = word1; String word1 = “Java"; String word2 = new String(word1); word1 OK Less efficient: wastes memory “Java" word2 word1 word2

Disadvantages of Immutability Less efficient — you need to create a new string and throw away the old one even for small changes. String word = “java"; char ch = Character.toUpperCase(word.charAt (0)); word = ch + word.substring (1); word “java" “Java"

Empty Strings An empty String has no characters. It’s length is 0. Not the same as an uninitialized String. String word1 = ""; String word2 = new String(); String Msg; System.out.println(Msg); Error: not initialized Empty strings

No Argument Constructors No-argument constructor creates an empty String. Rarely used. String empty = new String();

Copy Constructors Copy constructor creates a copy of an existing String. Also rarely used. Not the same as an assignment. String word = new String(“Java”); String word2 = new String(word); word word2 “Java" Copy Constructor: Each variable points to a different copy of the String. String word = “Java”; String word2 = word; word “Java" word2 Assignment: Both variables point to the same String.

Other Constructors Most other constructors take an array as a parameter to create a String. char[] letters = {‘J’, ‘a’, ‘v’, ‘a’}; String word = new String (letters);//”Java”

Methods — length, charAt int length(); char charAt(i); Returns the number of characters in the string Returns the char at position i. 7 ’n' ”Problem".length(); ”Window".charAt (2); Returns: Character positions in strings are numbered starting from 0 – just like arrays.

Methods — substring “lev" “mutable" "" (empty string) ”television".substring (2,5); “immutable".substring (2); “bob".substring (9); // Exception out of index Returns: television i k television i String subs = word.substring (i, k); –returns the substring of chars in positions from i to k-1 String subs = word.substring (i); –returns the substring from the i-th char to the end Returns a new String by copying characters from an existing String.

Methods — Concatenation String word1 = “re”, word2 = “think”; word3 = “ing”; int num = 2; String result = word1 + word2; //concatenates word1 and word2 “rethink“ String result = word1.concat (word2); //the same as word1 + word2 “rethink“ result += word3; //concatenates word3 to result “rethinking” result += num; //converts num to String //and concatenates it to result “rethinking2”

Example int count =25; System.out.println( "The count is : + count – 3" ); //The count is : + count – 3 System.out.println( "The count is: " + ( count + 2 ) ); //The count is: 27 System.out.println( "The count is:" + count + 4 ); //The count is:254

Methods — Find (indexOf) String name =“President George Washington"; date.indexOf (‘P'); 0 date.indexOf (‘e'); 2 date.indexOf (“George"); 10 date.indexOf (‘e', 3); 6 date.indexOf (“Bob"); - 1 date.lastIndexOf (‘e'); 15 Returns: (not found) (starts searching at position 3)

Methods — Equality boolean b = word1.equals(word2); returns true if the string word1 is equal to word2 boolean b = word1.equalsIgnoreCase(word2); returns true if the string word1 matches word2, case-blind b = “Raiders”.equals(“Raiders”);//true b = “Raiders”.equals(“raiders”);//false b = “Raiders”.equalsIgnoreCase(“raiders”);//true if(team.equalsIgnoreCase(“raiders”)) System.out.println(“Go You “ + team);

Methods — Comparisons int diff = word1.compareTo(word2); returns the “difference” word1 - word2 int diff = word1.compareToIgnoreCase(word2); returns the “difference” word1 - word2, case-blind Usually programmers don’t care what the numerical “difference” of word1 - word2 is, just whether the difference is negative (word1 comes before word2), zero (word1 and word2 are equal) or positive (word1 comes after word2). Often used in conditional statements. if(word1.compareTo(word2) > 0){ //word1 comes after word2… }

Comparison Examples //negative differences diff = “apple”.compareTo(“berry”);//a before b diff = “Zebra”.compareTo(“apple”);//Z before a diff = “dig”.compareTo(“dug”);//i before u diff = “dig”.compareTo(“digs”);//dig is shorter //zero differences diff = “apple”.compareTo(“apple”);//equal diff = “dig”.compareToIgnoreCase(“DIG”);//equal //positive differences diff = “berry”.compareTo(“apple”);//b after a diff = “apple”.compareTo(“Apple”);//a after A diff = “BIT”.compareTo(“BIG”);//T after G diff = “huge”.compareTo(“hug”);//huge is longer

Methods — trim String word2 = word1.trim (); returns a new string formed from word1 by removing white space at both ends does not affect whites space in the middle String word1 = “ Hi Bob “; String word2 = word1.trim(); //word2 is “Hi Bob” – no spaces on either end //word1 is still “ Hi Bob “ – with spaces

Methods — replace String word2 = word1.replace(oldCh, newCh); returns a new string formed from word1 by replacing all occurrences of oldCh with newCh String word1 = “rare“; String word2 = “rare“.replace(‘r’, ‘d’); //word2 is “dade”, but word1 is still “rare“

Methods — Changing Case String word2 = word1.toUpperCase(); String word3 = word1.toLowerCase(); returns a new string formed from word1 by converting its characters to upper (lower) case String word1 = “HeLLo“; String word2 = word1.toUpperCase();//”HELLO” String word3 = word1.toLowerCase();//”hello” //word1 is still “HeLLo“

Replacements Example: to “convert” word1 to upper case, replace the reference with a new reference. A common bug: word1 = word1.toUpperCase(); word1.toUpperCase(); word1 remains unchanged

Numbers to Strings Three ways to convert a number into a string: 1. String s = "" + num; 2. String s = Integer.toString (i); String s = Double.toString (d); 3. String s = String.valueOf (num); Integer and Double are “wrapper” classes from java.lang that represent numbers as objects. s = String.valueOf(123);//”123” s = “” + 123;//”123” s = Integer.toString(123);//”123” s = Double.toString(3.14); //”3.14”