You are on page 1of 164

Java

Sabyasachi Moitra
moitrasabyasachi@hotmail.com
Introduction
O Like C & C++, Java is also a high level
programming language.
O Java programming language was developed by
Sun Microsystems which was initiated by James
Gosling and was released in 1995.
O Like C++, Java is also an object oriented
programming language.
O Platform independent
- Unlike C/C++, when a Java code is compiled it is
converted into bytecode. This bytecode is a
platform-independent code because it can be
run on multiple platforms.
2
Types of Java Applications
O Standalone Application
- An application that we need to install on every
machine.
O Web Application
- An application that runs on the server side and
creates dynamic page.
O Enterprise Application
- An application that is distributed in nature.
O Mobile Application
- An application that is created for mobile
devices.
3
Java Platforms / Editions
O Java SE (Java Standard Edition)
- It is a java programming platform.
O Java EE (Java Enterprise Edition)
- It is an enterprise platform which is mainly used
to develop web and enterprise applications.
O Java ME (Java Micro Edition)
- It is a micro platform which is mainly used to
develop mobile applications.
O JavaFx
- It is used to develop rich internet applications.
4
OOP vs POP
OOP POP
Object Oriented Programming Procedure Oriented Programming
Programs are divided into what are known Large programs are divided into smaller
as objects. programs known as functions.
Objects may communicate with each other Data move openly around the system from
through functions. function to function.
Data is hidden & cannot be accessed by Does not have any proper way for hiding
external functions. Thus, more secure. data. Thus, less secure.
Follows bottom-up approach. Follows top-down approach.

5
OOP Terminologies
Terminology Description
Objects are the basic run-time entities in an
Object
object-oriented system.
A class is a collection of similar type of
objects.
Class Example
Employee emp1;

emp1  OBJECT
Employee  CLASS

Data abstraction refers to the act of


representing essential features without
Data Abstraction
including the background details or
explanations.
Data encapsulation refers to the wrapping
Data Encapsulation
up of data & functions into a single unit.

6
OOP Terminologies (2)
Terminology Description
Inheritance is the process by which objects of one
Inheritance class acquire the properties of objects of another
class.
• Ability to take more than one form.
• Using a single function name to perform
different types of tasks is known as Function
Polymorphism Overloading.
• The process of making an operator to exhibit
different behaviors in different instances is
termed as Operator Overloading.
Connecting a method call to the method body is
known as Binding.
When type of the object is determined at compile-
Dynamic Binding
time, it is known as Static Binding.
When type of the object is determined at run-time,
it is known as Dynamic Binding.
Involves specifying the name of the object, name
Message Passing of the function (message) & the information to be
sent.
7
C++ vs Java
C++ Java
C++ is platform-dependent. Java is platform-independent.
C++ is mainly used for system Java is mainly used for
programming. application programming.
C++ supports multiple Java doesn't support multiple
inheritance. inheritance through class. It
can be achieved by interfaces
in java.
C++ supports operator Java doesn't support operator
overloading. overloading.
C++ uses compiler only. Java uses both compiler and
interpreter.
8
First Java Program
Source Code
Output
(HelloWorld.java)
class HelloWorld HELLO WORLD!!!
{
public static
void main(String
args[])
{

System.out.print
ln("HELLO WORLD!!!");
}
}

9
Parameter Description
class • Keyword.
• Used to declare a class in java.
public • Keyword.
• Access modifier.
• Represents visibility.
• Means visible to all.
static • Keyword.
• If any method is declared as
static, it is known as static
method.
• The core advantage of static
method is that there is no need
to create an object to invoke the
static method.
• The main method is executed
by the JVM, so it doesn't require
to create object to invoke the
main method.
• Saves memory.
10
Parameter Description
void • Return type of the
method.
• Means the method
doesn't return any value.
main() Represents the start-up of
the program.
String args[] Used for command line
argument.
System.out.println() Used to print statement.

11
Flow of Java Program
HelloWorld.java

COMPILER

HelloWorld.class

JVM

Output

12
JVM, JRE & JDK
JVM
O Java Virtual Machine.
O It is an abstract machine which provides a runtime
environment for executing the java bytecode.
JRE
O Java Runtime Environment.
O It is the implementation of JVM.
O It physically exists.
O It contains the set of libraries + other files that JVM uses at
runtime.
JDK
O Java Development Kit.
O It physically exists.
O It contains JRE + development tools.

13
JVM, JRE & JDK (2)
JVM
JRE
JDK

14
Constants, Variables &
Data Types
Tokens
Smallest individual units in a program are
known as tokens.

TOKENS

Special
Keywords Identifiers Constants Strings Operators
Symbols

16
Keywords
O Reserved identifiers.
O Cannot be used as names for the program
variables or other user-defined program
elements.
abstract boolean break byte
case catch char class
const continue default do
double else enum extends
final finally float …..
17
Identifiers
O Identifiers refer to the names of variables,
functions, arrays, etc., created by the
programmers.
O An identifier starts with a letter A to Z, a to z, or
an underscore '_' followed by zero or more
letters, underscores, and digits (0 to 9).
O Punctuation characters such as @, $, and % are
not allowed within identifiers.
O Case-sensitive, i.e., account & ACCOUNT are two
different identifiers.

18
Literals
Literals (or Constants) refer to fixed values that
do not change during the execution of a
program.
Literals

Backslash
Floating Point Boolean Character
Integer Literals String Literals Character
Literals Literals Literals
Literals

5 5.5 true 'A' "ABC" '\n'

19
Variables
O A variable is a data name that is used to
store a data value which can be changed
during program execution.
O E.g. sum, avg, etc.

Types of Variable Description


Variable known only to the function in
Local
which it is defined.
Variable declared inside the class but
Instance
outside the method.
Variable that exists & retains its value
Static even after the control is transferred to
the calling function. 20
Data Types
byte

short
Integer
int

long

float
Primitive
Floating-Point
double
DATA TYPE

Character char

Boolean boolean

Array

Non-Primitive String

etc.

21
Operators & Expressions
Operators
O An operator is a symbol that tells the
computer to perform certain mathematical
or logical manipulations.
O Operators are used in programs to
manipulate data & variables.
O They usually form a part of the
mathematical or logical expressions.

23
Types of Operator
Type Operators
Arithmetic Operators +, -, *, /, %
Relational Operators ==, !=, >, <, >=, <=
Logical Operators &&, ||, !
Increment & Decrement ++, --
Operators
Conditional Operator ?:
Bitwise Operators &, |, ~, ^, <<, >>
=, +=, -=, *=, /=, %=, &=, |=,
Assignment Operators
^=, <<=, >>=

24
Example
(Scanner class)

25
Example
(BufferedReader class)

26
Scanner VS BufferedReader
Scanner BufferedReader
Reads data alone. Can’t read data alone, takes
help from InputStreamReader.
Reads & parse data, hence Only reads data, hence faster.
slower.
Reads int, float, char. Reads only strings.
Buffer size 1kb, hence Buffer size 8kb, hence
suitable for reading small suitable for reading file with
user inputs. long string.
Available from JDK 5. Available from JDK 1.1.

27
Decision Making &
Branching
Simple if Statement
O An if statement consists of a Boolean
expression followed by one or more
statements.
O If the Boolean expression evaluates to true,
then the block of code inside the if
statement will be executed. If the Boolean
expression evaluates to false, then the first
set of code after the end of the if statement
will be executed.
29
Example

30
if…else Statement
O An if statement can be followed by an
optional else statement, which executes
when the Boolean expression is false.
O If the Boolean expression evaluates to true,
then the if block will be executed, otherwise,
the else block will be executed.

31
Example

32
Nested if or if…else Statements
Use of one if or if…else statement inside
another if or if…else statement(s).

33
Example

34
if…else if Ladder Statement
The if…else if statement is used to execute
one code from multiple conditions.

35
Example

36
switch Statement
A switch statement allows a variable to be
tested for equality against a list of values
known as case.

37
Example

38
Decision Making &
Looping
What is loop?
O A loop in Java language is used to execute a
block of code or a part of the program for
several times.
O It saves code.

40
Types of Loops

LOOPS

while do while for for-each

41
while Loop
O Iterates the code until the condition is false.
O Condition is given before the code. So the
code may be executed 0 or more times.

42
Example
Source Code Output
public class WhileExample
{
1
public static void 2
main(String[] args)
{
3
int i=1; 4
while(i<=10)
5
{ 6
System.out.println(i);
7
i++; 8
}
}
9
} 10

43
do while Loop
O Iterates the code until the condition is false.
O Condition is given after the code. So at least
once the code is executed whether the
condition is true or false.

44
Example
Source Code Output
public class DoWhileExample
{
1
public static void 2
main(String[] args)
{
3
int i=1; 4
do
5
{ 6
System.out.println(i);
7
i++; 8
}while(i<=10);
}
9
} 10

45
for Loop
O Iterates the code until the condition is false.
O Initialization, condition and
increment/decrement is given before the
code. So the code may be executed 0 or
more times.

46
Example
Source Code Output
public class ForExample
{
1
public static void 2
main(String[] args)
{
3
int i=1; 4
for(i=1;i<=10;i++)
5
{ 6
System.out.println(i);
}
7
} 8
}
9
10

47
for-each Loop
O Introduced in Java5.
O Mainly used to traverse array or collection
elements.
O Eliminates the possibility of bugs and makes
the code more readable.

48
Example
Source Code Output
public class ForEachExample
{
12
public static void 13
main(String[] args)
{
14
int arr[]={12,13,14,44}; 44
int i;

for(i:arr)
{
System.out.println(i);
}
}
}

49
break VS continue
break continue
O Can appear in both O Can appear only in
switch and loop loop statements.
statements. O When encountered,
O When encountered, gets the control to the
terminates the block next iteration of the
and gets the control loop.
out of the switch or
loop.

50
Example
break continue
public class BreakExample public class ContinueExample
{ {
public static void public static void
main(String[] args) main(String[] args)
{ {
int i=1; int i=1;

for(int i=1;i<=10;i++) for(int i=1;i<=10;i++)


{ {
if(i==5) if(i==5)
break; continue;

System.out.println(i); System.out.println(i);
} }
} }
} }

1234 1 2 3 4 6 7 8 9 10
51
Arrays
What is Array?
O Collection of homogeneous (similar)
elements (data) in a contiguous memory
location.
O Linear Data Structure
- A data structure (data organization and
storage format that enables efficient access
and modification) is said to be linear if the
elements form a sequence.

53
Example (1D Array)

54
Example (2D Array)

55
Classes & Objects

56
What is a Class?
O A class is a way to bind the data & its
associated methods together.
O General form of a class definition:

57
Access Modifiers in Java
Access Modifier Description
Accessible only within the
private
class.
Accessible only within the
default
package.
• Accessible within the
package and outside the
package but through
protected
inheritance only.
• Can't be applied on the
class.
public Accessible everywhere.
58
Determining Access to Class
Members

59
What is an Object?
O An object is an entity that has state and
behaviour.
O General form of a object declaration:

Class-name object-name=new class-name();

60
Example
(Rectangle.java)

61
RecAreaCalc.java

62
Output

63
Constructor

64
What is Constructor?
O A special type of method that is used to
initialize the object.
O It is invoked at the time of object creation.

65
Types of Constructor

CONSTRUCTOR
constructor constructor
without with
parameters parameters

Default Parameterized

66
Default Constructor
Source Code Output
class Student{
int id;
Bike is created
String name; 0 null
Student(){System.out.println(“S
tudent is created");}
void
display(){System.out.println(id
+" "+name);}
public static void main(String
args[]){
Student s=new Student();
s.display();
}
}

67
Parameterized Constructor
Source Code Output
class Student
{ 111 Karan
int id;
String name;

Student(int i,String n)
{
id=i;
name=n;
}
void display()
{

System.out.println(id+"
"+name);
}

public static void


main(String args[])
{
Student s=new
Student(111,"Karan");

s.display();
}
} 68
Constructor Overloading
O A technique in Java in which a class can
have any number of constructors that differ
in their parameter lists.
O The compiler differentiates these
constructors by taking into account the
number of parameters in the list and their
type.

69
Example

70
Constructor VS Method
Constructor Method
Constructor is used to Method is used to expose
initialize the state of an behaviour of an object.
object.
Constructor must not have Method must have return
return type. type.
Constructor is invoked Method is invoked explicitly.
implicitly.
Constructor name must be Method name may or may not
same as the class name. be same as class name.

71
this Keyword
O Refers to the current object.

//use this to resolve name-space collisions


Emp(int eid,String ename,double esal)
{
this.eid=eid;
this.ename=ename;
this.esal=esal;
}

72
Java Garbage Collection
O A way to destroy the unused objects in Java.
O Frees memory of an object which is out of its
scope.
O Similar destructor in C++.

73
Example

74
static variable
O Used to refer the common property of all
objects, i.e., not unique for each object.
O Gets memory only once.

75
Example

76
static Method
O A static method belongs to a class rather
than the object of the class.
O A static method can be invoked without the
need for creating an instance of a class.
O static method can access static data
member and can change the value of it.

77
Example

78
Inheritance
What is Inheritance?
O Inheritance is a process in which one object
acquires all the properties and behaviours of its
parent object automatically.
O We can reuse, extend or modify the attributes
and behaviours which are defined in other class.
O The class which inherits the members of another
class is called child class and the class whose
members are inherited is called parent class.
O Inheritance represents the IS-A relationship, also
known as parent-child relationship.

80
Types of Inheritance

81
Single Inheritance

82
Multilevel Inheritance

83
Hierarchical Inheritance

84
Multiple Inheritance
O To reduce the complexity and simplify the
language, Multiple Inheritance is not supported
in java.
O Consider a scenario where A, B & C are three
classes. The C class inherits A & B classes. If A &
B classes have same method and you call it
from child class object, there will be ambiguity to
call method of A or B class.
O Implemented through Interfaces (discussed
later).
85
Hybrid Inheritance
Combination of more than one inheritance:
O Single + Hierarchical or vice-versa
O Multilevel + Hierarchical or vice-versa

86
Hierarchical + Single Inheritance

87
88
super keyword
O The super keyword in java is a reference
variable which is used to refer immediate
parent class object.
O Whenever an instance of subclass is
created, an instance of parent class is
created implicitly which is referred by super
reference variable.

89
Example

90
Aggregation
O Member of a class is object of another class.
O Represents HAS-A relationship.

class Emp
{
int empno;
String name; //object of String class
double sal;
.....
}

91
Example

92
Polymorphism
Method Overloading
O Overloading refers to the use of the same thing
for different purposes.
O Java supports overloading of methods, i.e., using
the same method name to create methods that
perform a variety of different tasks.
O Using the concept of method overloading, we
can design a family of methods with one method
name by changing the number of arguments &
the data type.
[NOTE: Method Overloading is not possible by
changing the return type of the method only.]

94
Example

95
Method Overriding
O If a sub (child) class has the same method as
declared in the super (parent) class, it is known
as method overriding in java.
O The sub class provides a specific
implementation of the method that is already
provided by its super class.
O Runtime polymorphism.

[NOTE: static method cannot be overridden,


because static method is bound with class
whereas instance method is bound with object.]

96
Example

97
Method Overloading VS
Method Overriding
Method Overloading Method Overriding
Use to increase the Use to provide the specific
readability of the program. implementation of the
method that is already
provided by its super class.
Performed within class. Occurs in two classes that
have IS-A (inheritance)
relationship.
Return type can be same or Return type & parameter
different, but parameter must must be same, i.e., signature
be different. must be same.
Compile time polymorphism. Run time polymorphism.
98
final Keyword
O If a variable is declared as final, the value of
that variable cannot be changed.
O If a method is declared as final, the method
cannot be overriding.
O If a class is declared as final, the class
cannot be inherited.

99
Abstraction

100
Abstract Class
O Class declared with abstract keyword, is known as
abstract class in java.
O Can have constructor, data member, methods
(abstract and non-abstract (method with body)).
O Can’t be instantiate, i.e., can’t create any object.
O If there is any abstract method in a class, that class
must be abstract.
O Class extending any abstract class that have abstract
method, must either provide the implementation of
the method or make this class (child /sub class)
abstract.
O Mustn’t be declared as final.

101
Example
abstract class Bike{
abstract void run(); //no body and abstract
}
class Honda4 extends Bike{
void run(){
System.out.println("running safely..");
}
public static void main(String args[]){
Bike obj = new Honda4(); //dynamic binding
obj.run();
}
}

Output
running safely..

102
Interface
O Like class, interface also have data members & member
methods, but doesn’t have any constructor.
O By default in interface all member methods are public &
abstract, & all member variables are public, static &
final.
O An interface can extend multiple interfaces. Thus, we
can say that using interface multiple inheritance can be
implemented.
O A class can implement one/more than one interfaces.
O A class implementing an interface must have to override
all the abstract methods defined within the interface to
become a concrete class.
O Interface can be declared either as public or as default.

103
Example
interface printable{
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
printable obj = new A6();
obj.print();
}
}

Output
Hello

104
Multiple Inheritance
(using Interface)
interface Printable{
void print();
}
interface Showable{
void print();
}
class TestInterface3 implements Printable, Showable{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
}
}

Output
Hello

105
Interface Inheritance
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){
System.out.println("Hello");
}
public void show(){
System.out.println("Welcome");
}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}

Output
Hello
Welcome
106
Abstract Class VS Interface
Abstract Class Interface
Can have abstract and non-abstract Can have only abstract methods.
methods.
Doesn't support multiple inheritance. Supports multiple inheritance.

Can have final, non-final, static and Has only static and final variables.
non-static variables.
The abstract keyword is used to The interface keyword is used to
declare abstract class. declare interface.
Can extend another Java class and Can extend another Java interface
implement multiple Java interfaces. only.
A Java abstract class can have class Members of a Java interface are public
members like private, protected, etc. by default.

107
Package

108
What is a Package?
O Group of similar types of classes, interfaces
and sub-packages.
O Can be categorized into two forms:
- Built-in package (java, lang, awt, javax,
swing, net, io, util, sql, etc.)
- User-defined package

109
110
Advantages of a Package
O Used to categorize the classes and
interfaces so that they can be easily
maintained.
O Removes naming collision.

111
Example
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

Output
Welcome to package

112
How to access package from
another package?
There are three ways to access the package
from another package:
O import package.*;
O import package.classname;
O fully qualified name

113
Example
(using packagename.*)

[NOTE: If you use package.* then all the classes and interfaces of this
package will be accessible but not subpackages.]

114
Example
(using packagename.classname)

115
Example
(using fully qualified name)

116
String Handling
O The String Class (see at the end)
O String Methods (see at the end)

118
String s = "java5" VS
String s = new String("java5“)

119
Exception Handling
What is an Exception?
O An Exception is a problem that arises during the execution of a
program (e.g., attempt to divide by zero).
O An Exception Handling is a process to handle such runtime errors.
O In Java 5 keywords are used to perform exception handling:-
- try (block, used to enclose the code that might throw an Exception)
- catch (block, used to handle the Exception)
- finally (block, always executed whether Exception is handled or
not)
- throw (used to explicitly throw an Exception)
- throws (used to declare an Exception)

[NOTE: For each try block there can be zero or more catch blocks, but
only one finally block]

121
Hierarchy of Java Exception
classes

122
Types of Exception
• Classes extending Throwable Irrecoverable.
class, except RuntimeException E.g., OutOfMemoryError,
& Error. VirtualMachineError,
• Checked at compile-time.
Exception AssertionError etc.

Checked Unchecked Error


• Classes extending
RuntimeException.
• Checked at run-
time.
123
Example
(try, catch, finally)

124
Exception Propagation
An exception is first thrown from the top of the
stack and if it is not caught, it drops down the
call stack to the previous method, If not
caught there, the exception again drops down
to the previous method, and so on until they
are caught or until they reach the very bottom
of the call stack. This is called Exception
Propagation.

125
Example

126
Diagrammatic Representation

127
Example
(throw)

128
Example
(throws)

129
Throw VS Throws
Throw Throws
Used to explicitly throw an Used to declare an exception.
exception.
Throw is followed by an Throws is followed by class.
instance.
Used within the method. Used with the method
signature.
Multiple exceptions can’t be Multiple exceptions can be
thrown. declared.
public void method()throws
IOException,SQLException

130
Final VS Finally VS Finalize
Final Finally Finalize
Used to apply restrictions on Used to place important Used to perform clean up
class, method and variable. code. It will be executed processing just before object
Final class can't be inherited, whether exception is is garbage collected.
final method can't be handled or not.
overridden and final variable
value can't be changed.
Final is a keyword. Finally is a block. Finalize is a method.

131
Working with Files
What is a File?
O A file is a collection of related data stored in a
particular area on the disk.
O Until now we have been using the standard input
(keyboard) for reading and standard output
(screen) for writing.
- It becomes cumbersome & time consuming to
handle large volumes of data through terminal.
- The entire data is lost when either the program
is terminated or the computer is turned off.
O To overcome the discussed problems the
concept of files is employed in Java
programming.
133
Writing to a File

134
Reading from a File

135
Appending to a File

136
References
O E Balagurusamy, Object Oriented
Programming with C++, 5th Edition,
McGrawHill
O Courtesy of JavaTPoint – Java Tutorial. URL:
https://www.javatpoint.com/java-tutorial
O Herbert Schildt, Java: The Complete
Reference, Seventh Edition, TMGH, 2007
O Courtesy of TutorialsPoint – Java Tutorial.
URL: https://www.tutorialspoint.com/java
137
The String Class
Objectives:

 Learn about literal strings


 Learn about String constructors
 Learn about commonly used
methods
 Understand immutability of strings
 Learn to format numbers into
strings
String class facts
 An object of the String class represents a
string of characters.
 The String class belongs to the java.lang
package, which does not require an import
statement.
 Like other classes, String has constructors
and methods.
 Unlike other classes, String has two
operators, + and += (used for
concatenation).
Literal Strings

 are anonymous objects of the String class


 are defined by enclosing text in double
quotes. ―This is a literal String‖
 don‘t have to be constructed.
 can be assigned to String variables.
 can be passed to methods and constructors
as parameters.
 have methods you can call.
Literal String examples
//assign a literal to a String variable
String name = “Robert”;

//calling a method on a literal String


char firstInitial = “Robert”.charAt(0);

//calling a method on a String variable


char firstInitial = name.charAt(0);
Immutability

 Once created, a string cannot be changed:


none of its methods changes the string.
 Such objects are called immutable.
 Immutable objects are convenient because
several references can point to the same
object safely: there is no danger of changing
an object through one reference without the
others being aware of the change.
Advantages Of Immutability
Uses less memory.
String word1 = "Java"; String word1 = ―Java";
String word2 = word1; String word2 = new String(word1);

word1 word1 ―Java"

―Java" word2 ―Java"


word2
Less efficient:
OK wastes memory
Disadvantages of Immutability
Less efficient — you need to create a new string and
throw away the old one even for small changes.

String word = ―Java";


char ch = Character.toUpperCase(word.charAt (0));
word = ch + word.substring (1);

word ―java"

―Java"
Empty Strings
 An empty String has no characters. It‘s
length is 0.
String word1 = ""; Empty strings
String word2 = new String();

 Not the same as an uninitialized String.


private String errorMsg; errorMsg
is null
No Argument Constructors

 No-argument constructor creates an


empty String. Rarely used.
String empty = new String();
 A more common approach is to
reassign the variable to an empty
literal String. (Often done to reinitialize a variable
used to store input.)

String empty = ―‖;//nothing between quotes


Copy Constructors
 Copy constructor creates a copy of an existing
String. Also rarely used.
 Not the same as an assignment.
Copy Constructor: Each variable points to a different copy of the String.

String word = new String(―Java‖); word ―Java"


String word2 = new String(word); word2 ―Java"
Assignment: Both variables point to the same String.

String word = ―Java‖; word


String word2 = word;
―Java"
word2
Other Constructors

Most other constructors take an array as


a parameter to create a String.
char[] letters = {„J‟, „a‟, „v‟, „a‟};
String word = new String(letters);//”Java”
Methods — length, charAt
int length();  Returns the number of characters in
the string

char charAt(i);  Returns the char at position i.

Character positions in strings are numbered


starting from 0 – just like arrays.
Returns:
‖Problem".length(); 7
‖Window".charAt (2); ‘n'
Methods — substring
Returns a new String by copying characters from an existing String.

 String subs = word.substring (i, k); television


 returns the substring of chars in
positions from i to k-1 i k
 String subs = word.substring (i); television
 returns the substring from the i-th
char to the end i
Returns:
‖television".substring (2,5); ―lev"
―immutable".substring (2); ―mutable"
―bob".substring (9); "" (empty string)
Methods — Concatenation
String word1 = ―re‖, word2 = ―think‖; word3 = ―ing‖;
int num = 2;

 String result = word1 + word2;


//concatenates word1 and word2 ―rethink―

 String result = word1.concat (word2);


//the same as word1 + word2 ―rethink―

 result += word3;
//concatenates word3 to result ―rethinking‖

 result += num; //converts num to String


//and concatenates it to result ―rethinking2‖
Methods — Find (indexOf)
0 2 6 10 15

String name =―President George Washington";


Returns:
date.indexOf (‗P'); 0
date.indexOf (‗e'); 2
date.indexOf (―George"); 10
(starts searching
date.indexOf (‗e', 3); 6
at position 3)

date.indexOf (―Bob"); -1 (not found)


date.lastIndexOf (‗e'); 15
Methods — Equality
boolean b = word1.equals(word2);
returns true if the string word1 is equal to word2
boolean b = word1.equalsIgnoreCase(word2);
returns true if the string word1 matches word2,
case-blind
b = “Raiders”.equals(“Raiders”);//true
b = “Raiders”.equals(“raiders”);//false
b = “Raiders”.equalsIgnoreCase(“raiders”);//true

if(team.equalsIgnoreCase(“raiders”))
System.out.println(“Go You “ + team);
Methods — Comparisons
int diff = word1.compareTo(word2);
returns the ―difference‖ word1 - word2
int diff = word1.compareToIgnoreCase(word2);
returns the ―difference‖ word1 - word2,
case-blind
Usually programmers don‘t care what the numerical ―difference‖ of
word1 - word2 is, just whether the difference is negative (word1
comes before word2), zero (word1 and word2 are equal) or positive
(word1 comes after word2). Often used in conditional statements.

if(word1.compareTo(word2) > 0){


//word1 comes after word2…
}
Comparison Examples
//negative differences
diff = “apple”.compareTo(“berry”);//a before b
diff = “Zebra”.compareTo(“apple”);//Z before a
diff = “dig”.compareTo(“dug”);//i before u
diff = “dig”.compareTo(“digs”);//dig is shorter

//zero differences
diff = “apple”.compareTo(“apple”);//equal
diff = “dig”.compareToIgnoreCase(“DIG”);//equal

//positive differences
diff = “berry”.compareTo(“apple”);//b after a
diff = “apple”.compareTo(“Apple”);//a after A
diff = “BIT”.compareTo(“BIG”);//T after G
diff = “huge”.compareTo(“hug”);//huge is longer
Methods — trim
String word2 = word1.trim ();
returns a new string formed from word1 by
removing white space at both ends
does not affect whites space in the middle
String word1 = ― Hi Bob ―;
String word2 = word1.trim();
//word2 is ―Hi Bob‖ – no spaces on either end
//word1 is still ― Hi Bob ― – with spaces
Methods — replace
String word2 = word1.replace(oldCh, newCh);
returns a new string formed from word1 by
replacing all occurrences of oldCh with newCh

String word1 = ―rare―;


String word2 = ―rare―.replace(‗r‘, ‗d‘);
//word2 is ―dade‖, but word1 is still ―rare―
Methods — Changing Case
String word2 = word1.toUpperCase();
String word3 = word1.toLowerCase();
returns a new string formed from word1 by
converting its characters to upper (lower) case

String word1 = ―HeLLo―;


String word2 = word1.toUpperCase();//‖HELLO‖
String word3 = word1.toLowerCase();//‖hello‖
//word1 is still ―HeLLo―
Replacements
 Example: to ―convert‖ word1 to upper case, replace
the reference with a new reference.
word1 = word1.toUpperCase();

 A common bug:
word1
word1.toUpperCase();
remains
unchanged
Numbers to Strings
Three ways to convert a number into a string:
1. String s = "" + num; Integer and Double
s = ―‖ + 123;//‖123‖ are ―wrapper‖ classes
2. String s = Integer.toString (i); from java.lang that
represent numbers as
String s = Double.toString (d); objects. They also
s = Integer.toString(123);//‖123‖ provide useful static
s = Double.toString(3.14); //‖3.14‖ methods.

3. String s = String.valueOf (num);


s = String.valueOf(123);//‖123‖
char charAt(int index)
Returns the character at the specified index.

int compareTo(Object o)
Compares this String to another Object.

int compareTo(String anotherString)


Compares two strings lexicographically.

Int compareToIgnoreCase(String str)


Compares two strings lexicographically,
ignoring case differences.

String concat(String str)


Concatenates the specified string to the end of
this string.

boolean endsWith(String suffix)


Tests if this string ends with the specified
suffix.

boolean equals(String str)


Compares this string to the specified object.

boolean
equalsIgnoreCase(String anotherStri
ng)
Compares this String to another String,
ignoring case considerations.

int indexOf(int ch)


Returns the index within this string of the first
occurrence of the specified character.

int lastIndexOf(int ch)


Returns the index within this string of the last
occurrence of the specified character.

int length()
Returns the length of this string.

String replace(char oldChar,


char newChar)
Returns a new string resulting from replacing
all occurrences of oldChar in this string with
newChar.

String replaceAll(String regex,


String replacement)
Replaces each substring of this string that
matches the given regular expression with the given
replacement.
boolean startsWith(String prefix)
Tests if this string starts with the specified
prefix.

String substring(int beginIndex)


Returns a new string that is a substring of this
string.

String substring(int beginIndex,


int endIndex)
Returns a new string that is a substring of this
string.
String toLowerCase()
Converts all of the characters in this String
to lower case using the rules of the default locale.

String toUpperCase()
Converts all of the characters in this String
to upper case using the rules of the default locale.

String trim()
Returns a copy of the string, with leading and
trailing whitespace omitted.

You might also like