Lecture5 - ICT102 - T222 For Lecture Class

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

ICT102

Introduction to Programming
Lecture 5 – Strings
Focus for this week

01 Primitive vs Reference variables


String Class, Methods, Constants

02 Intro Class, Fields and Method


2-3

Primitive Data Types


• Primitive data types are built into the Java language
and are not derived from classes.
• There are 8 Java primitive data types.
– byte – float
– short – double
– int – boolean
– long – char
2-4

Primitive vs. Reference Variables


• Primitive variables actually contain the value that they have been assigned.
number = 25;

• The value 25 will be stored in the memory location associated with the variable number.

• Objects are not stored in variables, however. Objects are referenced by variables.

• String cityName = "Charleston";

The object that contains the


character string “Charleston”

cityName Address to the object Charleston


2-5

Class, Object and Methods


• Java is an Object-Oriented Language.

• Class − A class can be defined as a template/blueprint that describes the behavior/state


that the object of its type support.

• Object − Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of
a class.

• Software objects also have a state and a behavior. A software object's state is stored in
fields and behavior is shown via methods.
Objects in real-world

Objects can be grouped based on their kind.


Similar objects can have different attribute values, e.g. houses
with different size.

Group 1

Group 2

Group 3

Group 4
2-9

The String Class


• Java has no primitive data type that holds a series
of characters.
• The String class from the Java standard library
is used for this purpose.
• In order to be useful, the variable must be created
to reference a String object.
String number;
• Notice the S in String is upper case.
• By convention, class names should always begin
with an upper case character.
2-10

String Objects
• A variable can be assigned a String literal.
String value = "Hello";

• Strings are the only objects that can be created


in this way.
• A variable can be created using the new keyword.
String value = new String("Hello");

• This is the method that all other objects must use


when they are created.
// A simple program demonstrating String objects.

public class StringDemo


{
public static void main(String[] args)

String greeting = "Good morning, ";

String name = "Herman";

System.out.println(greeting + name);

}
2-12

The String Methods


• Classes have methods available to be used by the objects

• Since String is a class, objects that are instances of it have methods.

• One of those methods is the length method.


int stringSize = value.length();

• This statement runs the length method on the object pointed to by the value variable.
// This program demonstrates the String class's length method.

public class StringLength

public static void main(String[] args)

{
String name = "Herman";

int stringSize;
stringSize = name.length();

System.out.println(name + " has " + stringSize +

" characters.");

} See example: StringLength.java


2-14

String Methods
• The String class contains many methods that help with the manipulation of String
objects.

• String objects are immutable, meaning that they cannot be changed.

• when we use String methods they return new string objects, they do not change the
original string object which is using those methods
// This program demonstrates a few of the String methods.

public class StringMethods

{
public static void main(String[] args)

{
String message = "Java is Great Fun!";
String upper = message.toUpperCase();
String lower = message.toLowerCase();
char letter = message.charAt(2);
int stringSize = message.length();

System.out.println(message);
System.out.println(upper);
System.out.println(lower);
System.out.println(letter);
System.out.println(stringSize);

}
} See example: StringMethods.java
2-16

Practice Question
• Write a program to store your name in Java, find the length of your name, Print name in
all CAP letters.
2-17

String Concatenation
• Java commands that have string literals must be treated with care.

• A string literal value cannot span lines in a Java source code file.
System.out.println("This line is too long and now it
has spanned more than one line, which will cause a
syntax error to be generated by the compiler. ");
2-18

String Concatenation
• The String concatenation operator can be used to fix this problem.
System.out.println("These lines are " +
"are now ok and will not " +
"cause the error as before.");

• String concatenation can join various data types.


int number = 999;
System.out.println("We can join a string to " +
"a number like this: " + 5 +
“ or like this :“ + number );
2-19

String Concatenation
• The Concatenation operator can be used to
format complex String objects.
System.out.println("The following will be printed " +
"in a tabbed format: " +
\n\tFirst = " + 5 * 6 + ", " +
"\n\tSecond = " (6 + 4) + "," +
"\n\tThird = " + 16.7 + ".");

• Notice that if an addition operation is also needed,


it must be put in parenthesis.
3-20

Comparing String Objects


• In most cases, you cannot use the relational operators to compare two String objects
because they are reference variables

• Reference variables contain the address of the object they represent.

• Unless the references point to the same object, the relational operators will not return
true.
// compares two String objects using the equals method.

String name1 = "Mark",

name2 = "Mark",

name3 = "Mary";

// Compare "Mark" and "Mark"


if (name1.equals(name2))
{
System.out.println(name1 + " and " + name2 +
" are the same.");
}
else
{
System.out.println(name1 + " and " + name2 +
" are the NOT the same.");
}
3-22

Ignoring Case in String Comparisons


• ‘A’ and ‘a’ can be same or different

• In the String class the equals and compareTo methods are case sensitive.

• In order to compare two String objects that might have different case, use:
– equalsIgnoreCase, or
– compareToIgnoreCase
9-23

Substrings and searching within Strings


• The String class provides several methods that search for
a string inside of a string.
• A substring is a string that is part of another string.
• Some of the substring searching methods provided by the
String class:

boolean startsWith(String str)


boolean endsWith(String str)
boolean regionMatches(int start, String str, int start2,
int n)
boolean regionMatches(boolean ignoreCase, int start,
String str, int start2, int n)
9-24

Searching Strings
• The startsWith method determines whether a
string begins with a specified substring.

String str = "Four score and seven years ago";


if (str.startsWith("Four"))
System.out.println("The string starts with Four.");
else
System.out.println("The string does not start with Four.");

• str.startsWith("Four") returns true because


str does begin with “Four”.
• startsWith is a case sensitive comparison.
9-25

Searching Strings
• The String class also provides methods that will
locate the position of a substring.
– indexOf
 returns the first location of a substring or character in the calling String
Object.
– lastIndexOf
 returns the last location of a substring or character in the calling String
Object.
9-26

Extracting Substrings
String fullName = "Cynthia Susan Smith";
String lastName = fullName.substring(14);

The fullName variable holds


the address of a String object.

Address “Cynthia Susan Smith”

The lastName variable holds


the address of a String object.

Address “Smith”
9-27

Returning Modified Strings


• The String class provides methods to return modified
String objects.

– concat
 Returns a String object that is the concatenation of two
String objects. s1.concat(”number”);

– replace
• Returns a String object with all occurrences of one character being
replaced by another character. s1.replace(‘i’,”u");
– trim
 Returns a String object with all leading and trailing
whitespace characters removed. s1.trim(””);
9-28

Check Point
• Look at the following code:
String str1 = “To be, or not to be”;
String str2 = str1.replace(‘o’, ‘u’);

System.out.println(str1);
System.out.println(str2);

You hear a fellow student claim that the code will display
the following:
Tu be ur nut tu be
Tu be ur nut tu be
Is your fellow student right or wrong? Why?
2-29

Creating Constants
• Many programs have data that does not need to
be changed.
• Littering programs with literal values can make the
program hard do read and maintain.
• Replacing literal values with constants remedies
this problem.
• Constants allow the programmer to use a name
rather than a value throughout the program.
• Constants also give a singular point for changing
those values when needed.
2-30

Creating Constants
• Constants are declared using the keyword final.

• Once initialized with a value, constants cannot be changed programmatically.

• By convention, constants are all upper case and words are separated by the underscore
character.

final int CAL_SALES_TAX = 0.725;

You might also like