Java Basics Ppt2

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 60

Internet And Java Application

MCA-501(N2)

Java Basics

Internet And Java Applicat


ion

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 Applicat


ion

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 Applicat


ion

Operators
Arithmetic
+,-,*,/,%,++,--

Logic
&,|,^,~,<<,>>,>>>

Assignment
=, +=, -=, etc..

Comparison
<,<=,>,>=,==,!=

Work just like in C++, except for special String


support
Internet And Java Applicat
ion

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 Applicat


ion

Control Structures
if/else, for, while, do/while, switch
Basically work the same as in C/C++
i = 0;
while(i < 10) {
a += i;
i++;
}
i = 0;
do {
a += i;
i++;
} while(i < 10);

for(i = 0; i < 10; i++) {


a += i;
}
if(a
a
}
else
a
}

> 3) {
= 3;

switch(i) {
case 1:
string = foo;
{
case 2:
= 0;
string = bar;
default:
string = ;
}
Internet And Java Applicat
6
ion

Control Structures
Java also has support for continue and break
keywords
Again, work very similar to C/C++
for(i = 0; i < 10; i++) {
a += i;
if(a > 100)
break;
}

for(i = 0; i < 10; i++) {


if(i == 5)
continue;
a += i;
}

Also note: switch statements require the


condition variable to be a char, byte, short
or int
Internet And Java Applicat
ion

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 Applicat


ion

Example
Variable declarations:
int primitive = 5;
String reference = Hello;

Memory representation:
primitive
reference

5
Hello

Internet And Java Applicat


ion

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 Applicat
ion

10

Declaring Array Variables


Declare array variables:
int myNumbers[];
String myStrings[];

This just creates the references


You must explicitly create the array object
in order to use it

Internet And Java Applicat


ion

11

Creating Array Objects


Create array objects:
myNumbers = new int[10];
myStrings = new String[10];

In the creation of any reference data object, the new


operator is almost always used
String objects can be created from String literals as weve seen
Array objects can also be created using Array literals
myNumbers = {1, 2, 3, 4, 5};

Note: in the first example, myStrings is a reference to an


array of references
Internet And Java Applicat
ion

12

Accessing Array Elements


Just like in C/C++
myNumbers[0] = 5;
myStrings[4] = foo;

Arrays also have a special length field


which can be accessed to determine the
size of an array
for(int i = 0; i < myNumbers.length; i++)
myNumbers[i] = i;
Internet And Java Applicat
ion

13

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 Applicat
ion

14

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 Applicat


ion

15

Example
public class Circle {
static final double PI = 3.14;
double radius;
public double area()
{
. . .
}

Each instance of a
Circle object contains
the fields and methods
shown
static

public double circumference()


{
. . .
}
}

Internet And Java Applicat


ion

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
16

Example
Static member variable (field) of the System class:
PrintStream object that points to standard out

System.out.println(Hello World);
Built in Java class

Member method of the PrintStream class


Internet And Java Applicat
ion

17

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 Applicat
ion

18

Contents
1. The String Class
2. The StringBuffer Class
3. The Character Class
4. The StringTokeniser Class
5. Regular Expressions

Internet And Java Applicat


ion

19

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 Applicat
ion

20

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 Applicat
ion

21

Creating a String Object


String color = blue";
String s1;
s1 = new String(hello );

Four different ways


(there are more).
2

char chs[] = {a, n, d, y};


String s2 = new String(chs);
s1 = s1 + s2 + davison;
// + is string concatenation

Internet And Java Applicat


ion

3
4

22

Creating Strings
As mentioned before, creating reference
objects in Java requires the use of the
new operator
Strings can be created this way:
String myString = new String(foo);

However, String literals can also be used


String myString = foo;

Internet And Java Applicat


ion

23

String Operators
The + operator contains special support
for String data types:
myString = foo + bar;

And also the += operator:


myString = foo;
myString += bar;

Internet And Java Applicat


ion

24

Comparing Strings
As mentioned before, the == operator does not
always work as expected with reference data
types
Example:
String string1 = foo;
String string2 = string1;
if(string1 == string2)
System.out.println(Yes);

Evaluates to true iff string1 and string2 both


contain a reference to the same memory location
Internet And Java Applicat
ion

25

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 Applicat
ion

26

Comparing Strings
0

48

57

65

90

97

122

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

Internet And Java Applicat


ion

continued

27

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 Applicat


ion

28

More String comparison


string1.compareTo(string2);

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
Internet And Java Applicat
ion

29

Accessing String characters


string1.charAt(0);

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

Internet And Java Applicat


ion

30

Other useful String methods


string1.length();
string1.indexOf(a);
string1.substring(5);
string1.substring(5,8);
string1.toCharArray();
string1.toUpperCase();
.
.
.

See more at the Java API site


http://java.sun.com/j2se/1.4.2/docs/api/index.
html
Internet And Java Applicat
ion

31

1.3. Locating Things in Strings


for text analysis
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)

Internet And Java Applicat


ion

32

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 Applicat


ion

33

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 Applicat


ion

34

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 Applicat
ion

35

Internet And Java Applicat


ion

36

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 Applicat


ion

37

2.1. Creating a StringBuffer Object


Three different ways
(there are more).
StringBuffer buf1 =
new StringBuffer(hello);
StringBuffer buf2 =
new StringBuffer(10);
StringBuffer buf3 =
new StringBuffer();

Internet And Java Applicat


ion

Just a starting
value, the size
can dynamically
increase.

38

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

Internet And Java Applicat


ion

continued

39

buf1.append(hello)
appends hello to the end of buf1
append() can take many types of
arguments: int, char, float, etc.
buf1.insert(5, hello)

modify
buf1

inserts hello at index position 5


insert() can take many types of data
argument
Internet And Java Applicat
ion

40

2.3. Other StringBuffer Methods


Look at the StringBuffer documentation.

Internet And Java Applicat


ion

41

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

Internet And Java Applicat


ion

continued

42

The type wrapper classes can be used to


create objects (e.g. a Character object) whi
ch can be manipulated like other Java obj
ects.
Most Character class methods are static
that means that the methods are called using
the class name
Internet And Java Applicat
ion

43

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 of
useful methods related to chars
Internet And Java Applicat
ion

44

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 Applicat


ion

45

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
variables, constants, keywords, numbers, etc.
Internet And Java Applicat
ion

46

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
}
Internet And Java Applicat
ion

continued

47

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 Applicat


ion

48

4.2. TokenTest.java
import java.util.*;
// StringTokenizer class
import 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 Applicat
ion

49

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 Applicat


ion

50

Use

Internet And Java Applicat


ion

51

Notes
tokens.countTokens()

returns the total number of tokens


use before tokens are removed from the
token sequence with nextToken()

Internet And Java Applicat


ion

52

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 the
y match.
matching strings can be changed/replaced
after being found
Internet And Java Applicat
ion

continued

53

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.

Internet And Java Applicat


ion

continued

54

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 Applicat


ion

55

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 Applicat


ion

56

// 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();

Internet And Java Applicat


ion

// true

57

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 Applicat
ion

58

// 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 Applicat


ion

59

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
Internet And Java Applicat
ion

60

You might also like