0% found this document useful (0 votes)
26 views77 pages

2 (1,2) Introduction To Java

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views77 pages

2 (1,2) Introduction To Java

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object Oriented Programming

Unit 3. Introduction to Java


Outline
1. Java: Brief history and background
2. Run cycle
3. Basic program structure
4. Basic Java elements
5. Array
6. String
7. StringBuffer - StringBuilder

[CMP167-Unit 3-Introduction to Java] 2


1. Java: Brief History & Background
James Gosling
1995, Sun Microsystems

Use C/C++ as foundation


▪ “Cleaner” in syntax
▪ Less low-level machine interaction

▪ Write Once, Run ▪ Less


EverywhereTM efficient
▪ Extensive and
well documented
standard library

[CMP167
[CMP167-Unit
Lecture3-Introduction
1: IntroductiontotoJava]
Java] 3
2. Run Cycle Recap: Process

Writing Compiling Executing

• Tool: • Tool:
• Tool: Editor Compiler None
• Produce: • Produce: • Produce:
Source Code Executable Result
Bytecode

Compilation Error
Runtime Error
Logic Error

[CMP167
[CMP167-Unit
Lecture 3-Introduction
1: Introductionto
toJava]
Java] 4
2. Run Cycle Recap: Run Cycle for C Programs
vim welcome.c
◼ Writing/Editing Program
❑ Use an editor, e.g.: vim
❑ Source code must have a .c welcome.c

extension

◼ Compiling Program gcc -Wall welcome.c


❑ Use a C compiler, eg: gcc
❑ Default executable file: [Link] [Link]

◼ Executing Binary
❑ Type name of executable file [Link]

output

[CMP167
[CMP167-Unit
Lecture3-Introduction
1: Introduction
toto
Java]
Java] 5
2. Run Cycle Java: Compile Once, Run Anywhere?
◼ Normal executable files are directly dependent
on the OS/Hardware
❑ Hence, an executable file is usually not executable
on different platforms
❑ E.g: The [Link] file compiled on sunfire is not
executable on your Windows computer
◼ Java overcomes this by running the executable
on an uniform hardware environment simulated
by software
❑ The hardware environment is know as the Java
Virtual Machine (JVM)
❑ So, we only need a specific JVM for a particular
platform to execute all Java bytecodes without
recompilation
[CMP167
[CMP167-Unit
Lecture 3-Introduction
1: Introductionto
toJava]
Java] 6
2. Run Cycle Run Cycle for Java Programs
vim [Link]
◼ Writing/Editing Program
❑ Use a text editor, e.g: vim
❑ Source code must have .java extension [Link]

◼ Compiling Program
❑ Use a Java compiler, e.g.: javac javac [Link]
❑ Compiled binary has .class extension
❑ The binary is also known as Java
[Link]
Executable Bytecode
◼ Executing Binary
❑ Run on a Java Virtual Machine (JVM) java HelloWorld
◼ e.g.: java HelloWorld
(leave out the .class extension)
output
❑ Note the difference here compared to C
executable
[CMP167
[CMP167-Unit
Lecture3-Introduction
1: IntroductiontotoJava]
Java] 7
2. Run Cycle Java Execution Illustration
[Link] Normal executable (e.g.: C programs) are
tied to a specific platform (OS + Hardware)
This [Link] cannot work in a machine of
Windows 7 on Core 2 different architecture.

[Link] JVM provides a uniform environment for


Java bytecode execution.
Java Virtual Machine

Windows 7 on Core 2
They are the same
[Link] portable file.

Java Virtual Machine

MacOS on PowerPC
[CMP167
[CMP167-Unit
Lecture 3-Introduction
1: Introductionto
toJava]
Java] 8
3. Basic Java Program Structure
◼ Today: just the basic language components:
❑ Basic Program Structure
❑ Primitive data types and simple variables
❑ Control flow (selection and repetition statements)
❑ Input/output statements
◼ Purpose: ease you into the language
❑ You can attempt to “translate” some simple C
programs done in 501042 into Java
◼ We will gradually cover many other Java features over
the next few weeks

[CMP167
[CMP167-Unit
Lecture 3-Introduction
1: Introductionto
toJava]
Java] 9
3. Basic Structure Hello World!
#include <stdio.h> C
int main(void) {
printf("Hello World!\n");
return 0;
} HelloWorld.c

import [Link].*; // optional Java


public class HelloWorld { Beginners’ common
mistake:
public static void main(String[] args) {
Public class name not
[Link]("Hello World!"); identical to program’s
file name.
}
}
[Link]

[CMP167
[CMP167-Unit
Lecture3-Introduction
1: IntroductiontotoJava]
Java] 10
4.1 Arithmetic Expressions
4.1 Identifier, Variable, Constant (1/2)
◼ Identifier is a name that we associate with
some program entity (class name, variable name,
parameter name, etc.)
◼ Java Identifier Rule:
❑ May consist of letters (‘a’ – ‘z’, ‘A’ – ‘Z’), digit
characters (‘0’ – ‘9’), underscore (_) and dollar sign ($)
❑ Cannot begin with a digit character
◼ Variable is used to store data in a program
❑ A variable must be declared with a specific data type
❑ Eg: int countDays;
double priceOfItem;

[CMP167
[CMP167-Unit
Lecture
3-Introduction
1: Introduction
to to
Java]
Java] 12
4.1 Identifier, Variable, Constant (2/2)
◼ Constant is used to represent a fixed value
❑ Eg: public static final int PASSING_MARK = 65;
❑ Keyword final indicates that the value cannot change
◼ Guidelines on how to name classes, variables,
and constants:
❑ Class name: UpperCamelCase
◼ Eg: Math, HelloWorld, ConvexGeometricShape
❑ Variable name: LowerCamelCase
◼ Eg: countDays, innerDiameter, numOfCoins
❑ Constant: All uppercase with underscore
◼ Eg: PI, CONVERSION_RATE, CM_PER_INCH

[CMP167
[CMP167-Unit
Lecture 3-Introduction
1: Introductionto
toJava]
Java] 13
4.1 Numeric Data Types
◼ Summary of numeric data types in Java:
Type Size Range
Name (#bytes)
byte 1 -27 to 27-1
Integer Data

short 2
Types

-215 to 215-1
int 4 -231 to 231-1
long 8 -263 to 263-1
float 4
Point Data

Negative: -3.4028235E+38 to -1.4E-45


Floating-

Types

Positive: 1.4E-45 to 3.4028235E+38


double 8 Negative: -1.7976931348623157E+308 to -4.9E-324
Positive: 4.9E-324 to 1.7976931348623157E+308

◼ Unless otherwise stated, you are to use:


◼ int for integers
◼ double for floating-point numbers

[CMP167-Unit 3-Introduction to Java] 14


4.1 Numeric Operators
() Parentheses Grouping Left-to-right
++, -- Postfix incrementor/decrementor Right-to-left
Higher Precedence

++, -- Prefix incrementor/decrementor Right-to-left


+, - Unary +, -
*, /, % Multiplication, Division, Left-to-right
Remainder of division
+, - Addition, Subtraction Left-to-right
= Assignment Operator Right-to-left
+= -= *= /= %= Shorthand Operators

◼ Evaluation of numeric expression:


❑ Determine grouping using precedence
❑ Use associativity to differentiate operators of same precedence
❑ Data type conversion is performed for operands with different
data type

[CMP167-Unit 3-Introduction to Java] 15


4.1 Numeric Data Type Conversion
◼ When operands of an operation have differing types:
1. If one of the operands is double, convert the other to double
2. Otherwise, if one of them is float, convert the other to float
3. Otherwise, if one of them is long, convert the other to long
4. Otherwise, convert both into int

◼ When value is assigned to a variable of differing types:


❑ Widening (Promotion):
◼ Value has a smaller range compared to the variable
◼ Converted automatically
❑ Narrowing (Demotion):
◼ Value has a larger range compared to the variable
◼ Explicit type casting is needed

[CMP167-Unit 3-Introduction to Java] 16


4.1 Data Type Conversion
◼ Conversion mistake:
double d;
int i; What’s the mistake? How
do you correct it?
i = 31415;
d = i / 10000;

Q: What is assigned to d?
The (int) d expression is
◼ Type casting: known as type casting
double d; Syntax:
int i;
(datatype) value
d = 3.14159;
i = (int) d; // i is assigned 3
Effect:
Q: What is assigned to i if d contains value is converted explicitly to
3.987 instead? the data type stated if possible.

[CMP167-Unit 3-Introduction to Java] 17


4.1 Problem: Fahrenheit to Celsius
◼ Write a simple Java program [Link]:
❑ To convert a temperature reading in Fahrenheit, a real
number, to Celsius degree using the following formula:
5
celsius =  ( fahrenheit − 32)
9
❑ Print out the result

◼ For the time being, you can hard code a value


for the temperature in Fahrenheit instead of
reading it from user

[CMP167-Unit 3-Introduction to Java] 18


4.1 Solution: Fahrenheit to Celsius
public class Temperature { [Link]
public static void main(String[] args) {

double fahrenheit, celsius; Output:


Celsius: 50.833333333333336
fahrenheit = 123.5;
celsius = (5.0/9) * (fahrenheit – 32);
[Link]("Celsius: " + celsius);
}
}
Compare with C: printf("Celsius: %f\n", celsius);

◼ Notes:
❑ 5.0/9 is necessary to get the correct result (what will 5/9 give?)
❑ “+” in the printing statement
◼ Concatenate operator, to combine strings into a single string
◼ Variable values will be converted to string automatically
❑ There is another printing statement, [Link](), which does
not include newline at the end of line (more in section 4.3)

[CMP167-Unit 3-Introduction to Java] 19


4.2 Control Statements

Program Execution Flow


4.2 Boolean Data Type [new in Java]
◼ Java provides an actual boolean data type
❑ Store boolean value true or false, which are keywords
in Java
❑ Boolean expression evaluates to either true or false
SYNTAX

boolean variable;

boolean isEven;
int input;
// code to read input from user omitted
if (input % 2 == 0)
Example

isEven = true; Equivalent:


else isEven = (input % 2 == 0);
isEven = false;
if (isEven)
[Link]("Input is even!");

[CMP167-Unit 3-Introduction to Java] 21


4.2 Boolean Operators

Operators Description
< less than
Operands are variables /
> larger than values that can be
Operators
Relational

compared directly.
<= less than or equal
>= larger than or equal Examples:

== Equal X < Y
1 >= 4
!= not equal
&& and Operands are boolean
Operators

variables/expressions.
Logical

|| or
! Examples:
not
(X < Y) && (Y < Z)
^ exclusive-or (XOR) (!isEven)

[Link]
[CMP167-Unit 3-Introduction to Java] 22
4.2 Comparison with C
◼ In ANSI C, there is no boolean type.
❑ Zero means ‘false’ and any other value means ‘true’
int x;
... // assume x is assigned a non-negative value
if (x%3)
printf("%d is not divisible by 3.\n", x);
else
printf("%d is divisible by 3.\n", x);

◼ In Java, the above is invalid


◼ Java code:
int x;
... // assume x is assigned a non-negative value
if (x%3 != 0)
[Link](x + " is not divisible by 3.");
else
[Link](x + " is divisible by 3.");

[CMP167-Unit 3-Introduction to Java] 23


4.2 Selection Statements
if (a > b) { ◼ if-else statement
... ❑ else-part is optional
}
◼ Condition:
else {
... ❑ Must be a boolean expression
} ❑ Unlike C, integer values are NOT valid

switch (a) { ◼ switch-case statement


case 1: ◼ Expression in switch() must evaluate
...
to a value of char, byte, short or
break;
case 2: int type
case 3: ◼ break: stop the fall-through execution
... ◼ default: catch all unmatched cases;
default: may be optional
}

[CMP167-Unit 3-Introduction to Java]


24
4.2 Repetition Statements (1/2)
◼ Valid conditions:
while (a > b) {
... //body ❑ Must be a boolean expression
} ◼ while : check condition before
executing body
do { ◼ do-while: execute body before
... //body condition checking
} while (a > b);

◼ A: initialization (e.g. i = 0)
for (A; B; C) { ◼ B: condition (e.g. i < 10)
... //body ◼ C: update (e.g. i++)
}
◼ Any of the above can be empty
◼ Execution order:
❑ A, B, body, C, B, body, C, …
[CMP167-Unit 3-Introduction to Java] 25
4.2 Repetition Statements (2/2)
◼ In ANSI C, the loop variable must be declared before it is
used in a ‘for’ loop
int i;
for (i=0; i<10; i++) {
...
}

◼ In Java, the loop variable may be declared in the initialisation


part of the ‘for’ loop
◼ In example below, the scope of variable i is within the ‘for’
loop only
for (int i=0; i<10; i++) {
...
}

[CMP167-Unit 3-Introduction to Java] 26


4.3 Basic Input/Output

Interacting with the outside world


4.3 Reading input: The Scanner Class
PACKAGE

import [Link];

//Declaration of Scanner "variable"


Scanner scVar = new Scanner([Link]);

//Functionality provided
SYNTAX

[Link](); Read an integer value from


source [Link]

Read a double value from


[Link](); source [Link]

...... Other data types, to be covered


later

[CMP167-Unit 3-Introduction to Java] 28


4.3 Reading Input: Fahrenheit Ver 2
import [Link]; // or import [Link].*;

public class TemperatureInteractive {

public static void main(String[] args) {

double fahrenheit, celsius;


Scanner sc = new Scanner([Link]);

[Link]("Enter temperature in Fahrenheit: ");


fahrenheit = [Link]();

celsius = (5.0/9) * (fahrenheit – 32);


[Link]("Celsius: " + celsius);

}
}

[Link]

[CMP167-Unit 3-Introduction to Java] 29


4.3 Reading Input: Key Points (1/3)
◼ The statement
Scanner sc = new Scanner([Link]);
❑ Declares a variable “sc” of Scanner type
❑ The initialization “new Scanner([Link])”
◼ Constructs a Scanner object
❑ We will discuss more about object later
◼ Attaches it to the standard input “[Link]” (which is
the keyboard)
❑ This Scanner object sc will receive input from this source
◼ Scanner can attach to a variety of input sources; this is
just a typical usage

[CMP167-Unit 3-Introduction to Java] 30


4.3 Reading Input: Key Points (2/3)
◼ After proper initialization, a Scanner object
provides functionality to read value of various
types from the input source
◼ The statement
fahrenheit = [Link]();
❑ nextDouble() works like a function (called method

in Java) that returns a double value read interactively


❑ The Scanner object sc converts the input into the

appropriate data type and returns it


◼ in this case, user input from the keyboard is converted into a
double value

[CMP167-Unit 3-Introduction to Java] 31


4.3 Reading Input: Key Points (3/3)
◼ Typically, only one Scanner object is needed,
even if many input values are to be read.
❑ The same Scanner object can be used to call the
relevant methods to read input values

[CMP167-Unit
[CMP167 Lecture 3-Introduction
1: Introductionto
toJava]
Java] 32
4.3 Writing Output: The Standard Output
◼ [Link] is the predefined output device
❑ Refers to the monitor/screen of your computer

//Functionality provided
[Link]( output_string );
SYNTAX

[Link]( output_string );

[Link]( format_string, [items] );

Output:
[Link]("ABC"); ABCDEF
[Link]("DEF"); GHI
[Link]("GHI"); Very C-like 3.142

[Link]("Very C-like %.3f\n", 3.14159);

[CMP167-Unit
[CMP167 Lecture 3-Introduction
1: Introductionto
toJava]
Java] 33
4.3 Writing Output: printf()
◼ Java introduces printf() in Java 1.5
❑ Very similar to the C version
◼ The format string contains normal characters and a
number of specifiers
❑ Specifier starts with a percent sign (%)
❑ Value of the appropriate type must be supplied for each specifier
◼ Common specifiers and modifiers:
%d for integer value
%f for double floating-point value %[-][W].[P]type

SYNTAX
%s for string
-: For left alignment
%b for boolean value W: For width
%c for character value P: For precision

[CMP167-Unit
[CMP167 Lecture 3-Introduction
1: Introductionto
toJava]
Java] 34
4.3 Problem: Approximating PI
◼ One way to calculate the PI () constant:
4 4 4 4 4
 = − + − + − .........
1 3 5 7 9
◼ Write [Link] to:
1. Ask the user for the number of terms to use
for approximation
2. Calculate  with the given number of terms
3. Output the approximation in 6 decimal
places

[CMP167-Unit 3-Introduction to Java] 35


4.3 Solution: Approximating PI
import [Link].*; // using * in import statement

public class ApproximatePI {

public static void main(String[] args) {

int nTerms, sign = 1, denom = 1;


double pi = 0.0;

Scanner sc = new Scanner([Link]);

[Link]("Enter number of terms: ");


nTerms = [Link]();
4 4 4 4 4
for (int i = 0; i < nTerms; i++) {
= − + − + − .........
1 3 5 7 9
pi += 4.0 / denom * sign;
sign *= -1;
denom += 2;
}
[Link]("PI = %.6f\n", pi);
}
} [Link]
[CMP167-Unit 3-Introduction to Java] 36
4.4 API

Application Programming Interface


4.4 API (1/2)
◼ The Scanner class you have seen is part of the Java API
❑ API: an interface for other programs to interact with a program
without having direct access to the internal data of the program
❑ Documentation, SE7: [Link]
❑ For Java programmers, it is very important to refer to the API
documentation regularly!

◼ The API consists of many classes


❑ You do not need to know all the classes (there are easily a few
thousand classes altogether!)
❑ You will learn some more classes in this course

◼ This week reading assignment


❑ Read up Scanner class in the API documentation

[CMP167-Unit
[CMP167 3-Introduction
Lecture 1: Introduction to Java] 38
4.4 API (2/2)

[CMP167-Unit 3-Introduction to Java] 39


4.5 Math class, Class Attributes

Using the Math class


4.5 The Math class (1/2)
◼ From the API documentation

[CMP167-Unit 3-Introduction to Java] 41


4.5 The Math class (2/2)
◼ Package: [Link] (default)
◼ Some useful Math methods:
❑ abs()
❑ ceil()
❑ floor()
❑ max()
❑ min()
❑ pow()
❑ random()
❑ sqrt()

[CMP167-Unit 3-Introduction to Java] 42


4.5 Class Attributes
◼ The Math class has two class attributes

◼ A class attribute (or class member) is associated


with the class, not the individual instances (objects).
Every instance of a class shares the class attribute.
◼ We will explain about “objects” later.
◼ How to use it?
◼ Example:
double area = [Link] * [Link](radius,2);
◼ Here, [Link] is used as the constant 

[CMP167-Unit 3-Introduction to Java] 43


4.5 The Math class: Demo
[Link]
// To find the area of the largest circle inscribed
// inside a square, given the area of the square.
import [Link].*;

public class TestMath { radius

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

[Link]("Enter area of a square: ");


double areaSquare = [Link]();

double radius = [Link](areaSquare)/2;


double areaCircle = [Link] * [Link](radius, 2);

[Link]("Area of circle = %.4f\n",


areaCircle);
}
}

[CMP167-Unit 3-Introduction to Java] 44


4.6 User-defined Functions

Reusable and independent code


units
4.6 Function with a new name
◼ In Java, C-like function is known as static/class method
❑ Denoted by the “static” keyword before return data type
❑ Another type of method, known as instance method will be
covered later
[Link]
public class Factorial {
// Returns n!
// Pre-cond: n >= 0
public static int factorial (int n) { If n is too big, say
if (n == 0) return 1; 40, what will
else return n * factorial(n-1);
} happen? Why?
public static void main(String[] args) {
int n = 5; // You can change it to interactive input

[Link]("Factorial(%d) = %d\n", n, factorial(n));


}
}

[CMP167-Unit 3-Introduction to Java] 46


4.6 Method Parameter Passing
◼ All parameters in Java are passed by value (as
in C):
❑ A copy of the actual argument is created upon method
invocation
❑ The method parameter and its corresponding actual
parameter are two independent variables

◼ In order to let a method modify the actual


argument:
❑ An object reference data type is needed (similar to
pointer in C)
❑ Will be covered later

[CMP167-Unit 3-Introduction to Java] 47


Java Exercises
◼ Go to:
[Link]
◼ Complete the folowing Exercises

48
Java Exercises
◼ Write functions to calculate the below formulas
with n is provided by user (each formula is one
function):

49
Homework
◼ Setup the Java Environment (Java JDK,
environment variable), compile and run the Java
program by using command line.
◼ Setup IntelliJ IDEA Community Edition in your
computer

◼ Do the above exercises (in two previous slides)


in IntelliJ IDEA CE and run them.
50
5 Array in Java
5.1 Create array

◼ Create Arrays
dataType[] arrayRefVar = new dataType[arraySize];

◼ Example:
double[] myList = new double[10];

[CMP167-Unit 3-Introduction to Java] 52


5.2 Process Arrays
◼ We often use either for loop
or foreach loop because all of
the elements in an array are
of the same type and the size
of the array is known

[CMP167-Unit 3-Introduction to Java] 53


5.3 Foreach Loops
◼ JDK 1.5 introduced a new for loop known as
foreach loop or enhanced for loop, which
enables you to traverse the complete array
sequentially without using an index variable

[CMP167-Unit 3-Introduction to Java] 54


5.4 Passing Arrays to Methods

◼ We can invoke it by passing an array. For


example, the following statement invokes the
printArray method to display 3, 1, 2, 6, 4, and
2

[CMP167-Unit 3-Introduction to Java] 55


5.5 Return an Array from a Method
◼ A method may also return an array. For
example, the following method returns an
array that is the reversal of another array

[CMP167-Unit 3-Introduction to Java] 56


5.6 Exercise
◼ Write some java functions:
❑ Enter an array of N positive integers (N - input
from the keyboard)
❑ Calculate the sum of numbers in the array
❑ Calculate the sum of numbers divisible by 3
◼ Write the main function to call the above
functions.

[CMP167-Unit 3-Introduction to Java] 57


5.6 Exercise
◼ Go to:
[Link]
◼ Complete the folowing Exercises

58
Homework
◼ Write a Java program to calculate the average
value of array elements.
◼ Write a Java program to test if an array contains
a specific value.
◼ Write a Java program to find the index of an
array element.
◼ Write a Java program to find the second largest
element in an array.
◼ Write a Java program to convert an array to an
ArrayList.

59
6 String
Java String
◼ In Java, string is basically an object that
represents sequence of char values. An array of
characters works same as Java string. For
example:

[CMP167-Unit 3-Introduction to Java] 61


String methods

[CMP167-Unit 3-Introduction to Java] 62


String methods

[CMP167-Unit 3-Introduction to Java] 63


String methods

[CMP167-Unit 3-Introduction to Java] 64


Exercise
◼ Write a Java program to get the character at the given
index within the string.

◼ Write a Java program to compare two strings


lexicographically.

◼ Write a Java program to concatenate a given string to


the end of another string.

[CMP167-Unit 3-Introduction to Java] 65


Exercise
◼ Write a Java program to print the current date and time
in the specified format.

◼ Write a Java program to replace a specified character


with another character.

[CMP167-Unit 3-Introduction to Java] 66


7 StringBuffer - StringBuilder
StringBuffer
◼ Java StringBuffer class is used to create mutable
(modifiable) string. The StringBuffer class in java is same
as String class except it is mutable i.e., it can be
changed.
◼ Java StringBuffer class is thread-safe i.e. multiple
threads cannot access it simultaneously. So, it is safe
and will result in an order
◼ Constructor:

[CMP167-Unit 3-Introduction to Java] 68


StringBuffer – methods

[CMP167-Unit 3-Introduction to Java] 69


StringBuffer – methods

[CMP167-Unit 3-Introduction to Java] 70


StringBuffer - append() and insert()
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ”);
[Link]("Java");//now original string is changed
[Link](sb);//prints Hello Java
}
}
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
[Link](1,"Java");//now original string is changed
[Link](sb);//prints HJavaello
}
}
[CMP167-Unit 3-Introduction to Java] 71
StringBuffer - replace(), delete()
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3,"Java");
[Link](sb);//prints HJavalo
}
}
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3);
[Link](sb);//prints Hlo
}
} [CMP167-Unit 3-Introduction to Java] 72
StringBuilder
◼ Java StringBuilder class is used to create
mutable (modifiable) string. The Java
StringBuilder class is same as StringBuffer
class except that it is non-synchronized. It is
available since JDK 1.5.

[CMP167-Unit 3-Introduction to Java] 73


String and StringBuffer
◼ There are many differences between String and
StringBuffer. A list of differences between String
and StringBuffer are given below:

[CMP167-Unit 3-Introduction to Java] 74


StringBuffer and String Builder
◼ Java provides three classes to represent a sequence of
characters: String, StringBuffer, and StringBuilder. The
String class is an immutable class whereas StringBuffer
and StringBuilder classes are mutable. There are many
differences between StringBuffer and StringBuilder. The
StringBuilder class is introduced since JDK 1.5.
◼ A list of differences between StringBuffer and
StringBuilder are given below:

[CMP167-Unit 3-Introduction to Java] 75


Summary
Data Types:
- Numeric Data Types:
byte, short, int, float, double
- Boolean Data Type:
boolean
Expressions:
Java Elements

- Arithmetic Expression
- Boolean Expression
Control Flow Statements:
- Selection Statements: if-else, switch-case
- Repetition Statements: while, do-while, for
Classes:
- Scanner
- Math
Array
StringBuffer - StringBuilder
[CMP167-Unit 3-Introduction to Java] 76
End of file

You might also like