Basic Elements of Programming Language

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 82

Basic Elements of Programming Language

1
Outline
 Identifiers
 Variables
 Named constants
 Literals
 Reserved Words
 Comments
 Data Types
 Operators
 Statements
 Expressions
 Blocks
 Name Conventions
 Numeric Type Conversion
2
Identifiers
• Identifiers are the names that identify the elements such as
classes, methods, and variables in a program.
• All identifiers must obey the following rules:
– An identifier is a sequence of characters that consists of
letters, digits, underscores (_), and dollar signs ($).
– An identifier must start with a letter, an underscore (_), or
a dollar sign ($). It cannot start with a digit.
– An identifier cannot be a reserved word.
– An identifier cannot be true, false, or null.
– An identifier can be of any length.
– Example: $2, ComputeArea, area, radius, and
showMessageDialog are legal identifiers, whereas
– 2A and d+4 are not because they do not follow the rules. 3
Variables
• Variables are used to represent values that may be
changed in the program.
• Variables are for representing data of a certain type.
• The variable declaration tells the compiler to allocate
appropriate memory space for the variable based on its
data type.
• Example: int count; double radius;
• Every variable has a scope. The scope of a variable is
the part of the program where the variable can be
referenced.

4
Named Constants
• A named constant is an identifier that represents a
permanent value.
• The value of a variable may change during the execution
of a program, but a named constant, or simply constant,
represents permanent data that never changes.
• The word final is a Java keyword for declaring a
constant.
• Example: final double PI=3.14159;

5
Literals
• A literal is a constant value that appears directly in a
program.
• For example, 34 and 0.305 are literals in the following
statements:
• int numberOfYears = 34;
• double weight = 0.305;
• String str = “Hello”;

6
Reserved Words
• Reserved words or keywords are words that have
a specific meaning to the compiler and cannot be
used for other purposes in the program.

• For example, class, public, static, final, int,


double, void etc.

7
Comments
• Comments are documents that describes what the
program is and how the program is constructed.
• Comments help programmers to communicate and
understand the program.
• Comments are not programming statements and thus are
ignored by the compiler.
• In Java, there are three types of comments:
 Single Line comment: is use to comment texts on one line.
//this line prints the value of var1
 Multiple Line comment: Anything enclosed by the pair /* and
*/ is considered a comment.
 Javadoc Comment: javadoc comments begin with /** and end
with */. 8
Data Types
• Data types are used to determine what kind of
data is stored in memory.
• Every data type has a range of values.

• The compiler allocates memory space for each


variable or constant according to its data type.

• Java provides eight primitive data types for


numeric values, characters, and Boolean values.

9
Data Types
1. Numeric Data Types
– Java has six numeric types for integers and floating-point
numbers.
– The following lists are the six numeric data types, their
ranges, and their storage sizes.

10
Data Types
2. Character Data Type
– A character data type represents a single character.
– Example;
• char letter = 'A';
• char numChar = '4' ;
– A string literal must be enclosed in quotation marks (" ").
– A character literal is a single character enclosed in single quotation marks ('
').
– Therefore, "A" is a string, but 'A' is a character.

3. Boolean Data Type


– A boolean data type declares a variable with the value either true or false.

– For example:
• boolean n = true;
• boolean a = false; 11
Data Types

4. The String Type


– A string is a sequence of characters.
– The char type represents only one character.
– To represent a string of characters, use the data type
called String.
– For example: String message = "Welcome to Java";
– String is a predefined class in the Java library, just
like the classes System, JOptionPane, and Scanner.
– The String type is a reference type, not a primitive
type.

12
Operators
1. Assignment Operator(=)
– The assignment operator causes the operand
on the left side of the assignment statement to
have its value changed to the value on the
right side of the statement.
– Example:
• x=12;
• x = y;
• x = y+2;

13
Operators
2. Numeric or Arithmetic Operators
– The operators for numeric data types include the
standard arithmetic operators:

14
Operators
3. Relational Operators
– Java provides six comparison operators or relational operators.
– The following table shows the equality and relational
operators.

15
Operators
4. Logical Operators
– The logical operators can be used to create a compound Boolean expression.
– The NOT (! ) operator, which negates true to false and false to true.
– The AND (&&) of two Boolean operands is true if and only if both operands are
true.
– The OR (||) of two Boolean operands is true if at least one of the operands is
true.
– The EXCLUSIVE OR (^) of two Boolean operands is true if and only if the two
operands have different Boolean values.

16
Operators
5. Augmented Assignment Operators
– The arithmetic operators can be combined with the
assignment operator to form augmented operators.

17
Operators
6. Increment and Decrement Operators
– The increment (++) and decrement (– –) operators are for
incrementing and decrementing a variable by 1.

18
Operators
• Example: Consider the following code:
int i = 10;
int newNum = 10 * i++;
System.out.print("i is " + i + ", newNum is
" + newNum); // The output newNum is 100

int i = 10;
int newNum = 10 * (++i);
System.out.print("i is " + i + ", newNum is
" + newNum); // The output newNum is 110

double x = 1.0;
double y = 5.0;
double z = x-- + (++y); // The output of z is 7
19
Operators
7. Evaluating Expressions and Operator Precedence:
– Java expressions are evaluated in the same way as
arithmetic expressions.
– When more than one operator is used in an expression,
the following operator precedence rule is used to
determine the order of evaluation.
• Multiplication, division, and remainder operators are applied
first. If an expression contains several multiplication,
division, and remainder operators, they are applied
from left to right.
• Addition and subtraction operators are applied last. If an
expression contains several addition and subtraction
operators, they are applied from left to right.
20
Operators
• Example:

21
Operators
8. Object Operators:
– The new operator: is used to create an object from a
class.
– The instanceof operator: is used to test whether the
object is an instance of the specified type (class).

22
Numeric Type Conversions

• Floating-point numbers can be converted into integers


using explicit casting.
• Casting is an operation that converts a value of one data type
into a value of another data type.
• Casting a type with a small range to a type with a larger
range is known as widening a type.
• Casting a type with a large range to a type with a smaller
range is known as narrowing a type.
• For example, see the following statement:
– double d = 4.5;
– int i = (int)d; // i becomes 4
– System.out.println((int) 1.7); // displays 1.
– System.out.println((double) 1 / 2); // displays 0.5 23
Naming Conventions
• Following with the Java naming conventions makes your
programs easy to read and avoids errors.
• Listed below are the conventions for naming variables, methods,
and classes.
– Use lowercase for variables and methods. If a name consists of
several words, concatenate them into one, making the first
word lowercase and capitalizing the first letter of each
subsequent word, for example, the variables radius and area
and the method showMessageDialog.
– Capitalize the first letter of each word in a class name, for
example, the class names ComputeArea, System, and
JOptionPane.
– Capitalize every letter in a constant, and use underscores
between words—for example, the constants PI and
MAX_VALUE. 24
Programming Control Structures

25
Programming Control Structures

• There are three control structure in java.


1. Sequential
2. Selection
3. Repetitive/Loop/

1. Sequential Control Structure


– Sequential structure is trivial.
– Simply list the statements to execute in the order in
which they should execute.
26
2. Selection Control Structure
• The program can decide which statements to
execute based on a condition.

• Java has several types of selection statements:


1. One-way if statements,
2. Two-way if-else statements,
3. Nested if statements,
4. switch statements, and
5. Conditional expressions.

27
Selection …
1. One -Way if Statements
– An if statement executes the statements if the
condition is true
– A one-way if statement executes an action if and only
if the condition is true.
– The syntax for a one-way if statement is:

if (boolean-expression) {
statement(s);
}
28
Selection …
2. Two-Way if-else Statements
– An if-else statement decides which statements to
execute based on whether the condition is true or
false.
– The syntax for a two-way if-else statement:
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
29
Selection …
3. Nested if and Multi-Way if-else Statements
• An if statement can be inside another if statement
to form a nested if statement.
• The nested if statement can be used to implement
multiple alternatives.
• Example:
• For instance, assigns a letter grade to the variable
grade according to the score, with multiple
alternatives.

30
Selection …

31
Selection…
4. switch Statements
– A switch statement executes statements based on the
value of a variable or an expression
– Overuse of nested if statements makes a program
difficult to read.
– Due to this problem, Java provides a switch
statement to simplify coding for multiple conditions.

32
Selection…
• Syntax:
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
...
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}

33
Selection…

• The switch statement observes the following


rules:
– The switch-expression must yield a value of char,
byte, short, int, or String type and must always be
enclosed in parentheses.

– The value1, . . ., and valueN must have the same


data type as the value of the switch-expression.
• Note that value1, . . ., and valueN are constant
expressions, meaning that they cannot contain variables,
such as 1 + x.
34
Selection…
– When the value in a case statement matches the value
of the switch-expression, the statements starting
from this case are executed until either a break
statement or the end of the switch statement is
reached.
– The default case, which is optional, can be used to
perform actions when none of the specified cases
matches the switch-expression.

– The keyword break is optional. The break statement


immediately ends the switch statement.
35
Selection…
5. Conditional Expressions
– A conditional expression evaluates an expression based on a
condition.
– Syntax: boolean-expression ? expression1 : expression2;
– Example, the following statement assigns 1 to y if x is greater than 0,
and -1 to y if x is less than or equal to 0.

if (x > 0)
y = 1; y = (x > 0) ? 1 : -1;
else
y = -1;

36
3. Repetitive /Loops

• A loop can be used to tell a program to


execute statements repeatedly.
• Java has four Loop control structures
– The While Loop
– The Do-while Loop
– For Loop
– For each or enhanced for loop
– Nested Loop

37
Repetitive…
1. The while Loop
– A while loop executes statements repeatedly while
the condition is true.
– The syntax for the while loop is:

while (condition) {
Statement(s);
}

38
Repetitive…
2. The do-while Loop
– A do-while loop is the same as a while loop except
that it executes the loop body first and then checks the
loop condition.
– The do-while loop is a variation of the while loop.
– Its syntax is:

do {
Statement(s);
} while(condition);

39
Repetitive…
3. The for Loop
– A for loop has a concise syntax for writing loops.
– In general, the syntax of a for loop is:

for (initialization; condition; increment) {


Statement(s);
}

40
Repetitive…
4. for-each Loop or enhanced for loop
– Java supports a convenient for loop, known as a for-each loop, which enables
you to traverse the array sequentially without using an index variable.
– The syntax for a for-each loop is:

for (elementType element: arrayRefVar) {


// Process the element
}
– For example, the following code displays all the elements in the array myList:
– double[] myList = {1.5,5.5,3.4,0.5,7.9};

for (double u: myList) {


System.out.println(u);
}

– You can read the code as “for each element u in myList, do the following.”
41
Repetitive…
5. Nested Loops
– A loop can be nested inside another loop.
– Nested loops consist of an outer loop and one or more inner loops.
public class MultiplicationTable {
public static void main(String[] args) {
System.out.println(" Multiplication Table");
System.out.print(" ");
for (int j = 1; j <= 9; j++)
System.out.print(" " + j);
System.out.println("\n ----------------------------------------------------------");
for (int i = 1; i <= 9; i++) {
System.out.print(i + " | ");
for (int j = 1; j <= 9; j++) {
System.out.print(i * j);
}
System.out.println();
}
} 42
}
Repetitive…
6. Jumping Statements
– The break and continue keywords provide additional
controls in a loop
– Example using Break

43
Jumping Statements
• Example using continue

44
Methods in Java

45
Methods in Java
• Methods can be used to define reusable code and
organize and simplify code.

• A method is a collection of statements grouped


together to perform an operation.

• Suppose that you need to find the sum of integers


from 1 to 10, from 20 to 37, and from 35 to 49,
respectively. You may write the code as follows:

46
Method…
Without Method, it needs three independent for loop.

47
Method…
Using Method, only one for loop is needed
public class TestMethod{
public static void main(String[] args) {
System.out.println("Sum from 1 to 10 is " + sum(1, 10));
System.out.println("Sum from 20 to 37 is " + sum(20, 37));
System.out.println("Sum from 35 to 49 is " + sum(35, 49));
}
public static int sum(int a, int b){
int result = 0;
for (int i = a; i <= b; i++)
result += i;
return result;
}
}
48
Method…
•Defining a Method:
–A method definition consists of its method name, parameters, return value type, and body.
–The syntax for defining a method is:

modifier returnValueType methodName(list of parameters) {


// Method body;
}

49
Method…
• Overloading Methods
– Overloading methods enables you to define the
methods with the same name as long as their
signatures are different.
– Method Overloading is a feature that allows a class to
have two or more methods having same name, if their
argument lists are different.
– If a class have multiple methods by same name but
different parameters, it is known as Method
Overloading.

50
Overloading Method…
public class TestMethodOverloading {
public static void main(String[] args) {
System.out.println("The maximum of 3 and 4 is “ +max(3, 4) );
System.out.println("The maximum of 3.0 and 5.4 is “+ max(3.0, 5.4) );
System.out.println("The maximum of 3.0, 5.4, and 10.14 is “ + max(3.0, 5.4, 10.14) );
}
public static int max(int num1, int num2){
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, double num2){
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, double num2, double num3){
return max(max(num1, num2), num3);
}
51
}
Method Abstraction and Stepwise Refinement
• Method abstraction is achieved by separating the use of a method from
its implementation.

• The client can use a method without knowing how it is implemented.

• The details of the implementation are encapsulated in the method and


hidden from the client who invokes the method.

• This is also known as information hiding or encapsulation.


• When writing a large program, you can use the divide-and-conquer
strategy, also known as stepwise refinement, to decompose it into sub-
problems.

• The sub-problems can be further decomposed into smaller, more


manageable problems.
52
Array in Java

53
Array In Java

• An array is a collection of similar type of elements


that have contiguous memory location.
• Java array is an object that contains elements of
similar data type.
• It is a data structure where we store similar
elements.
• The first element of the array is stored at 0 index.
• Arrays can be classified into:
– Single Dimensional Array
– Two-Dimensional Array
– Multi Dimensional Array
54
Single Dimensional Array

– Single-dimensional array is used to store linear


collections of elements.
– Suppose, for instance, that you need to read 100
numbers, compute their average, and find out how
many numbers are above the average.
– In order to accomplish this task, the numbers must all
be stored in variables.
– Declaration of 100 variables without array is like
writing identical code 100 times repeatedly.
– This way writing a program would be impractical and
also inefficient.

55
Single Dimensional Array
– Hence, Java provides an array that stores a fixed-size
sequential collection of elements of the same type.
– You can store all 100 numbers into an array and access
them through a single array variable.
– An array is reference variable that is used to access
the elements in an array using an index.
– Instead of declaring individual variables, such as
number0, number1, . . . , and number99, you
declare one array variable such as numbers and use
numbers[0] , numbers[1] , . . . , and numbers[99] to
represent individual variables.
– Example:
56
Single Dimensional Array

57
Single Dimensional Array
• Declaring and Creating Array Variables
 Declaration array variable:
• elementType[] arrayRefVar;
• Example: double[] myList;
 Creating Array:
• Unlike declarations for primitive data type variables, the
declaration of an array variable does not allocate any space in
memory for the array.
• It creates only a storage location for the reference to an array.
• You cannot assign elements to an array unless it has already been
created.
• After an array variable is declared, you can create an array by
using the new operator with the following syntax:
• arrayRefVar = new elementType[arraySize];
58
Single Dimensional Array
• Declaring an array variable, creating an array, and assigning the reference of the array to
the variable can be combined in one statement as:
– elementType[] arrayRefVar = new elementType[arraySize];
OR
– elementType arrayRefVar[] = new elementType[arraySize];
• Example: double[] myList = new double[10];
• To assign values to the elements, use the syntax:
arrayRefVar[index] = value;
• For example, the following code initializes the array.

myList[0] = 5.6;
myList[1] = 4.5;
myList[2] = 3.3;
myList[3] = 13.2;
myList[4] = 4.0;
myList[5] = 34.33;
myList[6] = 34.0;
myList[7] = 45.45;
myList[8] = 99.993;
myList[9] = 11123; 59
Single Dimensional Array
• The above array is stored in a memory in the following manner:

60
Single Dimensional Array

• Array Size and Default Values


– You can access or obtain the array size using
arrayRefVar.length.
– When an array is created, its elements are assigned the
default value of 0 for the numeric primitive data types,
\u0000 for char types, and false for boolean types.
• Array Indexed Variables
– Each element in the array is represented using the
following syntax, known as an indexed variable:
arrayRefVar[index];
– For example, myList[9] represents the last element in
the array myList. 61
Single Dimension…
• Array Initializers
– An array initializer is used to combines the declaration,
creation, and initialization of an array in one statement using
the following syntax:
elementType[] arrayRefVar = {value0, value1, ..., valuek};
– For example: double[] myList = {1.9, 2.9, 3.4, 3.5};
– This line of code declares, creates, and initializes the array
myList with four elements, which is equivalent to the
following statements:
– double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5; 62
Single Dimension…

• Caution:
– The new operator is not used in the array-initializer syntax.
– Splitting an array initializer would cause a syntax error.
– Example: double[] myList;
myList = {1.9, 2.9, 3.4, 3.5}; This statement is wrong.
• Processing/Accessing Array elements
– When processing array elements, you will often use a for loop
—for two reasons:
 All of the elements in an array are of the same type.
 Since the size of the array is known, it is natural to use a for loop.
– Assume the array is created as follows:
double[] myList = new double[10];
– The following are some examples of processing arrays.
63
Single Dimension…
1. Initializing arrays with user input values:
import java.util.Scanner;
public class ArrayInitializing{
public static void main(String[] args){
Scanner input = newScanner(System.in);
System.out.print("Enter " + myList.length + " values:");
for (int i = 0; i < myList.length; i++){
myList[i] = input.nextDouble();
}
}
}

64
Single Dimension…
2. Initializing arrays with random values: The following loop initializes the array myList
with random values between 0.0 and 100.0, but less than 100.0.

for (int i = 0; i < myList.length; i++) {


myList[i] = Math.random() * 100;
}

3. Displaying arrays: To print an array, you have to print each element in the array using a
loop like the following:

for (int i = 0; i < myList.length; i++) {


System.out.print(myList[i] + " ");
}
4. Summing all elements: Use a variable named total to store the sum. Initially total is 0.
Add each element in the array to total using a loop like this:

double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
} 65
Single Dimension…
5. Finding the largest element: Use a variable named max to store the largest element. Initially
max is myList[0] . To find the largest element in the array myList, compare each element with
max, and update max if the element is greater than max.

double max = myList[0];


for(int i = 1; i < myList.length; i++) {
if (myList[i] > max)
max = myList[i];
}

6. Finding the smallest index of the largest element: Often you need to locate the largest element
in an array. If an array has more than one largest element, find the smallest index of such an
element.

double max = myList[0];


int indexOfMax = 0;
for(int i = 1; i < myList.length; i++) {
if(myList[i] > max) {
max = myList[i];
indexOfMax = i;
}
} 66
Single Dimension…

7. Random shuffling: In many applications, you need


to randomly reorder the elements in an array. This is
called shuffling. To accomplish this, for each element
myList[i] , randomly generate an index j and swap
myList[i] with myList[j],as follows:
for (int i = 0; i < myList.length; i++) {
// Generate an index j randomly
int j = (int) (Math.random()*mylist.length);
// Swap myList[i] with myList[j]
double temp = myList[i];
myList[i] = myList[j]
myList[j] = temp;
}
67
Single Dimension…
8. Shifting elements: Sometimes you need to shift the
elements left or right. Here is an example of shifting the
elements one position to the left and filling the last
element with the first element:

double temp = myList[0];


for (int i = 1; i < myList.length; i++) {
myList[i - 1] = myList[i];
}
myList[myList.length - 1] = temp;

68
Single Dimension…
9. Simplifying coding: Arrays can be used to greatly simplify coding for certain tasks.

Using Array
String[] months = {"January", "February", ...,
"December"};
System.out.print("Enter a month number (1 to 12): ");
int monthNumber = input.nextInt();
System.out.println("The month is " + months[monthNumber -
1]);

Without Array or using multi-way if-else statement :

if (monthNumber == 1)
System.out.println("The month is January");
else if (monthNumber == 2)
System.out.println("The month is February");
...
else
System.out.println("The month is December");
69
Two-Dimensional Array
• Data in a table or a matrix can be represented using a two-
dimensional array.
• One-dimensional array is used to store linear collections of elements,
but two-dimensional array is used to store a matrix or a table.
• An element in a two-dimensional array is accessed through a row and
column index.

• Declaring Variables of Two-Dimensional Arrays


– The syntax for declaring a two-dimensional array is:

elementType[][] arrayRefVar;
OR
elementType arrayRefVar[][];

– Example: int[][]matrix; or
int matrix[][];
70
Two-Dimensional…
• Creating Two-Dimensional Arrays
– arrayRefVar = new elementType[][];
– Example: matrix = new int[5][5];

– To assign the value 7 to a specific element at row 2 and


column 1: matrix[2][1] = 7; 71
Two-Dimensional…
• Processing/Accessing Two-Dimensional Arrays
– Nested for loops are often used to process a two-dimensional array.
– Suppose an array matrix is created as follows:
int[][] matrix = new int[10][10];
– The following are some examples of processing two-dimensional arrays.
• Initializing arrays with input values. The following loop initializes
the array with user input values:

import java.util.Scanner;
Scanner input = new Scanner(System.in);
System.out.println("Enter " + matrix.length + " rows and " +
matrix[0].length + " columns: ");
for(int row = 0; row <matrix.length; row++){
for(int column = 0; column <matrix[0].length; column++){
matrix[row][column] = input.nextInt();
}
}
72
String Processing

73
String…
• The classes String, StringBuilder, and StringBuffer,
StringTokenizer are used for processing strings.

• The String Class


– A string is a sequence of characters.
– In many languages, strings are treated as an array of
characters, but in Java a string is treated as an object.
– A String object is immutable: Its content cannot be
changed once the string is created.

74
String…
• Constructing a String
– You can create a string object using
• A string literal or
• An array of characters.
– To create a string from a string literal, use the syntax:
– String newString = new String(stringLiteral);
– The argument stringLiteral is a sequence of characters enclosed inside
double quotes.
– String message = new String("Welcome to Java");
– Java treats a string literal as a String object. Thus, the following statement
is valid:
– String message = "Welcome to Java”;
– To create a string from an array of characters.
– For example, the following statements create the string "Good Day”:
char[] charArray = {'G' , 'o' , 'o' , 'd' , ' ' , 'D’ , 'a' , 'y' };
– String message = new String(charArray); 75
String…
• The StringBuilder and StringBuffer Classes
– The StringBuilder and StringBuffer classes are
similar to the String class except that the String class
is immutable.
– In general, the StringBuilder and StringBuffer
classes can be used wherever a string is used.
– StringBuilder and StringBuffer are more flexible
than String.
– You can add, insert, or append new contents into
StringBuilder and StringBuffer objects, whereas the
value of a String object is fixed once the string is
created. 76
String…
– The StringBuilder class is similar to StringBuffer except that the
methods for modifying the buffer in StringBuffer are synchronized,
which means that only one task is allowed to execute the methods.
– Use StringBuffer if the class might be accessed by multiple tasks
concurrently.
– Using StringBuilder is more efficient if it is accessed by just a
single task.
– Example: To modify strings in the StringBuilder and StringBuffer is:
String str = "Welcome";
StringBuilder sb = new StringBuilder(str);
StringBuffer sbf = new StringBuffer(str);
sb.append("To BDU");
sb.append(“To Bahir Dar University");
System.out.println(sb);
System.out.println(sbf);
77
String…
• StringBuffer
– StringBuffer is mutable means one can change the value of the object .
– The object created through StringBuffer is stored in the heap .
– StringBuffer  has the same methods as the StringBuilder , but each method in
StringBuffer is synchronized that is StringBuffer is thread safe .
– Due to this it does not allow  two threads to simultaneously access the same method .
– Each method can be accessed by one thread at a time .
– But being thread safe has disadvantages too as the performance of the StringBuffer
hits due to thread safe property .
– Thus  StringBuilder is faster than the StringBuffer when calling the same methods of
each class.
– StringBuffer value can be changed , it means it can be assigned to the new value .
• StringBuilder
– StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it
can also be modified .
– The main difference between the StringBuffer and StringBuilder is that
StringBuilder is also not thread safe. 
– StringBuilder is fast as it is not thread safe .  78
Difference between StringBuffer and StringBuilder

79
StringTokenizer Class

• When you read a sentence, your mind breaks it into tokens—


individual words and punctuation marks that convey meaning to
you.
• Compilers also perform tokenization.
• They break up statements into individual pieces like keywords,
identifiers, operators and other programming-language elements.
• The StringTokenizer class allows an application to break a
string into tokens.
• Tokens are separated from one another by delimiters, typically
white-space characters such as space, tab, newline and comma.
• Other characters can also be used as delimiters to separate
tokens.
80
Example: StringTokenizer
import java.util.StringTokenizer;
public class Tokenizer{
public static void main(String[] args){
String str = "This is String , split by
tringTokenizer, created by John";
StringTokenizer st = new StringTokenizer(str);
System.out.println("---- Split by space ------");
while(st.hasMoreElements())
{ System.out.println(st.nextElement());
}
System.out.println("---- Split by comma ','------");
StringTokenizer st2 = new StringTokenizer(str, ",");
while (st2.hasMoreElements()){
System.out.println(st2.nextElement());
}
}
} 81
The End!!

82

You might also like