cse144 intermediate programming for industrial engineering...

21
CSE144 Intermediate Programming for Industrial Engineering Lab Sessions Session 03 Res. Asst. M. Umut İZER

Upload: others

Post on 29-Jun-2020

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

CSE144 Intermediate Programming for Industrial EngineeringLab SessionsSession 03

Res. Asst. M. Umut İZER

Page 2: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

Java String

• In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string.

• The java.lang.String class provides a lot of methods to perform operations on strings.

• The Java String is immutable which means it cannot be changed. For mutable strings, you can use StringBuffer and StringBuilder classes.

• There are two ways to create String object:

1. By string literal

2. By new keyword

2

13

.03

.20

20

CSE

14

4 L

ab S

essi

on

03

Page 3: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

Example: Stringspublic class StringExample{

public static void main(String args[]){

String s1="java";

//creating string by java string literal

char ch[]={'s','t','r','i','n','g','s'};

String s2=new String(ch);

//converting char array to string

String s3=new String("example");

//creating java string by new keyword

System.out.println(s1);

System.out.println(s2);

System.out.println(s3);

}

}

3

13

.03

.20

20

CSE

14

4 L

abSe

ssio

n0

3

Page 4: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

Strings are Immutable

• In java, string objects are immutable. Once string object is created its data or state can't be changed but a new string object is created.

• Why string objects are immutable in java?• Because java uses the concept of string literal.

• Suppose there are 5 reference variables,all refer to one object "sachin".

• If one reference variable changes the value of the object, it will be affected to all the reference variables.

• That is why string objects are immutable in java.

• As seen in the figure two objects are created but s reference variable still refers to "Sachin" not to "Sachin Tendulkar".

• But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar" object.

• Notice that still sachin object is not modified.4

13

.03

.20

20

CSE

14

4 L

ab S

essi

on

03

Page 5: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

Example: Immutable Stringsclass Testimmutablestring{

public static void main(String args[]){

String s="Sachin";

s.concat(" Tendulkar");

//concat() method appends the string at the end

System.out.println(s);

//will print Sachin because strings are immutable

objects

}

}

class Testimmutablestring1{

public static void main(String args[]){

String s="Sachin";

s=s.concat(" Tendulkar");

System.out.println(s);

}

}

5

13

.03

.20

20

CSE

14

4 L

abSe

ssio

n0

3

Page 6: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

Java String Compare

• We can compare string in java on the basis of content and reference.

1. String compare by equals() method

• public boolean equals(Object another) compares this string to the specified object.

• public boolean equalsIgnoreCase(String another) compares this String to another string, ignoring case.

2. String compare by == operator

3. String compare by compareTo() method

• The String compareTo() method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string.

• Suppose s1 and s2 are two string variables. If:

• s1 == s2 :0

• s1 > s2 :positive value

• s1 < s2 :negative value6

13

.03

.20

20

CSE

14

4 L

ab S

essi

on

03

Page 7: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

Example: String Comparisonspublic class StringExample{

public static void main(String args[]){

String s1="Sachin";

String s2="SACHIN";

String s3=new String("Sachin");

String s4="Ratan";

String s5="Sachin";

System.out.println(s1.equals(s2));//false

System.out.println(s1.equalsIgnoreCase(s2));//true

System.out.println(s1.equals(s3));//true

System.out.println(s1.equals(s4));//false

System.out.println(s1==s5);//true (because both refer to

same instance)

System.out.println(s1==s3);//false(because s3 refers to

instance created in nonpool)

System.out.println(s1.compareTo(s5));//0

System.out.println(s1.compareTo(s4));//1 (because s1>s4)

System.out.println(s4.compareTo(s1));//-1(because s4<s1)

}

}

7

13

.03

.20

20

CSE

14

4 L

abSe

ssio

n0

3

Page 8: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

String Concatenation andSubstring• In java, string concatenation forms a new string that is the

combination of multiple strings. There are two ways to concat string in java:

1. By + (string concatenation) operator

2. By concat() method

• A part of string is called substring. In case of substring startIndex is inclusive and endIndex is exclusive.

• You can get substring from the given string object by one of the two methods:

1. public String substring(int startIndex): returns new String object containing the substring of the given string from specified startIndex (inclusive).

2. public String substring(int startIndex, int endIndex): returns new String object containing the substring of the given string from specified startIndex to endIndex.

8

13

.03

.20

20

CSE

14

4 L

ab S

essi

on

03

Page 9: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

Example: String Concantenation & Substringclass TestStringConcatenation1{

public static void main(String args[]){

String s1="Sachin ";

String s2="Tendulkar";

String s3=s1.concat(s2);

System.out.println(s3);//Sachin Tendulkar

String s="Sachin"+"Tendulkar";

System.out.println(s);//SachinTendulkar

String s4=50+30+"Sachin"+40+40;

System.out.println(s4);//80Sachin4040

System.out.println(s.substring(6));//Tendulkar

System.out.println(s.substring(0,6));//Sachin

}

} 9

13

.03

.20

20

CSE

14

4 L

abSe

ssio

n0

3

Page 10: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

String Class Methods

1. toUpperCase() and toLowerCase()

• converts the string into upper/lowercase letters

2. trim()

• eliminates white spaces before and after string.

3. startsWith() and endsWith()

• returns true if string starts/ends with the input

4. charAt()

• returns a character at specified index.

5. length()

• returns length of the string.

6. intern()

• if the pool already contains a string equal to the String object, then the string from the pool is returned. Else, this String object is added to the pool and a reference to this String object is returned.

7. valueOf()

• converts given type such as int, long, float, double, boolean, char and char array into string.

8. replace()

• replaces all occurrence of first sequence of character with second sequence of character.

10

13

.03

.20

20

CSE

14

4 L

ab S

essi

on

03

Page 11: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

Example: String Class Methodsclass TestStringConcatenation1{

public static void main(String args[]){

String s="Sachin";

System.out.println(s.toUpperCase());//SACHIN

System.out.println(s.toLowerCase());//sachin

System.out.println(s);//Sachin(original)

String s2=" Sachin ";

System.out.println(s2.trim());//Sachin

System.out.println(s.startsWith("Sa"));//true

System.out.println(s.endsWith("n"));//true

System.out.println(s.charAt(0));//S

System.out.println(s.charAt(3));//h

System.out.println(s.length());//6

String s3=s.intern();

System.out.println(s3);//Sachin

int a=10;

String s4=String.valueOf(a);

System.out.println(s4+10);

String s1="Java is a language. Java is a platform.";

String replaceString=s1.replace("Java","Kava");

//replaces all occurrences of "Java" to "Kava"

System.out.println(replaceString);

}

}

11

13

.03

.20

20

CSE

14

4 L

abSe

ssio

n0

3

Page 12: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

StringBufffer & StringBuilder

• Java provides three classes to represent a sequence of characters: String, StringBuffer, and StringBuilder.

• The String class is an immutable class whereas StringBufferand StringBuilder classes are mutable.

12

13

.03

.20

20

CSE

14

4 L

ab S

essi

on

03

Page 13: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

StringBuffer/Builder Methods

1. append()

• concatenates the given argument with this string.

2. insert()

• inserts the given string with this string at the given position.

3. replace()

• replaces the given string from the specified beginIndex and endIndex.

4. delete()

• deletes the string from the specified beginIndex to endIndex.

5. reverse()

• reverses the current string.

6. capacity()

• returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2.

7. ensureCapacity()

• ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2.

13

13

.03

.20

20

CSE

14

4 L

ab S

essi

on

03

Page 14: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

Example: StringBuffer Class Methodsclass StringBufferExample{

public static void main(String args[]){

StringBuffer sb=new StringBuffer("Hello ");

sb.append("Java");//now original string is changed

System.out.println(sb);//prints Hello Java

sb.insert(1,"Java");//now original string is changed

System.out.println(sb);//prints HJavaello Java

sb.replace(1,3,"Java");

System.out.println(sb);//prints HJavavaello Java

sb.delete(1,3);

System.out.println(sb);//prints Hvavaello Java

sb.reverse();

System.out.println(sb);//prints avaJ olleavavH

StringBuffer sb2=new StringBuffer();

System.out.println(sb2.capacity());//default 16

sb2.append("Hello");

System.out.println(sb2.capacity());//now 16

sb2.append("java is my favourite language");

System.out.println(sb2.capacity());//now (16*2)+2=34

}

} 14

13

.03

.20

20

CSE

14

4 L

abSe

ssio

n0

3

Page 15: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

Example: StringBuilder Class Methodsclass StringBuilderExample{

public static void main(String args[]){

StringBuilder sb=new StringBuilder("Hello ");

sb.append("Java");//now original string is changed

System.out.println(sb);//prints Hello Java

sb.insert(1,"Java");//now original string is changed

System.out.println(sb);//prints Hjavaello Java

sb.replace(1,3,"Java");

System.out.println(sb);//prints HJavavaello Java

sb.delete(1,3);

System.out.println(sb);//prints Hvavaello Java

sb.reverse();

System.out.println(sb);//prints avaJ olleavavH

StringBuilder sb2=new StringBuilder();

System.out.println(sb2.capacity());//default 16

sb2.append("Hello");

System.out.println(sb2.capacity());//now 16

sb2.append("java is my favourite language");

System.out.println(sb2.capacity());//now (16*2)+2=34

}

} 15

13

.03

.20

20

CSE

14

4 L

abSe

ssio

n0

3

Page 16: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

Java toString Method

• If you want to represent any object as a string, toString() method comes into existence.

• The toString() method returns the string representation of the object.

• If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.

• By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code.

16

13

.03

.20

20

CSE

14

4 L

ab S

essi

on

03

Page 17: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

Example: toString Methodclass Student{

int rollno;

String name;

String city;

Student(int rollno, String name, String city){

this.rollno=rollno;

this.name=name;

this.city=city;

}

public static void main(String args[]){

Student s1=new Student(101,"Raj","lucknow");

Student s2=new Student(102,"Vijay","ghaziabad");

System.out.println(s1);//compiler writes here s1.toString()

System.out.println(s2);//compiler writes here s2.toString()

}

}

17

13

.03

.20

20

CSE

14

4 L

abSe

ssio

n0

3

Page 18: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

Example: toString Methodclass Student{

int rollno;

String name;

String city;

Student(int rollno, String name, String city){

this.rollno=rollno;

this.name=name;

this.city=city;

}

public String toString(){//overriding the toString() method

return rollno+" "+name+" "+city;

}

public static void main(String args[]){

Student s1=new Student(101,"Raj","lucknow");

Student s2=new Student(102,"Vijay","ghaziabad");

System.out.println(s1);//compiler writes here s1.toString()

System.out.println(s2);//compiler writes here s2.toString()

}

}

18

13

.03

.20

20

CSE

14

4 L

abSe

ssio

n0

3

Page 19: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

StringTokenizer in Java

• The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break string.

• It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer class.

• The 6 useful methods of StringTokenizer class are as follows:

• StringTokenizer class is deprecated now. It is recommended to use split() method of String class or regex.

19

13

.03

.20

20

CSE

14

4 L

ab S

essi

on

03

Public method Description

boolean hasMoreTokens() checks if there is more tokens available.

String nextToken() returns the next token from the StringTokenizer object.

String nextToken(String delim) returns the next token based on the delimiter.

boolean hasMoreElements() same as hasMoreTokens() method.

Object nextElement() same as nextToken() but its return type is Object.

int countTokens() returns the total number of tokens.

Page 20: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

Example: StringTokenizerimport java.util.StringTokenizer;

public class Simple{

public static void main(String args[]){

StringTokenizer st = new StringTokenizer("my name is khan"," ");

while (st.hasMoreTokens()) {

System.out.println(st.nextToken());

}

StringTokenizer st2 = new StringTokenizer("my,name,is,khan");

// printing next token

System.out.println("Next token is : " + s2t.nextToken(","));

}

}

20

13

.03

.20

20

CSE

14

4 L

abSe

ssio

n0

3

Page 21: CSE144 Intermediate Programming for Industrial Engineering ...mimoza.marmara.edu.tr/~umut.izer/PS/CSE144_PS3.pdf · "Sachin" not to "Sachin Tendulkar". •But if we explicitly assign

References

• https://www.javatpoint.com/java-string

• Liang, Y.D. (2011). PowerPoint Lecture Slides for Introduction to Java Programming, 8th Edition, Georgia Southern University.

21

13

.03

.20

20

CSE

14

4 L

ab S

essi

on

03