java basics ppt2
DESCRIPTION
ppt2TRANSCRIPT
Internet And Java Application 1
Java Basics
Internet And Java ApplicationMCA-501(N2)
Internet And Java Application 2
Data Types
• Java has two main categories of data types:– Primitive data types
• Built in data types• Many very similar to C++ (int, double, char, etc.)• Variables holding primitive data types always hold the actual
value, never a reference
– Reference data types• Arrays and user defined data types (i.e. Classes, Interfaces)• Can only be accessed through reference variables
Internet And Java Application 3
Primitive Data Types• Integer data types
– byte – 8 bits (values from -128 to +127)– short – 16 bits (-32768 to +32767)– int – 32 bits (very big numbers)– long – 64 bits (even bigger numbers)
• Characters– char – 16 bits, represented in unicode, not ASCII!
• Floating point data types– float – 4 bytes (-3.4 x 1038 to +3.4 x 1038)– double – 8 bytes (-1.7 x 10308 to 1.7 x 10308)
• Boolean data– boolean
• can only have the value true or false• Unlike C++, cannot be cast to an int (or any other data type)
Internet And Java Application 4
Operators
• Arithmetic– +,-,*,/,%,++,--
• Logic– &,|,^,~,<<,>>,>>>
• Assignment– =, +=, -=, etc..
• Comparison– <,<=,>,>=,==,!=
• Work just like in C++, except for special String support
Internet And Java Application 5
Comparison Operators
• Note about comparison operators– Work just as you would expect for primitive
data types– We will see that they do not always operate
as you would think for reference data types
Internet And Java Application 6
Control Structures
• if/else, for, while, do/while, switch• Basically work the same as in C/C++
if(a > 3) { a = 3;}else { a = 0;}
for(i = 0; i < 10; i++) { a += i;}
i = 0;while(i < 10) { a += i; i++;}
i = 0;do { a += i; i++;} while(i < 10);
switch(i) { case 1: string = “foo”; case 2: string = “bar”; default: string = “”;}
Internet And Java Application 7
• Java also has support for continue and break keywords
• Again, work very similar to C/C++
• Also note: switch statements require the condition variable to be a char, byte, short or int
Control Structures
for(i = 0; i < 10; i++) { a += i; if(a > 100) break;}
for(i = 0; i < 10; i++) { if(i == 5) continue; a += i;}
Internet And Java Application 8
Reference Data Types
• Key difference between primitive and reference data types is how they are represented
• Primitive type variables hold the actual value of the variable
• Reference type variables hold the value of a reference to the object
Internet And Java Application 9
• Variable declarations:
• Memory representation:
Example
int primitive = 5;String reference = “Hello”;
5primitive
reference Hello
Internet And Java Application 10
Arrays
• In Java, arrays are reference data types
• You can define an array of any data type (primitive or reference type)
• Special support built into the language for accessing information such as the length of an array
• Automatic bound checking at run time
Internet And Java Application 11
• Declare array variables:
• This just creates the references
• You must explicitly create the array object in order to use it
Declaring Array Variables
int myNumbers[];String myStrings[];
Internet And Java Application 12
• Create array objects:
• In the creation of any reference data object, the new operator is almost always used– String objects can be created from String literals as we’ve seen– Array objects can also be created using Array literals
• Note: in the first example, myStrings is a reference to an array of references
Creating Array Objects
myNumbers = new int[10];myStrings = new String[10];
myNumbers = {1, 2, 3, 4, 5};
Internet And Java Application 13
Accessing Array Elements
• Just like in C/C++
• Arrays also have a special length field which can be accessed to determine the size of an array
myNumbers[0] = 5;myStrings[4] = “foo”;
for(int i = 0; i < myNumbers.length; i++) myNumbers[i] = i;
Internet And Java Application 14
Wrapper Classes
• Each primitive data type has a corresponding “Wrapper Class” reference data type
• Can be used to represent primitive data values as reference objects when it is necessary to do so
• Byte, Short, Integer, Long, Float, Double, Boolean, Character
Internet And Java Application 15
What are classes?
• User defined data types
• Classes can contain– Fields: variables that store information about
the object (can be primitive or reference variables)
– Methods: functions or operations that you can perform on a data object
Internet And Java Application 16
Example
• Each instance of a Circle object contains the fields and methods shown
• static– The static keyword
signifies that the class contains only one copy of a given member variable
– Non static member variables have their own copy per instance of the class
public class Circle { static final double PI = 3.14; double radius;
public double area() { . . . }
public double circumference() { . . . }}
Internet And Java Application 17
Example
System.out.println(“Hello World”);
Built in Java class
Static member variable (field) of the System class:PrintStream object that points to standard out
Member method of the PrintStream class
Internet And Java Application 18
Back to our Wrappers
• Each wrapper class contains a number of methods and also static methods that are potentially useful
• Examples:– Character.toLowerCase(ch)– Character.isLetter(ch)
• See the Java API for more details:– http://java.sun.com/j2se/1.4.2/docs/api/
index.html
Internet And Java Application 19
Contents
1. The String Class
2. The StringBuffer Class
3. The Character Class
4. The StringTokeniser Class
5. Regular Expressions
Internet And Java Application 20
Strings
• In Java, Strings are reference data types
• They are among many built-in classes in the Java language (such as the wrapper classes)– However, they do not work exactly like all
classes– Additional support is built in for them such as
String operators and String literals
Internet And Java Application 21
The String Class
• The inner parts of a string cannot be changed once they have been initialised– e.g. abbc --> addc is not allowed
• But new things can be added to the end of a string object.
• Also a string object can be changed by assigning it a new string.
Internet And Java Application 22
Creating a String Object
• String color = “blue";
String s1;s1 = new String(“hello ”);
char chs[] = {‘a’, ‘n’, ‘d’, ‘y’};String s2 = new String(chs);
s1 = s1 + s2 + “ davison”; // + is string concatenation
Four different ways(there are more).
1
2
3
4
Internet And Java Application 23
• As mentioned before, creating reference objects in Java requires the use of the new operator
• Strings can be created this way:
• However, String literals can also be used
Creating Strings
String myString = new String(“foo”);
String myString = “foo”;
Internet And Java Application 24
String Operators
• The + operator contains special support for String data types:
• And also the += operator:
myString = “foo” + “bar”;
myString = “foo”;myString += “bar”;
Internet And Java Application 25
Comparing Strings
• As mentioned before, the == operator does not always work as expected with reference data types
• Example:
• Evaluates to true iff string1 and string2 both contain a reference to the same memory location
String string1 = “foo”;String string2 = string1;if(string1 == string2) System.out.println(“Yes”);
Internet And Java Application 26
Solution
• The String class contains built in methods that will compare the two strings rather than the two references:
String string1 = “foo”;String string2 = string1;if(string1.equals(string2)) System.out.println(“Yes”);
String string1 = “foo”;String string2 = string1;if(string1.equalsIgnoreCase(string2)) System.out.println(“Yes”);
Internet And Java Application 27
Comparing Strings
• s1.equals(s2)
– lexicographical comparison– returns true if s1 and s2 contain the same text
• s1 == s2
– returns true if s1 and s2 refer to the same object
0 48 57 65 90 97 122
0 9 A Z a z
continued
Internet And Java Application 28
• s1.compareTo(s2)
– returns 0 if s1 and s2 are equal– returns < 0 if s1 < s2; > 0 if s1 > s2
• s1.startsWith(“text”)
– returns true if s1 starts with “text”
• s1.endsWith(“text”)
– returns true if s1 ends with “text”
Internet And Java Application 29
• Returns a negative integer when string1 is “alphabetically” before string2
• Note: “alphabetically” means we are considering the unicode value of a character
• The character with the smaller unicode value is considered to come first
More String comparison
string1.compareTo(string2);
Internet And Java Application 30
• Returns a Character reference object (not a char primitive variable)
• Throws a StringIndexOutOfBoundsException if given an index value that is not within the range of the length of the string– We will see more on exceptions later
– For now you do not need to worry about this
Accessing String characters
string1.charAt(0);
Internet And Java Application 31
Other useful String methods
• See more at the Java API site– http://java.sun.com/j2se/1.4.2/docs/api/
index.html
string1.length();string1.indexOf(‘a’);string1.substring(5);string1.substring(5,8);string1.toCharArray();string1.toUpperCase();
.
.
.
Internet And Java Application 32
1.3. Locating Things in Strings
• s1.indexOf(‘c’)
– returns index position of first ‘c’ in s1, otherwise -1
• s1.lastIndexOf(‘c’)
– returns index position of last ‘c’ in s1, otherwise -1
• Both of these can also take string arguments:– s1.indexOf(“text”)
for text analysis
Internet And Java Application 33
1.4. Extracting Substrings
• s1.substring(5)
– returns the substring starting at index position 5
• s1.substring(1, 4)
– returns substring between positions 1 and 3– note: second argument is end position + 1
Internet And Java Application 34
1.5. Changing Strings• s1.replace(‘a’, ‘d’)
– return a new string; replace every ‘a’ by ‘d’
• s1.toLowerCase()
– return a new string where every char has been converted to lowercase
• s1.trim()
– return a new string where any white space before or after the s1 text has been removed
Internet And Java Application 35
1.7. Other String Methods
• The String class is in the java.lang package– there are many more String methods!– e.g. s.length()
• Look at the Java documentation for the String class:
Internet And Java Application 36
Internet And Java Application 37
2. The StringBuffer Class
• Objects of the StringBuffer class can change their inner text– used when changing a string by creating a
new string is too slow • not often a problem
Internet And Java Application 38
2.1. Creating a StringBuffer Object
• StringBuffer buf1 = new StringBuffer(“hello”);
StringBuffer buf2 = new StringBuffer(10);
StringBuffer buf3 = new StringBuffer();
Three different ways(there are more).
Just a startingvalue, the sizecan dynamicallyincrease.
Internet And Java Application 39
2.2. StringBuffer Methods
• buf1.length()
– returns the length of the text in buf1– many String methods are also available in StringBuffer
• buf1.toString()
– return the text as a String
continued
Internet And Java Application 40
• buf1.append(“hello”)
– appends “hello” to the end of buf1– append() can take many types of argument
s: int, char, float, etc.
• buf1.insert(5, “hello”)
– inserts “hello” at index position 5– insert() can take many types of data argu
ment
modifybuf1
Internet And Java Application 41
2.3. Other StringBuffer Methods
• Look at the StringBuffer documentation.
Internet And Java Application 42
3. The Character Class
• Java provides the familiar primitive data types: – int, float, char, etc.
• It also provides class equivalents:– Integer, Float, Character, etc– called type wrappers
continued
Internet And Java Application 43
• The type wrapper classes can be used to create objects (e.g. a Character object) which can be manipulated like other Java objects.
• Most Character class methods are static– that means that the methods are called using
the class name
Internet And Java Application 44
3.1. Character Static Methods
• Character.isDigit(c)// is c a digit?
Character.isLetter(c)// is c a letter?
Character.isLowerCase(c)// is c lowercase?
Think of Character as a library ofuseful methods related to chars
Internet And Java Application 45
3.2. Creating a Character Object
• Character c1;c1 = new Character(‘A’);
• Compare with:char c2 = ‘A’;
• There are many more Character methods– see the documentation
Internet And Java Application 46
4. The StringTokeniser Class
• This class provides a way of separating a string into tokens– e.g. “hello andrew davison”
becomes three tokens:“hello” “andrew” “davison”
• Very useful for parsing– dividing a program into tokens representing variabl
es, constants, keywords, numbers, etc.
Internet And Java Application 47
4.1. The Basic Technique
• A String is converted to StringTokenizer, and then the tokens are removed one at a time inside a loop:
String token:StringTokenizer st =
new StringTokenizer( “...the string ...”);
while ( st.hasMoreTokens() ) { token = st.nextToken();
: // do something with token}
continued
Internet And Java Application 48
• StringTokenizer st =new StringTokenizer(...)
– creates a sequence of tokens from the string– the default separators are "\n\t\r "
(newline, tab, carriage return, space)– the separators can be changed
• st.hasMoreTokens()
– test if there are any more tokens left
• st.nextToken()
– returns the next token as a String object
Internet And Java Application 49
4.2. TokenTest.java
import java.util.*; // StringTokenizer classimport javax.swing.JOptionPane;
public class TokenTest {
public static void main(String args[]) { String str = JOptionPane.showInputDialog(
"Enter a string:"); String output;
StringTokenizer tokens = new StringTokenizer( str );
:
Internet And Java Application 50
output = "Number of elements: " + tokens.countTokens() + "\nThe tokens are:\n" ;
while ( tokens.hasMoreTokens() ) output += tokens.nextToken() + "\n" ; JOptionPane.showMessageDialog(null, output,
"Token Test Results",
JOptionPane.INFORMATION_MESSAGE); System.exit(0); } // end of main()} //end of TokenTest
Internet And Java Application 51
Use
Internet And Java Application 52
Notes
• tokens.countTokens()
– returns the total number of tokens– use before tokens are removed from the to
ken sequence with nextToken()
Internet And Java Application 53
5. Regular Expressions
• A regular expression is a text pattern.
• The java.util.regex package contains several classes that allow you to compare strings to regular expressions to see if they match.– matching strings can be changed/replaced aft
er being found
continued
Internet And Java Application 54
• Java uses the regular expression notation from the Perl language– easy to learn (if you already know Perl)
• This feature was introduced in J2SE 1.4, so it's not explained in older textbooks.
continued
Internet And Java Application 55
• A good place to learn about regular expressions and their use in Java:– Linux Magazine
July 2002
– a special issue on regular expressions– we have a copy in our library
• or see me for copies of the magazine's articles
Internet And Java Application 56
Find Matches in a String
• import java.util.regex.*;
public class BasicMatch { public static void main(String[] args) { // Compile regular expression String patternStr = "b"; Pattern pattern = Pattern.compile(patternStr); :
Internet And Java Application 57
// Determine if pattern exists in input String inputStr = "a b c b"; Matcher matcher = pattern.matcher(inputStr); boolean matchFound = matcher.find(); //true
// Get matching string String match = matcher.group(); // "b"
// Get indices of matching string int start = matcher.start(); // 2 int end = matcher.end(); // 3 // end is index of last matching char + 1
// Find the next occurrence matchFound = matcher.find(); // true }}
Internet And Java Application 58
Search and Replace
• import java.util.regex.*;
public class BasicReplace { public static void main(String[] args) { String inputStr = "a b c a b c"; String patternStr = "a"; String replacementStr = "x";
// Compile regular expression Pattern pattern = Pattern.compile(patternStr); :
Internet And Java Application 59
// Replace all occurrences of // pattern in input Matcher matcher = pattern.matcher(inputStr); String output = matcher.replaceAll(replacementStr); // makes "x b c x b c" }}
Internet And Java Application 60
StringTokenizer
String text = “To be or not to be”;StringTokenizer st = new StringTokenizer();While(st.hasMoreTokens()) { System.out.println(“The next word is “ + st.nextToken());}
• Can be used to split strings into “tokens” using a fixed delimiter
• Default delimiter is a space
• Can also specify custom delimiters
• Must import java.util.StringTokenizer