Basic Java Syntax - Gadjah Mada University

Download Report

Transcript Basic Java Syntax - Gadjah Mada University

Warsun Najib – [email protected]
Characters and Strings
http://www.te.ugm.ac.id/~warsun
Characters
• The data type char represents a single character in Java.
Warsun Najib – [email protected]
– Character values are written as a symbol: 'a', ')', '%', 'A', etc.
– A char value in Java is really represented as an integer.
• Each character has an associated 16-bit integer value*.
*Digression:
00000000 01000001
16 bits
…
0* 215 + …………. + 0* 27 + 1* 26 + 0* 25 + 0* 24 + 0* 23 + 0*22 + 0*21 + 1*20
7/21/2015Tuesday, 9:39
AM
Characters and Strings
2 http://www.te.ugm.ac.id/~warsun
Characters
Warsun Najib – [email protected]
– So: a char value in Java is really represented as an integer. Thus:
– The integer value associated with the character is based upon a code.
• The ASCII code represents 256 characters including all upper and lower
case English letters, the numbers between 0 and 9, punctuation, and
some unprintable characters.
• ASCII is a subset of the UNICODE character set.
• The UNICODE character set contains 34,168 distinct characters.
– The major languages from the Americas, Europe, Middle East, Africa,
India, Asia, and Pacifica are represented.
– Unicode (16 bits) support for every character in the world: ‘\u0000’ to
‘\uFFFF’
7/21/2015Tuesday, 9:39
AM
Characters and Strings
3 http://www.te.ugm.ac.id/~warsun
Characters
Warsun Najib – [email protected]
• The printable ASCII characters include tabs, new lines,
carriage return, single and double quote.
–
–
–
–
–
New line = '\n'
Tab = '\t'
Carriage return = '\r'
Single quote = '\''
Double quote = '\ "‘
System.out.println(“Line one \nLine two”);
7/21/2015Tuesday, 9:39
AM
Characters and Strings
4 http://www.te.ugm.ac.id/~warsun
Non-printable Characters
Warsun Najib – [email protected]
• There are also characters contained in ASCII that are not
printable.
– Bell tone = bel
(ASCII 7)
– Characters 0 to 32 are non-printable characters.
– Character 127 (delete) is also non-printable character
7/21/2015Tuesday, 9:39
AM
Characters and Strings
5 http://www.te.ugm.ac.id/~warsun
Characters
Warsun Najib – [email protected]
• To define a character use the char data type.
char firstChar = 'a', secondChar = 'A';
Notice that two integers are declared and initialized on the same lane.
• To convert an integer into a character you can type cast the
integer.
char thirdCharacter = (char) 120;
char thirdCharacter = ‘x’;
7/21/2015Tuesday, 9:39
AM
Characters and Strings
6 http://www.te.ugm.ac.id/~warsun
Characters
Warsun Najib – [email protected]
• You can print a char as an integer using type casting.
System.out.println( (int) 'C');
Output: 67
• Comparing characters is done based upon their integer
representation.
True or false? 'c' < 'C'
True or false? '1' < '4'
7/21/2015Tuesday, 9:39
AM
Characters and Strings
7 http://www.te.ugm.ac.id/~warsun
Characters
Warsun Najib – [email protected]
import java.io.* ;
public class CharString {
public static void main( String args[] ) {
System.out.println('A');
System.out.println('\u0041');
System.out.println((char)65);
}
}
Output:
A
A
A
7/21/2015Tuesday, 9:39
AM
Characters and Strings
8 http://www.te.ugm.ac.id/~warsun
Characters
Warsun Najib – [email protected]
import java.io.* ;
public class CharString {
public static void main( String args[] ) {
int a = 98;
System.out.println(a);
System.out.println((char)a);
System.out.println('a');
}
}
Output:
98
b
a
7/21/2015Tuesday, 9:39
AM
Characters and Strings
9 http://www.te.ugm.ac.id/~warsun
Strings
Warsun Najib – [email protected]
• A string is composed of individual characters that are treated
as a single unit.
– The individual characters 'h', 'e', 'l', 'l', and 'o' are combined
into the string "hello".
• A string may contain letters, digits, and special characters
such as +, -, etc.
• String Examples:
– "My name is Matilda."
– "1 + 2 = 3“
7/21/2015Tuesday, 9:39
AM
Characters and Strings
10 http://www.te.ugm.ac.id/~warsun
Strings
Warsun Najib – [email protected]
• The data type of a string is String.
– The capital S of String indicates that this data type is not a primitive
data type.
– In fact, String is a complex data type.
• When an individual string is created, it is an object of type String.
stringName
Here comes string
content.
7/21/2015Tuesday, 9:39
AM
Characters and Strings
11 http://www.te.ugm.ac.id/~warsun
String Constructors
Warsun Najib – [email protected]
• Java provides various string constructors.
• Assume String s1; (What’s the value of s1 so far?)
– s1 = new String( );
• This creates a string of length zero with no characters.
– s1 = new String( s );
• This creates a string that is a copy of the characters stored in String s that
is passed to the constructor.
– s1 = "This is a string";
• This is a special shortcut constructor, ONLY available to Strings.
7/21/2015Tuesday, 9:39
AM
Characters and Strings
12 http://www.te.ugm.ac.id/~warsun
Strings
Warsun Najib – [email protected]
• Each character of a String has an associated index.
– The first letter of a string has an index of zero (0), the second letter
has an index of one (1), … the last letter has an index of (string
length – 1).
– What is the string length of "hello"?
– What is the index of the second 'l' in the word "hello"?
7/21/2015Tuesday, 9:39
AM
Characters and Strings
13 http://www.te.ugm.ac.id/~warsun
String Methods
• The length of a string can be found by:
– stringName.length();
Warsun Najib – [email protected]
• The first element of a string is always zero.
• A character at a specific position can be found by:
– stringName.charAt( 3 );
• Where 3 is an index into the string.
0
1
2
3
4
5
6
S
u
m
a
t
r
a
stringName
The variable refers to the
whole string
7/21/2015Tuesday, 9:39
AM
stringName.charAt(3)
The method returns the
character at position #3
Characters and Strings
14 http://www.te.ugm.ac.id/~warsun
Warsun Najib – [email protected]
Strings
• Strings are immutable !!!
• Once you create a string and initialize it you can not change
the string.
– You can assign a new string to the string variable.
• The original string is lost (will be handled by the java garbage collection
process.
– You can not add new characters or remove existing characters.
7/21/2015Tuesday, 9:39
AM
Characters and Strings
15 http://www.te.ugm.ac.id/~warsun
Changing Case
Warsun Najib – [email protected]
• To change the case of characters in a string:
– stringName.replace( 'l', 'L' );
• This returns a String with all characters 'l' in the String replaced by
'L'. If there are no 'l's in the String, the original string is returned.
– stringName.toUpperCase( );
• This will return a String with all lower case letters to capital letters.
– stringName.toLowerCase( );
• This will return a String with all capital letters to lower case letters.
7/21/2015Tuesday, 9:39
AM
Characters and Strings
16 http://www.te.ugm.ac.id/~warsun
String Comparison
• Are two strings equal to one another?
Warsun Najib – [email protected]
– stringName1.equals( stringName2 );
• The result is true if the two strings are the same and false if the two
strings are different.
• Capital and Lower case letters are considered to be different.
– stringName1 == stringName2;
• The result is only true if stringName1 and stringName2 both refer to
the same object in memory.
7/21/2015Tuesday, 9:39
AM
Characters and Strings
17 http://www.te.ugm.ac.id/~warsun
Warsun Najib – [email protected]
String Comparison
• You can ignore the case of letters during comparison using:
– stringName1.equalsIgnoreCase( StringName2 );
• That means that "hello" is equal to "HELLO"
• You can also compare strings using
– stringName1.compareTo( StringName2 );
• This comparison returns 0 if the strings are equal, a negative number if
stringName less than stringName2, and a positive number if
stringName greater than stringName2.
7/21/2015Tuesday, 9:39
AM
Characters and Strings
18 http://www.te.ugm.ac.id/~warsun
String Comparison
• To compare portions of two strings:
Warsun Najib – [email protected]
– stringName1.regionMatches( 0, StringName2, 0, 5 );
• The first parameter 0 is the starting index in stringName1, the third
parameter is the starting index in stringName2, and the last argument is the
number of characters to compare.
• This method returns true only if the members compared are equal.
– "ello" == "ello" but "ello" != "Ello“
– stringNam1e.regionMatches( true, 0, StringName2, 0, 5 );
• Here, the true says we want to ignore case
7/21/2015Tuesday, 9:39
AM
Characters and Strings
19 http://www.te.ugm.ac.id/~warsun
Locating Characters and Substrings
Warsun Najib – [email protected]
• indexOf can be used to find characters in strings.
– stringName.indexOf( (int) 'a' );
• This returns the index of the first ‘a’ in the string if it is found. If it is
not found the result is -1.
– stringName.indexOf( (int) 'a', 2 );
• This is similar to the first except the second parameter specifies which
index of the string the search should begin.
– stringName.indexOf( "a" );
• This is the same as the first except the parameter is a String rather
than an int.
7/21/2015Tuesday, 9:39
AM
Characters and Strings
20 http://www.te.ugm.ac.id/~warsun
Characters
Warsun Najib – [email protected]
import java.io.* ;
public class CharString {
public static void main( String args[] ) {
String s = "Vladimir";
System.out.println( s.indexOf((int) 'i') );
System.out.println( s.indexOf((int) 'i',5) );
System.out.println( s.indexOf("i") );
System.out.println( s.indexOf('i') );
}
}
Output:
4
6
4
4
7/21/2015Tuesday, 9:39
AM
Characters and Strings
21 http://www.te.ugm.ac.id/~warsun
Extracting Substrings
• Methods to get substrings out of strings are:
Warsun Najib – [email protected]
– stringName.substring( 10 );
• This returns the string that begins at index 10 and ends at the end of the
original string.
– stringName.substring( 10, 15 );
• This returns the string that begins at index 10 and ends at one index
before 15.
7/21/2015Tuesday, 9:39
AM
Characters and Strings
22 http://www.te.ugm.ac.id/~warsun
Concatenating Strings
• We have already used string concatenation with:
Warsun Najib – [email protected]
– "this is a string" + stringName
• To concatenate two string variables:
– stringName3 = stringName1.concat( stringName2 );
• This returns the second string added to the end of the first string.
7/21/2015Tuesday, 9:39
AM
Characters and Strings
23 http://www.te.ugm.ac.id/~warsun
Warsun Najib – [email protected]
Name.java
public class Name {
public static void main( There
String args[]
{
is a ) simpler
String name;
write this:
int midLoc;
way to
name = "Nan";
for(int i=0; i<midLoc; i++) {
name = name.concat( " Schaller" );
System.out.println(name.charAt(i));
midLoc = name.indexOf( }" " );
name = name.substring( 0, midLoc ) + " Carol" +
name.substring( midLoc );
System.out.println( name );
// Print out first name, a character per line
for (int i=0; i<name.length() && name.charAt(i) != ' '; i++ ) {
System.out.println( name.charAt(i) );
}
}
}
7/21/2015Tuesday, 9:39
AM
Characters and Strings
24 http://www.te.ugm.ac.id/~warsun
Other String Methods
Warsun Najib – [email protected]
• Using the Javadoc documentation you can learn about the
many other String methods.
– Methods for comparing regions of strings.
– Converting variables of other data types to strings.
7/21/2015Tuesday, 9:39
AM
Characters and Strings
25 http://www.te.ugm.ac.id/~warsun
Primitive vs. Complex Data Types
Warsun Najib – [email protected]
• When you define a primitive data type (int, char, double,
bool) the memory location is allocated.
– The number of bytes is always the same to store a value.
– char let = 'A';
let
7/21/2015Tuesday, 9:39
AM
Characters and Strings
A
26 http://www.te.ugm.ac.id/~warsun
Primitive vs. Complex Data Types
Warsun Najib – [email protected]
• A complex data type is a data type defined by a class.
•
– String is an example of a complex data type.
– Complex data types usually begin with a capital letter.
– The amount of storage required for a complex data type varies
depending upon how large the actual values are.
– Complex data types are also called reference data types.
7/21/2015Tuesday, 9:39
AM
Characters and Strings
27 http://www.te.ugm.ac.id/~warsun
Primitive vs. Complex Data Types
Warsun Najib – [email protected]
• When we define a String a memory location is allocated to
hold a reference to the actual location of the information.
– The reference is the location of the first item in memory.
– The information is stored sequentially beginning at the reference
location.
7/21/2015Tuesday, 9:39
AM
Characters and Strings
28 http://www.te.ugm.ac.id/~warsun
Primitive vs. Complex Data Types
Warsun Najib – [email protected]
String nameA, nameB;
nameA = "Rochester";
nameB = nameA;
nameB
nameA
nameA
Rochester
7/21/2015Tuesday, 9:39
AM
Characters and Strings
2044
2044
…
R
o
c
h
e
s
t
e
r
1008
1012
2044
2048
2052
2056
2060
29 http://www.te.ugm.ac.id/~warsun
Primitive vs. Complex Data Types
Warsun Najib – [email protected]
• If we define another string and assign it equal to name then they will
both point to the same location in memory.
string nameB = nameA;
– Now nameA and nameB both point to memory location 2044.
nameA
2044
nameB
Rochester
7/21/2015Tuesday, 9:39
AM
Characters and Strings
30 http://www.te.ugm.ac.id/~warsun
Passing Primitive Data to Methods
Warsun Najib – [email protected]
• If a program passes a variable that has a primitive data type
to a method, the actual value is passed using call-by-value.
– The advantage is that the original value can not be modified by the
method.
– The disadvantage is that a copy of the original value is made, this
requires more memory.
– In fact, Java always passes method arguments by value!
• Even if variables are reference types.
• I’ll try to explain this – hope you’ll get it!
7/21/2015Tuesday, 9:39
AM
Characters and Strings
31 http://www.te.ugm.ac.id/~warsun
Passing Objects to methods
Warsun Najib – [email protected]
• When we pass a String to a method we are passing it using
call-by-reference mechanism.
– This means that we do not pass the actual string, we are passing the
contents of the memory location that holds the reference (address) to
the actual string.
• A problem associated with call-by-reference is that the
original object may be modified.
• All objects (both Java defined and user defined) are passed
using call-by-reference.
7/21/2015Tuesday, 9:39
AM
Characters and Strings
32 http://www.te.ugm.ac.id/~warsun
Passing Objects to methods
Warsun Najib – [email protected]
• Some of the String methods require a String as a
parameter to the method.
– For example, stringName1.equals(stringName2);
– The method definition requires a String object to be passed to the
method equals.
– Sometimes == results in different value than
stringName1.equals(stringName2);
– When? We want some example !!!
7/21/2015Tuesday, 9:39
AM
Characters and Strings
33 http://www.te.ugm.ac.id/~warsun
Passing Objects to methods
Warsun Najib – [email protected]
• Sometimes == results in different value than *.equals !!!
String
word1
:
Java
word1 == word2
is true
word1.equals(word2)
is true
word1 == word2
is false
word1.equals(word2)
is true
word2
String
word1
:
Java
word2
String
Java
7/21/2015Tuesday, 9:39
AM
Characters and Strings
34 http://www.te.ugm.ac.id/~warsun
Warsun Najib – [email protected]
Returning Things from Methods
• When a method returns an object, a memory reference is
really returned.
– Not the actual data.
• When a method returns a primitive data type, then the
actual value is returned.
7/21/2015Tuesday, 9:39
AM
Characters and Strings
35 http://www.te.ugm.ac.id/~warsun
Warsun Najib – [email protected]
StringBuffer
• The String class provides string objects that cannot be
changed (are immutable).
• The StringBuffer class provides mutable objects.
7/21/2015Tuesday, 9:39
AM
Characters and Strings
36 http://www.te.ugm.ac.id/~warsun
Palindrome
Warsun Najib – [email protected]
// This program checks a given string to see if it is a palindrome
public class Palin {
public static void main( String args[] ) {
String original = "mom", reverse = "";
// Reverse it
for (int i=0; i<original.length(); i++) {
reverse = original.charAt( i ) + reverse;
}
// Now check it ( note that orig == reverse does not work )
if (original.equalsIgnoreCase(reverse)) {
System.out.println( "Palindrome" );
} else {
System.out.println( "Not a palindrome !!!" );
}
}
}
7/21/2015Tuesday, 9:39
AM
Characters and Strings
37 http://www.te.ugm.ac.id/~warsun