2. Outlines
• Introduction
• Why Java?
• Where it is used?
• Characteristics of Java
• Java Platform Editions
• Evolution of Java
• Understanding JDK, JRE and JVM
• How Java is platform-independent
• Evaluating Java libraries, middle-ware, and database
options
[Expected Time: 3 Hours]
3. Introduction
Java is a Programming language and a Platform.
Java is a high level, robust, secured and object-oriented
programming language.
Developed by Sun Microsystems (James Gosling).
Platform: Any hardware or software environment in
which a program runs, is known as a platform.
4. Why Java?
Java is the Internet Programming Language.
Java enables users to develop and deploy applications
on the Internet for servers, desktop computers, and
small hand-held devices.
5. Where it is Used?
According to Sun, 3 billion devices run java.
• Desktop Applications such as acrobat reader, media player,
antivirus etc.
• Web Applications such as irctc.co.in, javatpoint.com etc.
• Enterprise Applications such as banking applications.
• Mobile Applications
• Embedded System, Smart Card, Robotics, Games etc.
6. Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
7. Java Platform Editions
• A Java Platform is the set of APIs, class libraries, and
other programs used in developing Java programs for
specific applications.
8. There are 3 Java Platform Editions:
1. Java 2 Platform, Standard Edition (J2SE)
• Core Java Platform targeting applications running on
workstations
2. Java 2 Platform, Enterprise Edition (J2EE)
• Component-based approach to developing distributed,
multi-tier enterprise applications
3. Java 2 Platform, Micro Edition (J2ME)
• Targeted at small, stand-alone or connectable
consumer and embedded devices
9. Origin of Java
James Gosling & Patrick Naughton at 1990
Goal : To develop distributed system which is
applicable to electronic products(platform
independent)
10. James Gosling
• James Gosling is generally
credited as the inventor of the
Java programming language
• He was the first designer of
Java and implemented its
original compiler and virtual
machine
• He is also known as the
Father of Java.
11. Brief History of Java
• In 1990, Sun Microsystems began an internal project known as
the Green Project to work on a new technology.
• In 1992, the Green Project was spun off and its interest directed
toward building highly interactive devices for the cable TV
industry. This failed to materialize.
• In 1994, the focus of the original team was re-targeted, this time
to the use of Internet technology. A small web browser called
HotJava was written.
• Oak was renamed to Java after learning that Oak had already
been trademarked.
12. • In 1995, Java was first publicly released.
• In 1996, Java Development Kit (JDK) 1.0 was released.
• In 2002, JDK 1.4 (codename Merlin) was released, the most
widely used version.
• In 2004, JDK 5.0 (codename Tiger) was released.
• The latest version of java is jdk 8.0.
14. 1. Simple: According to Sun, Java language is
simple because syntax is based on C++ and
there is Automatic Garbage Collection in java.
2. Object-oriented: We organize our software as
a combination of different types of objects that
incorporates both data and behaviour.
• Basic concepts of OOPs are:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
15. 3. Platform Independent:
• A platform is the hardware or software environment in which a
program runs.
• There are two types of platforms software-based and hardware-
based. Java provides software-based platform.
• The Java platform differs from most other platforms in the sense
that it is a software-based platform that runs on the top of other
hardware-based platforms. It has two components:
• Runtime Environment
• API(Application Programming Interface)
• Java code can be run on multiple platforms e.g. Windows, Linux,
Sun Solaris, Mac/OS etc. Java code is compiled by the compiler and
converted into bytecode. This bytecode is a platform-independent
code because it can be run on multiple platforms i.e. Write Once
and Run Anywhere(WORA).
16.
17. 4. Secured: Java is secured because:
• No explicit pointer
• Java Programs run inside virtual machine sandbox
• Classloader: adds security by separating the package for the
classes of the local file system from those that are imported from
network sources.
• Bytecode Verifier: checks the code fragments for illegal code that
can violate access right to objects.
• Security Manager: determines what resources a class can access
such as reading and writing to the local disk.
18. 5. Robust: Robust simply means strong. Java uses strong
memory management. There is automatic garbage
collection in java. There is exception handling and type
checking mechanism in java. All these points makes java
robust.
6. Architecture-neutral: There is no implementation
dependent features e.g. size of primitive types is fixed.
• In C programming, int data type occupies 2 bytes of
memory for 32-bit architecture and 4 bytes of memory
for 64-bit architecture. But in java, it occupies 4 bytes of
memory for both 32 and 64 bit architectures.
19. 7. Portable: We may carry the java bytecode to
any platform.
8. High-performance: Java is faster than
traditional interpretation since byte code is
"close" to native code still somewhat slower
than a compiled language (e.g., C++)
9. Distributed: We can create distributed
applications in java. RMI and EJB are used for
creating distributed applications. We may
access files by calling the methods from any
machine on the internet.
20. 10. Multi-Threaded: A thread is like a separate
program, executing concurrently.
• We can write Java programs that deal with
many tasks at once by defining multiple
threads.
• The main advantage of multi-threading is that
it doesn't occupy memory for each thread. It
shares a common memory area.
• Threads are important for multi-media, Web
applications etc.
25. Understanding JDK & JRE
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JDK
JDK is an acronym for Java Development Kit.
It physically exists. It contains JRE and development tools.
JRE
JRE is an acronym for Java Runtime Environment.
It is the implementation of JVM and used to provide runtime
environment.
It contains set of libraries and other files that JVM uses at
runtime.
26. Understanding JVM
JVM (Java Virtual Machine) is an abstract machine.
It is a specification that provides runtime environment in
which java byte code can be executed.
JVMs are available for many hardware and software
platforms.
The JVM performs following main tasks:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
30. How Java is Platform-independent?
The source code (program) written in java is saved as a
file with .java extension.
The java compiler “javac” compiles the source code and
produces the platform independent intermediate code
called BYTE CODE. It is a highly optimized set of
instructions designed to be executed by the JVM.
31. How Java is Platform-independent?
The byte code is not native to any platform because java
compiler doesn’t interact with the local platform while
generating byte code.
It means that the Byte code generated on Windows is
same as the byte code generated on Linux for the same
java code.
The Byte code generated by the compiler would be saved
as a file with .class extension. As it is not generated for
any platform, can’t be directly executed on any CPU.
32. Portability Vs Platform Independence
Portability focuses on adaptation of software in various
OS, by recompiling the source to make the binary
compatible with the target OS and not necessarily
modifying the source.
Platform independence focuses on ability of software to
run on VIRTUAL hardware that in turn interfaces with
the PHYSICAL hardware.
Examples of cross-platform or platform independent
languages are Python, JavaScript, Java etc.
34. Java Libraries, Middle-ware,
and Database options
java.lang
Provides classes that are fundamental to the design of the Java programming
language.
Following are the Important Classes in java.lang package:
Boolean: The Boolean class wraps a value of the primitive type boolean in an
object.
Byte: The Byte class wraps a value of primitive type byte in an object.
ClassLoader: A class loader is an object that is responsible for loading classes.
Integer: The Integer class wraps a value of the primitive type int in an object.
Object: Class Object is the root of the class hierarchy.
String: The String class represents character strings.
Thread: A thread is a thread of execution in a program.
Math: The class Math contains methods for performing basic numeric operations
such as the elementary exponential, logarithm, square root, and trigonometric
functions.
35. Java Libraries, Middle-ware,
and Database options
java.util
It contains the collections framework, legacy collection classes, event model, date
and time facilities, internationalization, and miscellaneous utility classes (a string
tokenizer, a random-number generator, and a bit array).
Following are the Important Classes in Java.util package :
AbstractCollection: This class provides a skeletal implementation of the Collection
interface, to minimize the effort required to implement this interface.
AbstractQueue: This class provides skeletal implementations of some Queue
operations.
Currency: Represents a currency.
Date: The class Date represents a specific instant in time, with millisecond
precision.
36. Java Libraries, Middle-ware,
and Database options
java.sql
This package include classes and interface to perform almost all JDBC operation
such as creating and executing SQL Queries.
Following are the Important Classes in java.sql package :
java.sql.Connection: creates a connection with specific database
java.sql.CallableStatement: Execute stored procedures
java.sql.Date: Provide support for Date SQL type.
java.sql.Driver: create an instance of a driver with the DriverManager.
java.sql.DriverManager: This class manages database drivers.
37. Java Libraries, Middle-ware,
and Database options
java.io
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
Following are the Important Classes in java.io package :
OutputStream
Java application uses an output stream to write data to a destination, it may be a file,
an array, peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source, it may be a file, an
array, peripheral device or socket.
System.out: standard output stream
System.in: standard input stream
System.err: standard error stream
38. Java Libraries, Middle-ware,
and Database options
java.nio
Java has provided a second I/O system called NIO (New I/O).
Java NIO provides the different way of working with I/O than the standard
I/O API's.
It is an alternate I/O API for Java (from Java 1.4).It supports a buffer-
oriented, channel based approach for I/O operations.
With the introduction of JDK 7, the NIO system is expanded, providing the
enhanced support for file system features and file-handling.
Due to the capabilities supported by the NIO file classes, NIO is widely used
in file handling.
39. Java Libraries, Middle-ware,
and Database options
java.awt
JavaAWT (Abstract Window Toolkit) is an API to develop GUI or window-based
applications in java.
Java AWT components are platform-dependent i.e. components are displayed according
to the view of operating system. AWT is heavyweight i.e. its components are using the
resources of OS.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
.
40. Java Libraries, Middle-ware,
and Database options
java.swing
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
.
43. Variables
Variables are the data members or the fields defined
inside a class.
There are three types of variables:
Local Variables
Instance Variables
Class Variables
44. Local Variables
Local variables are those data members which are
declared in methods, constructors, or blocks.
They are created only when the method, constructor or
block is executed and destroyed as soon as the
execution of that block is completed.
So the visibility of local variables is inside the block
only, they can’t be accessed outside the scope of that
block.
45. Important
Access modifiers are NOT ALLOWED with local
variables.
Local variables are created in STACK.
Default value is NOT ASSIGNED to the local variables
in Java.
46. Instance Variables
• Variables which are declared in a class, but outside a
method, constructor or any block are known as instance
variables.
• They are created inside the object in heap.
• Each object has its own set of instance variables and
they can be accessed/modified separately using object
reference.
47. • Instance variables are created when an object is created
with the use of the 'new' keyword and destroyed when the
object is destroyed.
• Access modifiers can be used with instance variables.
• Instance variables have default values (Initialization is not
mandatory, JVM will take the default value)
• For numbers the default value is 0,
• for Booleans it is false
• and for object references it is NULL.
48. Class (Static) Variables
Class variables are also known as static variables.
Variable which are declared in a class, but outside a method,
constructor or a block and qualified with ‘static’ keyword are known
as class variables.
Used when we don’t want to modify the value from object to object.
Only one copy of each class variable is created, regardless of how
many objects are created from it.
Static variables can be accessed by calling with the class name.
ClassName.VariableName
49. Static variables are created with the start of execution of a
program and destroyed when the program terminates.
Default values are same as instance variables.
A public static final variable behaves as a CONSTANT in
Java.
Static variables can be initialized using static block also.
51. Variable Initialization
Local variables must be initialized explicitly by the
programmer as the default values are not assigned to them
where as the instance variables and static variables are
assigned default values if they are not assigned values at the
time of declaration.
52. Brainstorming 1
What will be the output of the following Program?
class VariableDemo
{
public static void main(String [] rk)
{
int x = 10;//if used without initialization will give error(int x)
System.out.print(x);
}
}
53. Brainstorming 2
What will be the output of the following Program?
class VariableDemo
{
static int x;
public static void main(String [] rk)
{
System.out.print(x);
}
}
54. Variable Using Object
class VariableDemo
{
int x=100;
public static void main(String [] rk)
{
VariableDemo v1=new VariableDemo();
System.out.print(v1.x);
}
}
55. Brainstorming 3
What will be the output of the following Program?
class VariableDemo
{
static int x;
public static void main(String [] rk)
{
System.out.print(VariableDemo.x);
//OR System.out.print(x);
}
}
56. Data Types
• Data types represent the different values to be
stored in the variable.
• In Java, there are two types of data types:
1. Primitive data types
2. Non-primitive data types
57.
58. All the letters of an identifier in Java should be in lower case
Except:
Class Names: First letter of each word in the identifier should be
capitalized.
Method Names: First letter of each word in the identifier should be
capitalized except the first word.
Naming Conventions
59. Identifiers
A name in a program is called an identifier.
Identifiers can be used to denote classes, methods, variables,
and labels.
An identifier may be any descriptive sequence of uppercase
and lowercase letters, numbers, or the underscore and
dollar-sign characters.
Example: number, Number, sum_$, bingo, $$_100
Note: Identifiers must not begin with a number.
60. Keywords
Keywords are reserved identifiers that are predefined in the
language.
Cannot be used as names for a variable, class, or method.
All the keywords are in lowercase.
There are 50 keywords currently defined in the Java language.
The keywords const and goto are reserved but not used.
true, false, and null are also reserved.
61. Java Keywords
abstract char else goto long return throw
assert class enum if native short throws
boolean const extends implements new static this
break continue final import package strictfp transient
byte default finally instanceof private super void
case do float int protected switch try
catch double for interface public synchronize
d
while and
volatile
62. Writing Your First Java Program
• class MyJavaProgram
• {
• public static void main(String args[])
{
System.out.println(“Have fun in Java…”);
}
• }
63. Compiling and Executing Java Program
Step-1: Save your file with (.java) extension
• Example: Program1.java
NOTE: If the class is public then the file name MUST BE same as
the name of the class.
Step-2: Compile your .java file using javac compiler from the
location where the file is saved
javac Program1.java
64. Compiling and Executing Java Program
Step-3: Execute your java class which contains the following
method: public static void main(String args[]) {}
java MyJavaProgram
65. Access Specifiers
Specifier Sub class
(Same
Package)
Non-Sub class
(Same
Package)
Sub class
(Different
Package)
Non-Sub class
(Different
Package)
public Yes Yes Yes Yes
protected Yes Yes Yes No
default Yes Yes No No
private No No No No
66. Important Points
A user defined outer class can be either public or default. We can
not define a private or protected class.
One file can have multiple classes/interfaces but out of them
only one can be public.
67. Named Constants
A named constant is an identifier that represents a
permanent value.
• Syntax is:
• final datatype CONSTANTNAME = value;
• The word final is a Java keyword for declaring a
constant.
70. Introduction
Operators are special symbols that perform specific
operations on one, two, or three operands, and then
return a result.
71. Assignment Operator
One of the most common operators is the simple
assignment operator "=".
This operator assigns the value on its right to the
operand on its left.
Example:
int salary = 25000; double speed = 20.5;
This operator can also be used on objects to assign
object references.
Student s = new Student();
Student s2 = s;
72. • The syntax for assignment statements
• is as follows:
•variable = expression
• int y = 1; // Assign 1 to variable y
• double radius = 1.0; // Assign 1.0 to variable radius
• int x = 5 * (3 / 2); // Assign the value of the
expression to x
• x = y + 1; // Assign the addition of y and
1 to x
73. The following statement is correct:
• System.out.println(x = 1);
• which is equivalent to
• x = 1;
• System.out.println(x);
If a value is assigned to multiple variables, you can use
this syntax:
• i = j = k = 1;
• which is equivalent to
• k = 1;
• j = k;
• i = j;
74. • In an assignment statement, the data type of
the variable on the left must be compatible
with the data type of the value on the right.
• For example, int x = 1.0 would be illegal.
• We cannot assign a double value (1.0) to
• an int variable without using type casting.
75. Arithmetic Operators
Java provides operators that perform addition, subtraction,
multiplication, and division.
Operator Description
+
Additive operator (also used for String
concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
76. Compound Assignments
Arithmetic operators are combined with the simple
assignment operator to create compound assignments.
Compound assignment operators are +=, -=, *=, /+,
%=
For example, x+=1; and x=x+1; both increment the
value of x by 1.
77. Relational Operators
Relational operators determine if one operand is
greater than, less than, equal to, or not equal to
another operand.
It always returns boolean value i.e true or false.
79. Type Comparison Operators
The instanceof operator is used to compare an object
to a specified type i.e. class or interface.
It can be used to test if an object is an instance of a
class or subclass, or an instance of a class that
implements a particular interface.
80. Example
class Parent{}
class Child extends Parent{}
class TestInstanceOf {
public static void main(String [] rk){
Parent p = new Parent();
Child c = new Child();
System.out.println(p instanceof Child);
System.out.println(p instanceof Parent);
System.out.println(c instanceof Parent); }
}
81. Unary Operators
The unary operators require only one operand.
Operator Description
+ Unary plus operator; indicates positive value
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
!
Logical complement operator; inverts the value of a
boolean
82. Boolean Logical Operators
The Boolean logical operators shown here operate only
on boolean operands.
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
== Equal to
!= Not equal to
?: Ternary if-then-else
83. • The following table shows the effect of each logical
operation:
A B A | B A & B A ^ B ~ A
False False False False False True
True False True False True False
False True True False True True
True True True True False False
84. Bitwise Logical NOT
• Also called the bitwise complement, the unary
NOT operator, ~, inverts all of the bits of its
operand. For example, the number 42, which
has the following bit pattern:
00101010 becomes
11010101
after the NOT operator is applied.
85. Bitwise Logical AND
• The AND operator, &, produces a 1 bit if both
operands are also 1. A zero is produced in all
other cases. Here is an example:
00101010 42
&
00001111 15
=
00001010 10
86. Bitwise Logical OR
• The OR operator, |, combines bits such that if
either of the bits in the operands is a 1, then
the resultant bit is a 1, as shown here:
00101010 42
|
00001111 15
=
00101111 47
87. Bitwise Logical XOR
• The XOR operator, ^, combines bits such that if exactly one
operand is 1, then the result is 1. Otherwise, the result is
zero. The following example shows the effect of the ^.
• Notice how the bit pattern of 42 is inverted wherever the
second operand has a 1 bit. Wherever the second operand
has a 0 bit, the first operand is unchanged. You will find this
property useful when performing some types of bit
manipulations.
00101010 42
^
00001111 15
=
00100101 37
88. Short-Circuit Logical Operators
• These are secondary versions of the Boolean AND and OR
operators, and are known as short-circuit logical operators.
• OR operator results in true when A is true , no matter what
B is. Similarly, AND operator results in false when A is
false, no matter what B is.
• If we use the || and && forms, rather than the | and & forms
of these operators, Java will not bother to evaluate the right-
hand operand when the outcome of the expression can be
determined by the left operand alone.
89. This is very useful when the right-hand operand depends
on the value of the left one in order to function properly.
For example
if (denom != 0 && num / denom > 10)
The above code fragment shows how you can take
advantage of short-circuit logical evaluation to be sure
that a division operation will be valid before evaluating it.
90. The ? Operator
• Java includes a special ternary (three-way)operator, ?, that can
replace certain types of if-then-else statements.
• The ? has this general form:
expression1 ? expression2 : expression3
• Here,expression1 can be any expression that evaluates to a
boolean value.
• If expression1 is true , then expression2 is evaluated; otherwise,
expression3 is evaluated.
• Both expression2 and expression3 are required to return the same
type, which can’t be void.
91. int ratio = denom == 0 ? 0 : num / denom ;
• When Java evaluates this assignment expression, it first looks at
the expression to the left of the question mark.
• If denom equals zero, then the expression between the question
mark and the colon is evaluated and used as the value of the
entire ? expression.
• If denom does not equal zero, then the expression after the colon
is evaluated and used for the value of the entire ? expression.
• The result produced by the? operator is then assigned to ratio.
92. Bitwise Operators
These operators act upon the individual bits of their
operands.
Can be applied to the integer types, long, int, short, char,
and byte.
93. Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
95. The Left Shift Operator
• The left shift operator,<<, shifts all of the bits in a value to
the left a specified number of times.
value << num
• Example:
01000001 65 << 2
00000100 4
96. The Right Shift Operator
• The right shift operator, >>, shifts all of the bits in a value
to the right a specified number of times.
value >> num
• It is also known as signed right shift.
• Example:
00100011 35 >> 2
00001000 8
97. • When we are shifting right, the top (leftmost) bits exposed
by the right shift are filled in with the previous contents of
the top bit.
• This is called sign extension and serves to preserve the
sign of negative numbers when you shift them right.
98. The Unsigned Right Shift
• In these cases, to shift a zero into the high-order bit no
matter what its initial value was. This is known as an
unsigned shift.
• To accomplish this, we will use Java’s unsigned, shift-right
operator, >>>, which always shifts zeros into the high-order
bit.
• Example:
– 11111111 11111111 11111111 11111111 –1 in
binary as an int
– >>>24
– 00000000 00000000 00000000 11111111 255 in
binary as an int
100. Brainstorming 1
What will be the output of the following code snippets?
byte b = 30; System.out.println(~b);
byte b = -53; System.out.println(~b);
System.out.println(34<<3);
System.out.println(-34>>3);
System.out.println(-34>>>3);
101. Brainstorming 2
int x = 10, y = 5;
while(x- - > 7 || + + y < 8 )
System.out.print(x);
System.out.print(y);
A. 95
B. 67
C. 78
D. 48
E. 77
F. N.O.T
102. Brainstorming 3
System.out.print(2>1||4>3?false:true);
class X{}
class Y extends X{}
class Z extends Y{}
X x1 = new Y();
Y y1 = new Z();
Y y2 = new Y();
System.out.println( x1 instanceof X);
System.out.println( x1 instanceof Z);
System.out.println( y1 instanceof Z);
System.out.println( y2 instanceof X);
104. 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:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch); is same as:
String s="javatpoint";
105. Introduction
Every string we create is actually an object of type String.
String constants are actually String objects.
Example:
System.out.println("This is a String, too");
Objects of type String are immutable i.e. once a String object
is created, its contents cannot be altered.
String
Constant
106. Why String is Immutable or Final?
String has been widely used as parameter for many java classes e.g.
for opening network connection we can pass hostname and port
number as string ,
we can pass database URL as string for opening database
connection,
we can open any file in Java by passing name of file as argument to
File I/O classes.
In case if String is not immutable , this would lead serious security
threat, means some one can access to any file for which he has
authorization and then can change the file name either deliberately
or accidentally and gain access of those file.
107. String Class
• The java.lang.String class implements Serializable, Comparable and
CharSequence interfaces.
108. CharSequence Interface
• The CharSequence interface is used to represent sequence of
characters. It is implemented by String, StringBuffer and
StringBuilder classes. It means, we can create string in java by
using these 3 classes.
109. • The java String is immutable i.e. it cannot be changed. Whenever
we change any string, a new instance is created. For mutable string,
you can use StringBuffer and StringBuilder classes.
110. Introduction
In java, 4 predefined classes are provided that either represent
strings or provide functionality to manipulate them. Those
classes are:
◦ String
◦ StringBuffer
◦ StringBuilder
◦ StringTokenizer
String, StringBuffer, and StringBuilder classes are
defined in java.lang package and all are final.
All of them implement the CharSequence interface.
111. Important
• String Objects are IMMUTABLE.
• StringBuffer is MUTABLE and SYNCHRONIZED.
• StringBuilder is MUTABLE and NON-SYNCHRONIZED.
112. How to create String object?
• There are two ways to create String object:
1. By string literal
2. By new keyword
113. 1) String Literal
• Java String literal is created by using double quotes. For
Example:
String s="welcome";
• Each time you create a string literal, the JVM checks the
string constant pool first. If the string already exists in the
pool, a reference to the pooled instance is returned. If
string doesn't exist in the pool, a new string instance is
created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";
//will not create new instance
114. • Note: String objects are stored in a special memory area
known as string constant pool.
115. 2) By new keyword
String s=new String("Welcome");
• In such case, JVM will create a new string object in
normal(non pool) heap memory and the literal
"Welcome" will be placed in the string constant pool. The
variable s will refer to the object in heap(non pool).
116. Java String Example
public class StringExample
{
public static void main(String args[])
{
String s1="java";
//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);
//converting char array to string
String s3=new String("example");
//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}