SlideShare une entreprise Scribd logo
1  sur  138
Introduction: Feature of Java, Java
Virtual Machine, Byte Code, JDK, JRE,
Comments, Java coding convention
What is Java?
1. Java is a programming language and a platform. Java is a high level,
robust, object-oriented and secure programming language.
2. Java was developed by Sun Microsystems (which is now the
subsidiary of Oracle) in the year 1995. James Gosling is known as
the father of Java. Before Java, its name was Oak. Since Oak was
already a registered company, so James Gosling and his team
changed the name from Oak to Java.
3. Platform: Any hardware or software environment in which a
program runs, is known as a platform. Since Java has a runtime
environment (JRE) and API, it is called a platform.
Application
According to Sun, 3 billion devices run Java. There are many devices where Java
is currently used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus, etc.
2. Web Applications such as irctc.co.in etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
Java
• The principles for creating Java programming were "Simple, Robust,
Portable, Platform-independent, Secured, High Performance,
Multithreaded, Architecture Neutral, Object-Oriented, Interpreted,
and Dynamic". Java was developed by James Gosling, who is
known as the father of Java, in 1995. James Gosling and his team
members started the project in the early '90s.
• Currently, Java is used in internet programming, mobile devices,
games, e-business solutions, etc. Following are given significant
points that describe the history of Java
• 1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called
Green Team.
• 2) Initially it was designed for small, embedded systems in electronic
appliances like set-top boxes.
• 3) Firstly, it was called "Greentalk" by James Gosling, and the file
extension was .gt.
• 4) After that, it was called Oak and was developed as a part of the
Green project.
• 7) Why had they chosen the name Java for Java language? The
team gathered to choose a new name. The suggested words were
"dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted
something that reflected the essence of the technology:
revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun
to say.
• According to James Gosling, "Java was one of the top choices along
with Silk". Since Java was so unique, most of the team members
preferred Java than other names.
• 8) Java is an island in Indonesia where the first coffee was produced
(called Java coffee). It is a kind of espresso bean. Java name was
chosen by James Gosling while having a cup of coffee nearby his
office.
• 9) Notice that Java is just a name, not an acronym.
• 10) Initially developed by James Gosling at Sun Microsystems (which is now a
subsidiary of Oracle Corporation) and released in 1995.
• 11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
• 12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there
have been many additional features added to the language. Now Java is being
used in Windows applications, Web applications, enterprise applications, mobile
applications, cards, etc. Each new version adds new features in Java.
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan 1996)
3. JDK 1.1 (19th Feb 1997)
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
6. J2SE 1.4 (6th Feb 2002)
7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
1. Java SE 8 (18th Mar 2014)
2. Java SE 9 (21st Sep 2017)
3. Java SE 10 (20th Mar 2018)
4. Java SE 11 (September 2018)
5. Java SE 12 (March 2019)
6. Java SE 13 (September 2019)
7. Java SE 14 (Mar 2020)
8. Java SE 15 (September 2020)
9. Java SE 16 (Mar 2021)
10. Java SE 17 (September 2021)
11. Java SE 18 (to be released by March
2022)
Features of Java
• The primary objective of Java
programming language creation
was to make it portable, simple
and secure programming language.
Apart from this, there are also
some excellent features which play
an important role in the popularity
of this language. The features of
Java are also known as Java
buzzwords.
• A list of the most important
features of the Java language is
given below.
• Simple
• Object-Oriented
• Portable
• Platform independent
• Secured
• Robust
• Architecture neutral
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic
Simple
1. Java is very easy to learn, and its syntax is simple, clean and easy to
understand. According to Sun Microsystem, Java language is a
simple programming language because:
2. Java syntax is based on C++ (so easier for programmers to learn it
after C++).
3. Java has removed many complicated and rarely-used features, for
example, explicit pointers, operator overloading, etc.
4. There is no need to remove unreferenced objects because there is
an Automatic Garbage Collection in Java.
Object-oriented
• Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different
types of objects that incorporate both data and behavior
• Object-oriented programming (OOPs) is a methodology that simplifies
software development and maintenance by providing some rules.
Basic concepts of OOPs are:
1.Object
2.Class
3.Inheritance
4.Polymorphism
5.Abstraction
6.Encapsulation
Platform Independent
1. Java is platform independent because it is different from other languages like C,
C++, etc. which are compiled into platform specific machines while Java is a write
once, run anywhere language. A platform is the hardware or software
environment in which a program runs.
2. There are two types of platforms software-based and hardware-based. Java
provides a software-based platform.
3. The Java platform differs from most other platforms in the sense that it is a
software-based platform that runs on top of other hardware-based platforms. It
has two components:
4. Runtime Environment
5. API(Application Programming Interface)
6. Java code can be executed on multiple platforms, for example, 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).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
1. No explicit pointer
2. Java Programs run inside a virtual machine sandbox
Classloader:
Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to load Java
classes into the Java Virtual Machine dynamically. It adds security by separating the package
for the classes of the local file system from those that are imported from network sources.
1. Bytecode Verifier: It checks the code fragments for illegal code that can violate access
rights to objects.
2. Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.
3. Java language provides these securities by default. Some security can also be provided
by an application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
The English meaning of Robust is strong. Java is robust because:
1. It uses strong memory management.
2. There is a lack of pointers that avoids security problems.
3. Java provides automatic garbage collection which runs on the Java
Virtual Machine to get rid of objects which are not being used by a
Java application anymore.
4. There are exception handling and the type checking mechanism in
Java. All these points make Java robust.
Architecture-neutral
• Java is architecture neutral because there are no implementation
dependent features, for example, the 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.
However, it occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.
Portable
• Java is portable because it facilitates you to carry the Java bytecode to
any platform. It doesn't require any implementation.
High-performance
• Java is faster than other traditional interpreted programming
languages because Java bytecode is "close" to native code. It is
still a little bit slower than a compiled language (e.g., C++). Java
is an interpreted language that is why it is slower than compiled
languages, e.g., C, C++, etc.
• Distributed
• Java is distributed because it facilitates users to create distributed applications in Java. RMI and
EJB are used for creating distributed applications. This feature of Java makes us able to access
files by calling the methods from any machine on the internet.
• 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.
• Dynamic
• Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
• Java supports dynamic compilation and automatic memory management (garbage
collection).
Java Arrays
• Normally, an array is a collection of similar type of elements
which has contiguous memory location.
• Java array is an object which contains elements of a similar
data type. Additionally, The elements of an array are stored in a
contiguous memory location. It is a data structure where we
store similar elements. We can store only a fixed set of
elements in a Java array.
• Array in Java is index-based, the first element of the array is
stored at the 0th index, 2nd element is stored on 1st index and
so on.
• In Java, array is an object of a dynamically generated class. Java
array inherits the Object class, and implements the Serializable as
well as Cloneable interfaces. We can store primitive values or
objects in an array in Java. Like C/C++, we can also create single
dimensional or multidimensional arrays in Java.
• Moreover, Java provides the feature of anonymous arrays which is
not available in C/C++.
Advantages
• Code Optimization: It makes the code optimized, we can retrieve
or sort the data efficiently.
• Random access: We can get any data located at an index
position.
Disadvantages
• Size Limit: We can store only the fixed size of elements in the
array. It doesn't grow its size at runtime. To solve this problem,
collection framework is used in Java which grows automatically.
Types of Array in java
There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array
Single Dimensional Array in Java
Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
Example of Java Array
we are going to declare, instantiate, initialize and traverse an array
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together
by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
For-each Loop for Java Array
We can also print the Java array using for-each loop. The Java for-each loop prints the
array elements one by one. It holds an array element in a variable, then executes the
body of the loop. The syntax of the for-each loop is given below:
for(data_type variable:array){
//body of the loop
}
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}
Passing Array to a
Method in Java
//Java Program to demonstrate the way of passing an array
//to method.
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}
We can pass the java array to method so that
we can reuse the same logic on any array.
Let's see the simple example to get the
minimum number of an array using a
method.
Output:
3
//Java Program to return an array from the m
ethod
class TestReturnArray{
//creating method which returns an array
static int[] get(){
return new int[]{10,30,50,90,60};
}
public static void main(String args[]){
//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}}
Returning Array from the Method
We can also return an array from the method
in Java.
Output:
10
30
50
90
60
Multidimensional Array in Java
In such case, data is stored in row and
column-based index (also known as
matrix form). Syntax to Declare
Multidimensional Array in Java
Example to instantiate Multidimensional Array
in Java
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in Java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example of
Multidimensional Java
Array. declare,
instantiate, initialize
and print the
2Dimensional array.
//Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Addition of 2
Matrices in
Java
//Java Program to demonstrate the addition of two matrices in Java
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}
multiply two
matrices of
3 rows and
3 columns
//Java Program to multiply two matrices
public class MatrixMultiplicationExample{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
//creating another matrix to store the multiplication of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns
//multiplying and printing multiplication of 2 matrices
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}}
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:
• char[] ch={'j','a','v','a','p','o','i','n','t'};
• String s=new String(ch);
• is same as:
• String s="java";
• Java String class provides a lot of
methods to perform operations on
strings such as compare(), concat(),
equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.
• The java.lang.String class
implements Serializable, Comparable a
nd CharSequence interfaces.
CharSequence Interface
• The CharSequence interface is used to represent the
sequence of characters.
String, StringBuffer and StringBuilder classes implement
it. It means, we can create strings in Java by using these
three classes.
• The Java String is immutable which means it cannot be
changed. Whenever we change any string, a new
instance is created. For mutable strings, you can use
StringBuffer and StringBuilder classes.
• We will discuss immutable string later. Let's first
understand what String in Java is and how to create the
String object.
What is String in
Java?
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
the 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";//It doe
sn't create a new instance
Generally, String is a sequence of
characters. But in Java, string is an
object that represents a sequence of
characters. The java.lang.String class is
used to create a string object.
There are two ways to create String
object:
1.By string literal
2.By new keyword
• only one object will be created.
Firstly, JVM will not find any string
object with the value "Welcome"
in string constant pool that is why
it will create a new object. After
that it will find the string with the
value "Welcome" in the pool, it
will not create a new object but
will return the reference to the
same instance.
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
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 a heap (non-pool).
Why Java uses the concept of String
literal?
To make Java more memory efficient
(because no new objects are created if it
exists already in the string constant pool).
Java String Example
StringExample.java
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by Java s
tring 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");//creatin
g Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Output:
java
strings
Example
The above code, converts a char array
into a String object. And displays the
String objects s1, s2, and s3 on console
using println() method.
Java String class methods
The java.lang.String class provides many useful methods to perform operations on
sequence of char values.
No. Method Description
1 char charAt(int index) It returns char value for the particular index
2 int length() It returns string length
3 static String format(String format, Object... args) It returns a formatted string.
4 static String format(Locale l, String format, Object... args) It returns formatted string with given locale.
5 String substring(int beginIndex) It returns substring for given begin index.
6 String substring(int beginIndex, int endIndex) It returns substring for given begin index and end index.
7 boolean contains(CharSequence s) It returns true or false after matching the sequence of char
value.
8 static String join(CharSequence delimiter, CharSequence... elements) It returns a joined string.
9 static String join(CharSequence delimiter, Iterable<? extends CharSequence>
elements)
It returns a joined string.
10 boolean equals(Object another) It checks the equality of string with the given object.
11 boolean isEmpty() It checks if string is empty.
12 String concat(String str) It concatenates the specified string.
13 String replace(char old, char new) It replaces all occurrences of the specified char value.
14 String replace(CharSequence old, CharSequence new) It replaces all occurrences of the specified CharSequence.
15 static String equalsIgnoreCase(String another) It compares another string. It doesn't check case.
String Handling
• Concept of String
• Immutable String
• String Comparison
• String Concatenation
• Concept of Substring
• String class methods and its
usage
• StringBuffer class
• StringBuilder class
• Creating Immutable class
• toString() method
• StringTokenizer class
Immutable String in Java
A String is an unavoidable type of variable while
writing any application program. String references
are used to store various attributes like username,
password, etc. In Java, String objects are
immutable. Immutable simply means unmodifiable
or unchangeable.
Once String object is created its data or state can't
be changed but a new String object is created.
Output:
Sachin
Testimmutablestring.java
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method
appends the string at the end
System.out.println(s);//will print Sachin be
cause strings are immutable objects
}
}
Now it can be
understood by the
diagram given below.
Here Sachin is not
changed but a new
object is created with
Sachin Tendulkar.
That is why String is
known as immutable.
As you can see in the above
figure that two objects are
created but s reference
variable still refers to "Sachin"
not to "Sachin Tendulkar".
But if we explicitly assign it to
the reference variable, it will
refer to "Sachin Tendulkar"
object.
For example:
Testimmutablestring1.java
class Testimmutablestring1{
public static void main(String
args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output:
Sachin Tendulkar
Why String objects are immutable in Java?
• As Java uses the concept of String literal.
Suppose there are 5 reference variables, all
refer to one object "Sachin". If one reference
variable changes the value of the object, it will
be affected by all the reference variables.
That is why String objects are immutable in
Java.
• 1. ClassLoader:
• A ClassLoader in Java uses a String object as an
argument. Consider, if the String object is
modifiable, the value might be changed and the
class that is supposed to be loaded might be
different.
• To avoid this kind of misinterpretation, String
is immutable.
•
2. Thread Safe:
• As the String object is immutable we don't
have to take care of the synchronization that
is required while sharing an object across
multiple threads.
• 3. Security:
• As we have seen in class loading, immutable
String objects avoid further errors by loading the
correct class. This leads to making the
application program more secure. Consider an
example of banking software. The username
and password cannot be modified by any
intruder because String objects are immutable.
This can make the application program more
secure.
• 4. Heap Space:
• The immutability of String helps to minimize the
usage in the heap memory. When we try to
declare a new String object, the JVM checks
whether the value already exists in the String
pool or not. If it exists, the same value is
assigned to the new object. This feature allows
Java to use the heap space efficiently.
• Why String class is Final in Java?
• The reason behind the String class being final is
because no one can override the methods of the
String class. So that it can provide the same
Java String compare
We can compare String in Java on the basis of
content and reference.
It is used in authentication (by equals()
method), sorting (by compareTo() method),
reference matching (by == operator) etc.
There are three ways to compare String in
Java:
By Using equals() Method
By Using == Operator
By compareTo() Method
The String class equals() method compares the
original content of the string. It compares
values of string for equality. String class
provides the following two methods:
• public boolean equals(Object
another) compares this string to the
specified object.
• public boolean
equalsIgnoreCase(String
another) compares this string to
another string, ignoring case.
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//fals
e
In the above code, two strings are compared
using equals() method of String class. And
the result is printed as boolean
values, true or false.
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
}
}
2) By Using == operator
• The == operator compares references not values.
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instan
ce)
System.out.println(s1==s3);//false(because s3 refers to instance cre
ated in nonpool)
}
}
• 3) String compare by compareTo() method
• The above code, demonstrates the use of == operator used for
comparing two String objects.
• 3) By Using compareTo() method
• The String class compareTo() method compares values
lexicographically and returns an integer value that describes if
first string is less than, equal to or greater than second string.
• Suppose s1 and s2 are two String objects. If:
• s1 == s2 : The method returns 0.
• s1 > s2 : The method returns a positive value.
• s1 < s2 : The method returns a negative value.
Teststringcomparison4.java
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
String Concatenation in Java
• In Java, String concatenation
forms a new String that is the
combination of multiple
strings. There are two ways to
concatenate strings in Java:
1.By + (String concatenation)
operator
2.By concat() method
class TestStringConcatenation
1{
public static void main(String
args[]){
String s="Sachin"+" Tendulka
r";
System.out.println(s);//Sachin
Tendulkar
}
}
The Java compiler transforms above code to this:
String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toStrin
g();
• In Java, String concatenation is implemented through the StringBuilder (or
StringBuffer) class and it's append method. String concatenation operator
produces a new String by appending the second operand onto the end of
the first operand. The String concatenation operator can concatenate not
only String but primitive values also. For Example:
class TestStringConcatenation2{
public static void main(String args[]){
String s=50+30+"Sachin"+40+40;
System.out.println(s);//80Sachin4040
}
}
After a string literal, all the + will be treated as string concatenation operator.
2) String Concatenation by concat()
method
The String concat() method
concatenates the specified string to the
end of current string. Syntax:
public String concat(String another)
class TestStringConcatenation3{
public static void main(String ar
gs[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin
Tendulkar
}
}
There are some other possible ways to concatenate Strings in
Java,
1. String concatenation using StringBuilder class
• StringBuilder is class provides append()
method to perform concatenation
operation. The append() method accepts
arguments of different types like Objects,
StringBuilder, int, char, CharSequence,
boolean, float, double.
public class StrBuilder
{
/* Driver Code */
public static void main(String args[])
{
StringBuilder s1 = new StringBuilder("H
ello"); //String 1
StringBuilder s2 = new StringBuilder("
World"); //String 2
StringBuilder s = s1.append(s2); //Strin
g 3 to store the result
System.out.println(s.toString()); //Dis
plays result
}
}
2. String concatenation using format() method
• String.format() method allows to
concatenate multiple strings using
format specifier like %s followed by
the string values or objects.
public class StrFormat
{
/* Driver Code */
public static void main(String args[
])
{
String s1 = new String("Hello");
//String 1
String s2 = new String(" World");
//String 2
String s = String.format("%s%s",s
1,s2); //String 3 to store the result
System.out.println(s.toString());
//Displays result
}
}
Substring in Java
• A part of String is
called substring. In other
words, substring is a subset
of another String. Java String
class provides the built-in
substring() method that
extract a substring from the
given string by using the
index values passed as an
argument. In case of
substring() method startIndex
is inclusive and endIndex is
exclusive.
1.public String substring(int startIndex):
This method returns new String object containing
the substring of the given string from specified
startIndex (inclusive). The method throws an
IndexOutOfBoundException when the startIndex is
larger than the length of String or less than zero.
2.public String substring(int startIndex, int
endIndex):
This method returns new String object containing
the substring of the given string from specified
startIndex to endIndex. The method throws an
IndexOutOfBoundException when the startIndex is
less than zero or startIndex is greater than
endIndex or endIndex is greater than length of
String.
Using String.split() method:
The split() method of String class can be
used to extract a substring from a sentence.
It accepts arguments in the form of a
regular expression.
Output:
Hello,
My
name
is
Sachin
import java.util.*;
public class TestSubstring2
{
/* Driver Code */
public static void main(String args[])
{
String text= new String("Hello, My name is Sachin");
/* Splits the sentence by the delimeter passed as an
argument */
String[] sentences = text.split("s");
for(String w:sentences){
System.out.println(w);
}
}
}
Java String Class Methods
The java.lang.String class provides a lot of built-in
methods that are used to manipulate string in Java.
• Java String toUpperCase() and
toLowerCase() method
Output:
SACHIN
sachin
Sachin
public class Stringoperation1
{
public static void main(String ar[])
{
String s="Sachin";
System.out.println(s.toUpperCase());//S
ACHIN
System.out.println(s.toLowerCase());//s
achin
System.out.println(s);//Sachin(no chang
e in original)
}
}
Java String trim() method
The String class trim() method eliminates white spaces before and after the String.
Stringoperation2.java
public class Stringoperation2
{
public static void main(String ar[])
{
String s=" Sachin ";
System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin
}
} Output:
Sachin
Sachin
Java String startsWith() and endsWith() method
The method startsWith() checks whether the String starts with the letters passed as arguments
and endsWith() method checks whether the String ends with the letters passed as arguments.
public class Stringoperation3
{
public static void main(String ar[])
{
String s="Sachin";
System.out.println(s.startsWith("Sa"));//true
System.out.println(s.endsWith("n"));//true
}
}
true
true
Java String charAt() Method
The String class charAt() method returns a character at
specified index.
public class Stringoperation4
{
public static void main(String ar[])
{
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
}
}
Output:
S
h
Java String length() Method
The String class length() method returns length of the specified
String.
public class Stringoperation5
{
public static void main(String ar[])
{
String s="Sachin";
System.out.println(s.length());//6
}
}
Java StringBuffer Class
• Java StringBuffer class is used to create mutable (modifiable)
String objects. The StringBuffer class in Java is the same as
String class except it is mutable i.e. it can be changed.
Constructor Description
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(String str) It creates a String buffer with the specified string..
StringBuffer(int capacity) It creates an empty String buffer with the specified capacity
as length.
Important Constructors of StringBuffer Class
public synchronized
StringBuffer
append(String s) It is used to append the specified string with this string. The
append() method is overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.
public synchronized
StringBuffer
insert(int offset, String s) It is used to insert the specified string with this string at the
specified position. The insert() method is overloaded like
insert(int, char), insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
public synchronized
StringBuffer
replace(int startIndex, int
endIndex, String str)
It is used to replace the string from specified startIndex and
endIndex.
public synchronized
StringBuffer
delete(int startIndex, int
endIndex)
It is used to delete the string from specified startIndex and
endIndex.
public synchronized
StringBuffer
reverse() is used to reverse the string.
public int capacity() It is used to return the current capacity.
public void ensureCapacity(int minimumCapacity) It is used to ensure the capacity at least equal to the
given minimum.
public char charAt(int index) It is used to return the character at the specified
position.
public int length() It is used to return the length of the string i.e. total
number of characters.
public String substring(int beginIndex) It is used to return the substring from the specified
beginIndex.
public String substring(int beginIndex, int
endIndex)
It is used to return the substring from the specified
beginIndex and endIndex.
What is a mutable String?
A String that can be modified or changed is known as mutable String. StringBuffer and StringBuilder
classes are used for creating mutable strings.
1) StringBuffer Class append() Method
The append() method concatenates the given argument with this String.
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Output:
Hello Java
2) StringBuffer insert() Method
The insert() method inserts the given String with this string at the given
position.
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Output:
HJavaello
3) StringBuffer replace() Method
The replace() method replaces the given String from the specified
beginIndex and endIndex.
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
Output:
HJavalo
StringBuffer reverse() Method
The reverse() method of the StringBuilder class reverses the
current String.
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Output
olleH
Java StringBuilder Class
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
Constructor Description
StringBuilder() It creates an empty String Builder with the initial capacity of 16.
StringBuilder(String str) It creates a String Builder with the specified string.
StringBuilder(int length) It creates an empty String Builder with the specified capacity as length.
Important methods of StringBuilder class
Method Description
public StringBuilder
append(String s)
It is used to append the specified string with this string. The append()
method is overloaded like append(char), append(boolean), append(int),
append(float), append(double) etc.
public StringBuilder insert(int
offset, String s)
It is used to insert the specified string with this string at the specified
position. The insert() method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int, float), insert(int, double)
etc.
public StringBuilder
replace(int startIndex, int
endIndex, String str)
It is used to replace the string from specified startIndex and endIndex.
public StringBuilder
delete(int startIndex, int
It is used to delete the string from specified startIndex and endIndex.
public StringBuilder reverse() It is used to reverse the string.
public int capacity() It is used to return the current capacity.
public void ensureCapacity(int
minimumCapacity)
It is used to ensure the capacity at least equal to the given
minimum.
public char charAt(int index) It is used to return the character at the specified position.
public int length() It is used to return the length of the string i.e. total number of
characters.
public String substring(int
beginIndex)
It is used to return the substring from the specified beginIndex.
public String substring(int
beginIndex, int endIndex)
It is used to return the substring from the specified beginIndex and
endIndex.
StringBuilder append() method
The StringBuilder append() method concatenates the given
argument with this String.
class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Output:
Hello Java
StringBuilder insert() method
class StringBuilderExample2{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Output:
HJavaello
StringBuilder replace() method
class StringBuilderExample3{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
Output:
HJavalo
Difference between String and
StringBuffer
No. String StringBuffer
1) The String class is immutable. The StringBuffer class is mutable.
2) String is slow and consumes more memory
when we concatenate too many strings
because every time it creates new instance.
StringBuffer is fast and consumes less memory when we
concatenate t strings.
3) String class overrides the equals() method of
Object class. So you can compare the
contents of two strings by equals() method.
StringBuffer class doesn't override the equals() method
of Object class.
4) String class is slower while performing
concatenation operation.
StringBuffer class is faster while performing
concatenation operation.
5) String class uses String constant pool. StringBuffer uses Heap memory
Difference between StringBuffer and
StringBuilder
N
o.
StringBuffer StringBuilder
1) StringBuffer
is synchronized i.e. thread
safe. It means two threads
can't call the methods of
StringBuffer simultaneously.
StringBuilder is non-synchronized i.e. not
thread safe. It means two threads can call
the methods of StringBuilder
simultaneously.
2) StringBuffer is less
efficient than StringBuilder.
StringBuilder is more efficient than
StringBuffer.
3) StringBuffer was introduced in
Java 1.0
StringBuilder was introduced in Java 1.5
Type Conversion and Casting
• If the two types are compatible, then Java will perform the conversion
automatically. For example, it is always possible to assign an int value to
a long variable.
• However, not all types are compatible, and thus, not all type
conversions are implicitly allowed.
• For instance, there is no automatic conversion defined from double to
byte. still possible to obtain a conversion between incompatible types.
• cast, performs an explicit conversion between incompatible types.
Java’s Automatic Conversions
• When one type of data is assigned to another type of variable, an
automatic type conversion will take place if the following two conditions
are met:
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place the
int type is always large enough to hold all valid byte values, so no explicit cast
statement is
required.
1. For widening conversions, the numeric types, including integer and
floating-point types, are compatible with each other.
2. However, there are no automatic conversions from the numeric types
to char or boolean.
3. char and boolean are not compatible with each other.
Casting Incompatible Types: if you want to assign an int value to a byte
variable?
1. This conversion will not be performed automatically, because a byte is
smaller than an int.
2. This kind of conversion is sometimes called a narrowing conversion,
since you are explicitly making the value narrower so that it will fit into
the target type.
• To create a conversion between two incompatible types, use cast.
• A cast is simply an explicit type conversion (target-type) value
int a;
byte b;
// ...
b = (byte) a;
A different type of conversion will occur when a floating-point value is
assigned to an integer type: truncation.
if the value 1.23 is assigned to an integer, the resulting value will simply be
1.
Type conversions that require casts
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
This program generates the following output:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67
Automatic Type Promotion in Expressions
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
intermediate term a * b easily exceeds the range of either of its byte operands
• Java automatically promotes each byte, short, or char operand to int when evaluating an
expression. This means that the subexpression a * b is performed using integers—not bytes. Thus,
2,000, the result of the intermediate expression, 50 * 40, is legal even though a and b are both
specified as type byte.
byte b = 50;
B = b * 2; // Error! Cannot assign an int to a byte!
50 * 2, a perfectly valid byte value, back into a byte variable. However, because the operands were
automatically promoted to int the result has also been promoted to int but type int, cannot be
assigned to a byte without the use of a cast.
byte b = 50;
b = (byte)(b * 2);
Operators:
Java provides a rich operator environment. Most of its operators can be divided into the
following four groups: arithmetic, bitwise, relational, and logical.
Arithmetic Operators :Arithmetic operators are used in mathematical expressions in the
same way that they are used in algebra.
Operator Result
+ Addition
– Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
–= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
– – Decrement
+= compound assignment operator.
The Basic Arithmetic Operators
• The basic arithmetic
operations—addition,
subtraction, multiplication, and
division— all behave as you
would expect for all numeric
types.
• The minus operator also has a
unary form that negates its
single operand.
The Modulus Operator
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
Output:
x mod 10 = 2
y mod 10 = 2.25
• Arithmetic Compound Assignment Operators
• a = a + 4;
• In Java, you can rewrite this statement as shown here:
• a += 4;
• Increment and Decrement
The Bitwise Operators:
Java defines several bitwise operators that can be applied to the integer
types, long, int, short,
char, and byte.
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
The Bitwise Logical Operators: The bitwise
logical operators are &, |, ^, and ~.
The Bitwise 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
• The Bitwise 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
The Left Shift
value << num
class ByteShift {
public static void main(String args[])
{
byte a = 64, b;
int i;
i = a << 2;
b = (byte) (a << 2);
System.out.println("Original value of
a: " + a);
System.out.println("i and b: " + i + "
" + b);
}
}
• The output generated by this program is
shown here:
• Original value of a: 64
• i and b: 256 0
Relational Operators: The relational operators
determine the relationship that one operand has
to the other.
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
int a = 4;
int b = 1;
boolean c = a < b;
Boolean Logical Operators: The Boolean logical
operators shown here operate only on boolean
operands
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
In Java logical operators, if the evaluation of a logical expression exits in between before complete evaluation, then
it is known as Short-circuit.
• A short circuit happens because
the result is clear even before
the complete evaluation of the
expression, and the result is
returned. Short circuit
evaluation avoids unnecessary
work and leads to efficient
processing.
1. AND(&&) short circuit:
In the case of AND, the expression
is evaluated until we get one false
result because the result will
always be false, independent of
the further conditions. If there is
an expression with &&(logical
AND), and the first operand itself
is false, then a short circuit occurs,
the further expression is not
evaluated, and false is returned.
//Short-circuiting using AND(&&) operator.
import java.io.*;
class ShortCirAND {
public static void main(String arg[])
{
if (false && true && true) {
System.out.println("This output "
+ "will not "
+ "be printed");
}
else {
System.out.println("This output "
+ "got printed actually, "
+ " due to short circuit");
}
if (true && true && true) {
System.out.println("This output "
+ "gets print"
+ " as there will be"
+ " no Short circuit");
}
else {
System.out.println("This output "
+ "will not "
+ "be printed");
}
}
} Output
This output got printed actually, due to short circuit
This output gets print as there will be no Short circuit
//OR(||) short circuit:
class ShortCirOR {
public static void main(String arg[])
{
if (true || false || false) {
System.out.println("This output "
+ "got printed actually, "
+ " due to short circuit");
}
else {
System.out.println("This output "
+ "will not "
+ "be printed");
}
if (false || false || true) {
System.out.println("This output "
+ "gets print"
+ " as there will be"
+ " no Short circuit");
}
else {
System.out.println("This output "
+ "will not "
+ "be printed");
}
}
} Output
This output got printed actually, due to short circuit
This output gets print as there will be no Short circuit
The Assignment Operator
int x, y, z;
x = y = z = 100; // set x, y, and z to 100
The ? Operato
expression1 ? expression2 : expression3
class Ternary {
public static void main(String args[]) {
int i, k;
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
The output generated by the program is shown here:
Absolute value of 10 is 10
Absolute value of -10 is 10
Wrapper classes in Java
• The wrapper class in Java provides the mechanism to convert
primitive into object and object into primitive.
• Since J2SE 5.0, autoboxing and unboxing feature convert
primitives into objects and objects into primitives automatically.
• The automatic conversion of primitive into an object is known
as autoboxing and vice-versa unboxing.
Use of Wrapper classes in Java: Java is an object-oriented programming
language, so we need to deal with objects many times like in Collections,
Serialization, Synchronization, etc.
1. Change the value in Method: Java supports only call by value. So, if
we pass a primitive value, it will not change the original value. But, if we
convert the primitive value in an object, it will change the original value.
2. Serialization: We need to convert the objects into streams to perform
the serialization. If we have a primitive value, we can convert it in objects
through the wrapper classes.
3. Synchronization: Java synchronization works with objects in
Multithreading.
4. java.util package: The java.util package provides the utility classes to
deal with objects.
5. Collection Framework: Java collection framework works with objects
only. All classes of the collection framework (ArrayList, LinkedList,
Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque,
etc.) deal with objects only.
The eight classes of
the java.lang package are known as
wrapper classes in Java.
Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Autoboxing
• The automatic conversion of
primitive data type into its
corresponding wrapper class is
known as autoboxing.
• For example, byte to Byte, char to
Character, int to Integer, long to
Long, float to Float, boolean to
Boolean, double to Double, and
short to Short.
Output:
20 20 20
Wrapper class Example: Primitive to
Wrapper
public class WrapperExample1{
public static void main(String ar
gs[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//con
verting int into Integer explicitly
Integer j=a;//autoboxing, now co
mpiler will write Integer.valueOf(a
) internally
System.out.println(a+" "+i+" "+j);
Unboxing
• The automatic conversion of
wrapper type into its
corresponding primitive type
is known as unboxing. It is the
reverse process of
autoboxing.
Output:
3 3 3
• Wrapper class Example: Wrapper to
Primitive
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to i
nt explicitly
int j=a;//unboxing, now compiler will writ
e a.intValue() internally
System.out.println(a+" "+i+" "+j);
}}
Class Fundamentals
1. Perhaps the most important thing to understand about a class is that it defines a new data type.
2. Once defined, this new type can be used to create objects of that type.
3. Thus, a class is a template for an object, and an object is an instance of a class. Because an object
is an instance of a class, you will often see the two words object and instance used
interchangeably When you define a class, you declare its exact form and nature.
4. You do this by specifying the data that it contains and the code that operates on that data.
5. While very simple classes may contain only code or only data, most real-world classes contain
both. As you will see, a class’ code defines the interface to its data.
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
• The data, or variables, defined within
a class are called instance variables.
• The code is contained within
methods. Collectively, the methods
and variables defined within a class
are called members of the class.
• In most classes, the instance variables
are acted upon and accessed by the
methods defined for that class.
• Thus, as a general rule, it is the
methods that determine how a class’
data can be used.
1. Variables defined within a class are called instance
variables because each instance of the class (that
is, each object of the class) contains its own copy
of these variables.
2. Thus, the data for one object is separate and
unique from the data for another.
3. All methods have the same general form as
main(), which we have been using thus far.
4. However, most methods will not be specified as
static or public.
class Box {
double width;
double height;
double depth;
}
• Here is a class called Box that defines three
instance variables: width, height, and depth.
Box mybox = new Box(); // create a
Box object called mybox
• mybox will be an instance of Box. each time
you create an instance of a class, you are
creating an object that contains its own copy of
each instance variable defined by the class.
every Box object will contain its own copies of
the instance variables width, height, and
depth
• To access these variables, you will use the dot
(.) operator. The dot operator links the name of
the object with the name of an instance
variable.
• mybox.width = 100;
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
• Refere BoxDemo Example
• You should call the file that contains this
program BoxDemo.javabecause the main( )
method is in the class called BoxDemo, not
the class called Box.
• When you compile this program, you will find
that two .class files have been created, one for
Box and one for BoxDemo.
• The Java compiler automatically puts each
class into its own .class file. It is not necessary
for both the Box and the BoxDemo class to
actually be in the same source file.
• You could put each class in its own file, called
Box.java and BoxDemo.java, respectively.
• As stated earlier, each object has its own
copies of the instance variables. This means
that if you have two Box objects, each has its
own copy of depth, width, and height.
• It is important to understand that changes to
the instance variables of one object have no
effect on the instance variables of another.
• Refer BoxDemo2 Example
• As you can see, mybox1’s data is completely
separate from the data contained in mybox2.
class Box {
double width;
double height;
double depth;
}
class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/
* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}
Declaring Objects
1. Obtaining objects of a class is a two-step process. First, you must declare a variable of
the class type.
2. This variable does not define an object.
3. Instead, it is simply a variable that can refer to an object. Second, you must acquire an
actual, physical copy of the object and assign it to that variable.
4. You can do this using the new operator. The new operator dynamically allocates (that is,
allocates at run time) memory for an object and returns a reference to it.
5. This reference is, more or less, the address in memory of the object allocated by new.
6. This reference is then stored in the variable. Thus, in Java, all class objects must be
dynamically allocated.
7. Box mybox = new Box(); or;
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
• The first line declares mybox as a reference to an object of type Box.
• After this line executes, mybox contains the value null, which indicates that it does not yet point to an
actual object.
• Any attempt to use mybox at this point will result in a compile-time error.
• The next line allocates an actual object and assigns a reference to it to mybox. After the second line
executes, you can use mybox as if it were a Box object.
• But in reality, mybox simply holds the memory address of the actual Box object.
Assigning Object Reference Variables
Box b1 = new Box();
Box b2 = b1;
• You might think that b2 is being assigned a
reference to a copy of the object referred to by
b1.
• That is, you might think that b1 and b2 refer to
separate and distinct objects.
• However, this would be wrong. Instead, after
this fragment executes, b1 and b2 will both
refer to the same object.
• The assignment of b1 to b2 did not allocate
any memory or copy any part of the original
object.
• It simply makes b2 refer to the same object as
does b1. Thus, any changes made to the
object through b2 will affect the object to which
b1 is referring, since they are the same object.
• Although b1 and b2 both refer to the same object, they are not linked in
any other way.
• For example, a subsequent assignment to b1 will simply unhook b1 from
the original object without affecting the object or affecting b2. For
example:
Box b1 = new Box();
Box b2 = b1;
b1 = null;
• Here, b1 has been set to null, but b2 still points to the original object.
Introducing Methods: classes usually consist of two
things: instance variables and methods
This is the general form of a method:
type name(parameter-list) {
// body of method
}
Adding a Method to the Box Class
class Box {
double width;
double height;
double depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
// assign values to mybox1's instance
variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// display volume of first box
mybox1.volume();
// display volume of second box
mybox2.volume();
}
}
Returning a
Value
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Adding a Method That
Takes Parameters
// This program uses a parameterized
method.
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
// sets dimensions of box
void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
}
class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// initialize each box
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Constructors
1. It can be tedious to initialize all of the variables in
a class each time an instance is created.
2. Even when you add convenience functions like
setDim( ), it would be simpler and more concise
to have all of the setup done at the time the
object is first created.
3. Because the requirement for initialization is so
common, Java allows objects to initialize
themselves when they are created.
4. This automatic initialization is performed through
the use of a constructor.
1. A constructor initializes an object immediately
upon creation. It has the same name as the class
in which it resides and is syntactically similar to a
method.
2. Once defined, the constructor is automatically
called immediately after the object is created,
before the new operator completes.
3. Constructors look a little strange because they
have no return type, not even void.
4. This is because the implicit return type of a class’
constructor is the class type itself.
5. It is the constructor’s job to initialize the internal
state of an object so that the code creating an
instance will have a fully initialized, usable object
immediately
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box
objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Output:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
Parameterized Constructors
While the Box( ) constructor in the preceding example does initialize a
Box object, it is not very useful—all boxes have the same dimensions.
What is needed is a way to construct Box objects of various
dimensions. The easy solution is to add parameters to the constructor
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Volume is 3000.0
Volume is 162.0
The this Keyword
• Sometimes a method will need to
refer to the object that invoked it. To
allow this, Java defines the this
keyword. this can be used inside any
method to refer to the current
object.
• That is, this is always a reference to
the object on which the method was
invoked.
• You can use this anywhere a
reference to an object of the current
class’ type is permitted.
// A redundant use of this.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
This version of Box( ) operates exactly like the
earlier version. The use of this is redundant,
but perfectly correct. Inside Box( ), this will always
refer to the invoking object. While it is
redundant in this case, this is useful in other
contexts, one of which is explained in the next
section.
Instance Variable Hiding
• It is illegal in Java to declare two local variables with
the same name inside the same or enclosing scopes.
Interestingly, you can have local variables, including
formal parameters to methods, which overlap with
the names of the class’ instance variables.
• However, when a local variable has the same name
as an instance variable, the local variable hides the
instance variable. This is why width, height, and
depth were not used as the names of the parameters
to the Box( ) constructor inside the Box class.
• If they had been, then width would have referred to
the formal parameter, hiding the instance variable
width. While it is usually easier to simply use
different names, there is another way around this
situation.
• Because this lets you refer directly to the object,
you can use it to resolve any name space collisions
that might occur between instance variables and
local variables.
• For example, here is another version of Box( ),
which uses width, height, and depth for
parameter names and then uses this to access the
instance variables by the same name:
Box(double width, double height, double
depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Garbage Collection
• Since objects are dynamically allocated by
using the new operator, you might be
wondering
• how such objects are destroyed and their
memory released for later reallocation. In
some
• languages, such as C++, dynamically allocated
objects must be manually released by use of
• a delete operator. Java takes a different
approach; it handles deallocation for you
automatically.
• The technique that accomplishes this is called
garbage collection.
• It works like this: when no
• references to an object exist, that object is
assumed to be no longer needed, and the
memory
• occupied by the object can be reclaimed.
There is no explicit need to destroy objects as
in C++.
• Garbage collection only occurs sporadically (if
at all) during the execution of your program.
• It will not occur simply because one or more
objects exist that are no longer used.
Furthermore,
• different Java run-time implementations will
take varying approaches to garbage collection,
• but for the most part, you should not have to
think about it while writing your programs.
The finalize( ) Method
Sometimes an object will need to perform some action
when it is destroyed. For example, if an object is
holding some non-Java resource such as a file handle
or character font, then you might want to make sure
these resources are freed before an object is
destroyed.
To handle such situations, Java provides a
mechanism called finalization.
By using finalization, you can define specific actions
that will occur when an object is just about to be
reclaimed by the garbage collector.
To add a finalizer to a class, you simply define the
finalize( ) method.
The Java run time calls that method whenever it is
about to recycle an object of that class.
Inside the finalize( ) method, you will specify those
actions that must be performed before an object is
destroyed.
The garbage collector runs periodically, checking for
objects that are no longer referenced by any running
state or indirectly through other referenced objects.
Right before an asset is freed, the Java run time calls
the finalize( ) method on the object.
The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
} It is important to understand that finalize( ) is only
called just prior to garbage collection.
It is not called when an object goes out-of-scope, for
example. This means that you cannot know when—or
even if—finalize( ) will be executed. Therefore, your
program should provide other means of releasing
system resources, etc., used by the object. It must not
rely on finalize( )
for normal program operation.
A Stack Class: one of the archetypal examples of encapsulation: the stack. A stack stores data using first-in, last-
out
ordering. That is, a stack is like a stack of plates on a table—the first plate put down on the table is the last plate to
be used. Stacks are controlled through two operations traditionally called push and pop. To put an item on top of
the stack, you will use push. To take an item off the stack, you will use pop.
class Stack {
int stck[] = new int[10];
int tos;
Stack() {
tos = -1;
}
void push(int item) {
if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0; }
else
return stck[tos--];
} }
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack(); for(int i=0;
i<10; i++) mystack1.push(i);
for(int i=10; i<20; i++) mystack2.push(i);
System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());
}
}
This program generates the following
output:
Stack in mystack1:
9
8
7
6
5
4
3
2
1
0
Stack in mystack2:
19
18
17
16
15
14
13
12
11
10
Overloading Methods
• In Java it is possible to define two or more
methods within the same class that share
the same name, as long as their
parameter declarations are different.
• When this is the case, the methods are
said to be overloaded, and the process is
referred to as method overloading.
• Method overloading is one of the ways
that Java supports polymorphism.
• If you have never used a language that
allows the overloading of methods, then
the concept may seem strange at first.
• When an overloaded method is invoked, Java
uses the type and/or number of arguments as
its guide to determine which version of the
overloaded method to actually call.
• Thus, overloaded methods must differ in the
type and/or number of their parameters.
• While overloaded methods may have different
return types, the return type alone is
insufficient to distinguish two versions of a
method.
When Java encounters a call to an overloaded
method, it simply executes the version of the
method whose parameters match the
arguments used in the call.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
} // Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
} }
class Overload {
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of
ob.test(123.25): " + result);
} }
This program generates the following output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
Overloading Constructors: overloading normal methods, you
can also overload constructor methods
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;}
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box}
Box(double len) {
width = height = depth = len;
double volume() {
return width * height * depth;}}
class OverloadCons {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
Using Objects as Parameters: So far, we have only been using simple types as parameters to methods.
However, it is both correct and common to pass objects to methods. For example, consider the following
short program:
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
} boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
class PassOb {
public static void main(String
args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " +
ob1.equals(ob2));
System.out.println("ob1 == ob3: " +
ob1.equals(ob3));
}
}
This program generates the following output:
ob1 == ob2: true
ob1 == ob3: false
class Box {
double width;
double height;
double depth;
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;}
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;}
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box}
Box(double len) {
width = height = depth = len;}
double volume() {
return width * height * depth;}}
class OverloadCons2 {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
Box myclone = new Box(mybox1); // create copy of
mybox1
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println("Volume of cube is " + vol);
vol = myclone.volume();
System.out.println("Volume of clone is " + vol);} }
Here, Box allows one
object to initialize
another.
Introducing Access Control
• As you know, encapsulation links data with the
code that manipulates it. However, encapsulation
provides another important attribute: access
control.
• Through encapsulation, you can control what
parts of a program can access the members
of a class. By controlling access, you can
prevent misuse. Java’s access specifiers are
public, private, and protected. Java also defines a
default access level. protected applies only when
inheritance is involved.
• The other access specifiers are described next.
When a member of a class is modified by the
public specifier, then that member can be
accessed by any other code. When a member
of a class is specified as private, then that
member can only be accessed by other
members ofits class.
• Now you can understand why main( ) has
always been preceded by the publics pecifier.
It is called by code that is outside the
program—that is, by the Java run-timesystem.
When no access specifier is used, then by
default the member of a class is publicwithin
its own package, but cannot be accessed
outside of its package. (Packages
arediscussed in the following chapter.)
In the classes developed so far, all members of a class
have used the default access mode, which is essentially
public. However, this is not what you will typically want to
be the case.
Usually, you will want to restrict access to the data
members of a class—allowing access only through
methods. Also, there will be times when you will want to
define methods that are private to a class.
This program demonstrates the difference
between public and private.
class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) { // set c's value
c = i; }
int getc() { // get c's value
return c;} }
class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
// These are OK, a and b may be accessed
directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a
+ " " +
ob.b + " " + ob.getc());
}
}
Understanding static
• There will be times when you will want to define a
class member that will be used independently of any
object of that class. Normally, a class member must
be accessed only in conjunction with an object of its
class.
• However, it is possible to create a member that can be
used by itself, without reference to a specific instance.
To create such a member, precede its declaration with
the keyword static.
• When a member is declared static, it can be accessed
before any objects of its class are created, and
without reference to any object. You can declareboth
methods and variables to be static.
• The most common example of a static member
ismain( ).main( ) is declared as static because it must
be called before any objects exist.
Instance variables declared as static are, essentially,
global variables. When objects of its class are declared,
no copy of a static variable is made. Instead, all
instances of the class share the same static variable.
Methods declared as static have several restrictions:
1. They can only call other static methods.
2. They must only access static data.
3. They cannot refer to this or super in any way. (The
keyword super relates to inheritance and is
described in the next chapter.)
If you need to do computation in order to initialize your
static variables, you can declare a static block that gets
executed exactly once, when the class is first loaded.
The following example shows a class that has a static
method, some static variables, and a static initialization
block:
// Demonstrate static variables, methods,
and blocks.
class UseStatic {
static int a = 3;
static int b;
static void meth(int x)
{System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block
initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
1. As soon as the UseStatic class is loaded, all of the static
statements are run.
2. First, a is set to 3, then the static block executes, which
prints a message and then initializes b to a * 4 or 12.
3. Then main( ) is called, which calls meth( ), passing 42 to
x.
4. The three println( ) statements refer to the two static
variables a and b, as well as to the local variable x.
Here is the output of the program:
Static block initialized.
x = 42
a = 3
b = 12
Outside of the class in which they are defined, static methods
and variables can be used independently of any object.
To do so, you need only specify the name of their class
followed by the dot operator.
For example, if you wish to call a static method from outside
its class, you can do so using the following general form:
classname.method( )
• Here, classname is the name of the class in which the
static method is declared.
• As you can see, this format is similar to that used to
call non-static methods through object-reference
variables.
• A static variable can be accessed in the same way—
by use of the dot operator on the name of the class.
• This is how Java implements a controlled version of
global methods and global variables.
• Inside main( ), the static method callme( ) and the
static variable b are accessed through their class
name StaticDemo.
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}
class StaticByName {
public static void main(String args[])
{
StaticDemo.callme();
System.out.println("b = " +
StaticDemo.b);
}
}
Here is the output of this program:
a = 42
b = 99
Introducing final
• A variable can be declared as final. Doing so
prevents its contents from being modified.
• This means that you must initialize a final
variable when it is declared.
• For example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
• Subsequent parts of your program can now use
FILE_OPEN, etc., as if they were constants, without
fear that a value has been changed.
• It is a common coding convention to choose all
uppercase identifiers for final variables. Variables
declared as final do not occupy memory on a per-
instance basis.
• Thus, a final variable is essentially a constant. The
keyword final can also be applied to methods, but
its meaning is substantially different than when it is
applied to variables.
• This second usage of final is described in the next
chapter, when inheritance is described.
Nested and Inner Classes
• It is possible to define a class within another class;
such classes are known as nested classes.
• The scope of a nested class is bounded by the
scope of its enclosing class.
• Thus, if class B is defined within class A, then B
does not exist independently of A.
• A nested class has access to the members,
including private members, of the class in which it
is nested.
• However, the enclosing class does not have access
to the members of the nested class.
• A nested class that is declared directly within its
enclosing class scope is a member of its enclosing
class.
• It is also possible to declare a nested class that is
local to a block.
• There are two types of nested classes: static and
non-static.
• A static nested class is one that has the static
modifier applied. Because it is static, it must access
the members of its enclosing class through an object.
• That is, it cannot refer to members of its enclosing
class directly. Because of this restriction, static
nested classes are seldom used.
• The most important type of nested class is the inner
class.
• An inner class is a non-static nested class. It has
access to all of the variables and methods of its outer
class and may refer to them directly in the same way
that other non-static members of the outer class do.
The class named Outer has one instance variable named outer_x, one instance method named test(
), and defines one inner class called Inner.
// Demonstrate an inner class.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
void display() {
System.out.println("display: outer_x =
" + outer_x);
} } }
class InnerClassDemo {
public static void main(String
args[]) {
Outer outer = new Outer();
outer.test();
}
}
Output from this application is shown here:
display: outer_x = 100
• The main( ) method of InnerClassDemo creates an instance of class Outer and invokes its test( )
method.
• That method creates an instance of class Inner and the display( ) method is called. It is important to
realize that an instance of Inner can be created only within the scope of class Outer.
• The Java compiler generates an error message if any code outside of class Outer attempts to
instantiate class Inner.
• (In general, an inner class instance must be created by an enclosing scope.) You can, however,
create an instance of Inner outside of Outer by qualifying its name with Outer, as in Outer.Inner.
• An inner class has access to all of the members of its enclosing class, but the reverse is not true.
• Members of the inner class are known only within the scope of the inner class and may not be used
by the outer class
// This program will not compile.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
int y = 10; // y is local to Inner
void display() {
System.out.println("display: outer_x = "
+ outer_x);
}
}
void showy() {
System.out.println(y); // error, y not
known here!
}
}
class InnerClassDemo {
public static void main(String args[])
{
Outer outer = new Outer();
outer.test();
}
}
Here, y is declared as an instance varia
• Although we have been focusing on inner classes declared as
members within an outer class scope, it is possible to define
inner classes within any block scope.
• For example, you can define a nested class within the block
defined by a method or even within the body of a for loop, as this
next program shows.
// Define an inner class within a for loop.
class Outer {
int outer_x = 100;
void test() {
for(int i=0; i<10; i++) {
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
} }
Inner inner = new Inner();
inner.display(); }}}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
The output from this version of the program is shown here.
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
• While nested classes are not applicable to all stiuations,
they are particularly helpful when handling events. We will
return to the topic of nested classes in Chapter 22.
• There you will see how inner classes can be used to simplify
the code needed to handle certain types of events.
• You will also learn about anonymous inner classes, which
are inner classes that don’t have a name.
• One final point: Nested classes were not allowed by the
original 1.0 specification for Java.
Java Singleton Class: Singleton Design Pattern in Java.
Singleton is a design pattern that ensures that a class can only
have one object.
To create a singleton class, a class must
implement the following properties:
1. Create a private constructor of the class to
restrict object creation outside of the class.
2. Create a private attribute of the class type that
refers to the single object.
3. Create a public static method that allows us to
create and access the object we created. Inside
the method, we will create a condition that
restricts us from creating more than one object.
class SingletonExample {
// private field that refers to the object
private static SingletonExample singleObject;
private SingletonExample() {
// constructor of the SingletonExample class
}
public static SingletonExample getInstance() {
// write code that allows us to create only one
object
// access the object as per our need
}}
1. private static SingletonExample singleObject - a
reference to the object of the class.
2. private SingletonExample() - a private constructor
that restricts creating objects outside of the class.
3. public static SingletonExample getInstance() - this
method returns the reference to the only object
of the class. Since the method static, it can be
accessed using the class name.
Use of Singleton in Java: Singletons can be used while working with
databases. They can be used to create a connection pool to access the
database while reusing the same connection for all the clients
class Database {
private static Database dbObject;
private Database() {
}
public static Database getInstance() {
// create object if it's not already created
if(dbObject == null) {
dbObject = new Database(); }
// returns the singleton object
return dbObject; }
public void getConnection() {
System.out.println("You are now connected to the database."); }}
class Main {
public static void main(String[] args) {
Database db1; // refers to the only object of Database db1=
Database.getInstance();
db1.getConnection();} }
You are now connected to the database.
1. We have created a singleton class Database.
2. The dbObject is a class type field. This will
refer to the object of the class Database. The
private constructor Database() prevents object
creation outside of the class.
3. The static class type method getInstance()
returns the instance of the class to the outside
world. In the Main class, we have class type
variable db1.
4. We are calling getInstance() using db1 to get
the only object of the Database. The method
getConnection() can only be accessed using
the object of the Database.
5. Since the Database can have only one object,
all the clients can access the database through
a single connection.

Contenu connexe

Similaire à Java Programming Language Features, Applications and History

Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programmingElizabeth Thomas
 
Java and its features
Java and its featuresJava and its features
Java and its featuresPydi Nikhil
 
JAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptxJAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptxMurugesh33
 
JAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptxJAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptxMurugesh33
 
PPS Java Overview Unit I.ppt
PPS Java Overview Unit I.pptPPS Java Overview Unit I.ppt
PPS Java Overview Unit I.pptRajeshSukte1
 
PPS Java Overview Unit I.ppt
PPS Java Overview Unit I.pptPPS Java Overview Unit I.ppt
PPS Java Overview Unit I.pptCDSukte
 
JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxSuganthiDPSGRKCW
 
1 Introduction to JAVA.pptx
1 Introduction to JAVA.pptx1 Introduction to JAVA.pptx
1 Introduction to JAVA.pptxKabiles07
 
Lecture - 1 introduction to java
Lecture - 1 introduction to javaLecture - 1 introduction to java
Lecture - 1 introduction to javamanish kumar
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsOm Ganesh
 
Java Introduction | PDF
Java Introduction |  PDFJava Introduction |  PDF
Java Introduction | PDFGeekster
 

Similaire à Java Programming Language Features, Applications and History (20)

Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
 
Java
JavaJava
Java
 
Java introduction
Java introductionJava introduction
Java introduction
 
Java and its features
Java and its featuresJava and its features
Java and its features
 
JAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptxJAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptx
 
JAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptxJAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptx
 
PPS Java Overview Unit I.ppt
PPS Java Overview Unit I.pptPPS Java Overview Unit I.ppt
PPS Java Overview Unit I.ppt
 
PPS Java Overview Unit I.ppt
PPS Java Overview Unit I.pptPPS Java Overview Unit I.ppt
PPS Java Overview Unit I.ppt
 
JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptx
 
Getting Started with JAVA
Getting Started with JAVAGetting Started with JAVA
Getting Started with JAVA
 
Java Basic.pdf
Java Basic.pdfJava Basic.pdf
Java Basic.pdf
 
Java
JavaJava
Java
 
Java 2 computer science.pptx
Java 2 computer science.pptxJava 2 computer science.pptx
Java 2 computer science.pptx
 
Introduction of java
Introduction  of javaIntroduction  of java
Introduction of java
 
1 Introduction to JAVA.pptx
1 Introduction to JAVA.pptx1 Introduction to JAVA.pptx
1 Introduction to JAVA.pptx
 
INTRODUCTORY CONCEPTS OF JAVA
INTRODUCTORY CONCEPTS OF JAVAINTRODUCTORY CONCEPTS OF JAVA
INTRODUCTORY CONCEPTS OF JAVA
 
Lecture - 1 introduction to java
Lecture - 1 introduction to javaLecture - 1 introduction to java
Lecture - 1 introduction to java
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Java Introduction | PDF
Java Introduction |  PDFJava Introduction |  PDF
Java Introduction | PDF
 
java slides
java slidesjava slides
java slides
 

Dernier

(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 

Dernier (20)

(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 

Java Programming Language Features, Applications and History

  • 1. Introduction: Feature of Java, Java Virtual Machine, Byte Code, JDK, JRE, Comments, Java coding convention
  • 2. What is Java? 1. Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure programming language. 2. Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was already a registered company, so James Gosling and his team changed the name from Oak to Java. 3. Platform: Any hardware or software environment in which a program runs, is known as a platform. Since Java has a runtime environment (JRE) and API, it is called a platform.
  • 3. Application According to Sun, 3 billion devices run Java. There are many devices where Java is currently used. Some of them are as follows: 1. Desktop Applications such as acrobat reader, media player, antivirus, etc. 2. Web Applications such as irctc.co.in etc. 3. Enterprise Applications such as banking applications. 4. Mobile 5. Embedded System 6. Smart Card 7. Robotics 8. Games, etc.
  • 4. Java • The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and Dynamic". Java was developed by James Gosling, who is known as the father of Java, in 1995. James Gosling and his team members started the project in the early '90s. • Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc. Following are given significant points that describe the history of Java • 1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The small team of sun engineers called Green Team.
  • 5. • 2) Initially it was designed for small, embedded systems in electronic appliances like set-top boxes. • 3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt. • 4) After that, it was called Oak and was developed as a part of the Green project.
  • 6. • 7) Why had they chosen the name Java for Java language? The team gathered to choose a new name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted something that reflected the essence of the technology: revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun to say. • According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so unique, most of the team members preferred Java than other names. • 8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of espresso bean. Java name was chosen by James Gosling while having a cup of coffee nearby his office.
  • 7. • 9) Notice that Java is just a name, not an acronym. • 10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released in 1995. • 11) In 1995, Time magazine called Java one of the Ten Best Products of 1995. • 12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many additional features added to the language. Now Java is being used in Windows applications, Web applications, enterprise applications, mobile applications, cards, etc. Each new version adds new features in Java.
  • 8. 1. JDK Alpha and Beta (1995) 2. JDK 1.0 (23rd Jan 1996) 3. JDK 1.1 (19th Feb 1997) 4. J2SE 1.2 (8th Dec 1998) 5. J2SE 1.3 (8th May 2000) 6. J2SE 1.4 (6th Feb 2002) 7. J2SE 5.0 (30th Sep 2004) 8. Java SE 6 (11th Dec 2006) 9. Java SE 7 (28th July 2011) 1. Java SE 8 (18th Mar 2014) 2. Java SE 9 (21st Sep 2017) 3. Java SE 10 (20th Mar 2018) 4. Java SE 11 (September 2018) 5. Java SE 12 (March 2019) 6. Java SE 13 (September 2019) 7. Java SE 14 (Mar 2020) 8. Java SE 15 (September 2020) 9. Java SE 16 (Mar 2021) 10. Java SE 17 (September 2021) 11. Java SE 18 (to be released by March 2022)
  • 9. Features of Java • The primary objective of Java programming language creation was to make it portable, simple and secure programming language. Apart from this, there are also some excellent features which play an important role in the popularity of this language. The features of Java are also known as Java buzzwords. • A list of the most important features of the Java language is given below. • Simple • Object-Oriented • Portable • Platform independent • Secured • Robust • Architecture neutral • Interpreted • High Performance • Multithreaded • Distributed • Dynamic
  • 10. Simple 1. Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem, Java language is a simple programming language because: 2. Java syntax is based on C++ (so easier for programmers to learn it after C++). 3. Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc. 4. There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java.
  • 11. Object-oriented • Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we organize our software as a combination of different types of objects that incorporate both data and behavior • Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance by providing some rules. Basic concepts of OOPs are: 1.Object 2.Class 3.Inheritance 4.Polymorphism 5.Abstraction 6.Encapsulation
  • 12. Platform Independent 1. Java is platform independent because it is different from other languages like C, C++, etc. which are compiled into platform specific machines while Java is a write once, run anywhere language. A platform is the hardware or software environment in which a program runs. 2. There are two types of platforms software-based and hardware-based. Java provides a software-based platform. 3. The Java platform differs from most other platforms in the sense that it is a software-based platform that runs on top of other hardware-based platforms. It has two components: 4. Runtime Environment 5. API(Application Programming Interface) 6. Java code can be executed on multiple platforms, for example, 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).
  • 13. Secured Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because: 1. No explicit pointer 2. Java Programs run inside a virtual machine sandbox Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to load Java classes into the Java Virtual Machine dynamically. It adds security by separating the package for the classes of the local file system from those that are imported from network sources. 1. Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects. 2. Security Manager: It determines what resources a class can access such as reading and writing to the local disk. 3. Java language provides these securities by default. Some security can also be provided by an application developer explicitly through SSL, JAAS, Cryptography, etc.
  • 14. Robust The English meaning of Robust is strong. Java is robust because: 1. It uses strong memory management. 2. There is a lack of pointers that avoids security problems. 3. Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not being used by a Java application anymore. 4. There are exception handling and the type checking mechanism in Java. All these points make Java robust.
  • 15. Architecture-neutral • Java is architecture neutral because there are no implementation dependent features, for example, the 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. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
  • 16. Portable • Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation. High-performance • Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.
  • 17. • Distributed • Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet. • 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. • Dynamic • Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++. • Java supports dynamic compilation and automatic memory management (garbage collection).
  • 18. Java Arrays • Normally, an array is a collection of similar type of elements which has contiguous memory location. • Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array. • Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on.
  • 19. • In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an array in Java. Like C/C++, we can also create single dimensional or multidimensional arrays in Java. • Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
  • 20. Advantages • Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently. • Random access: We can get any data located at an index position. Disadvantages • Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically. Types of Array in java There are two types of array. 1. Single Dimensional Array 2. Multidimensional Array
  • 21. Single Dimensional Array in Java Syntax to Declare an Array in Java dataType[] arr; (or) dataType []arr; (or) dataType arr[]; Instantiation of an Array in Java arrayRefVar=new datatype[size];
  • 22. Example of Java Array we are going to declare, instantiate, initialize and traverse an array class Testarray{ public static void main(String args[]){ int a[]=new int[5];//declaration and instantiation a[0]=10;//initialization a[1]=20; a[2]=70; a[3]=40; a[4]=50; //traversing array for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]); }}
  • 23. Declaration, Instantiation and Initialization of Java Array We can declare, instantiate and initialize the java array together by: int a[]={33,3,4,5};//declaration, instantiation and initialization //Java Program to illustrate the use of declaration, instantiation //and initialization of Java array in a single line class Testarray1{ public static void main(String args[]){ int a[]={33,3,4,5};//declaration, instantiation and initialization //printing array for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]); }}
  • 24. For-each Loop for Java Array We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then executes the body of the loop. The syntax of the for-each loop is given below: for(data_type variable:array){ //body of the loop } class Testarray1{ public static void main(String args[]){ int arr[]={33,3,4,5}; //printing array using for-each loop for(int i:arr) System.out.println(i); }}
  • 25. Passing Array to a Method in Java //Java Program to demonstrate the way of passing an array //to method. class Testarray2{ //creating a method which receives an array as a parameter static void min(int arr[]){ int min=arr[0]; for(int i=1;i<arr.length;i++) if(min>arr[i]) min=arr[i]; System.out.println(min); } public static void main(String args[]){ int a[]={33,3,4,5};//declaring and initializing an array min(a);//passing array to method }} We can pass the java array to method so that we can reuse the same logic on any array. Let's see the simple example to get the minimum number of an array using a method. Output: 3
  • 26. //Java Program to return an array from the m ethod class TestReturnArray{ //creating method which returns an array static int[] get(){ return new int[]{10,30,50,90,60}; } public static void main(String args[]){ //calling method which returns an array int arr[]=get(); //printing the values of an array for(int i=0;i<arr.length;i++) System.out.println(arr[i]); }} Returning Array from the Method We can also return an array from the method in Java. Output: 10 30 50 90 60
  • 27. Multidimensional Array in Java In such case, data is stored in row and column-based index (also known as matrix form). Syntax to Declare Multidimensional Array in Java Example to instantiate Multidimensional Array in Java int[][] arr=new int[3][3];//3 row and 3 column Example to initialize Multidimensional Array in Java arr[0][0]=1; arr[0][1]=2; arr[0][2]=3; arr[1][0]=4; arr[1][1]=5; arr[1][2]=6; arr[2][0]=7; arr[2][1]=8; arr[2][2]=9; dataType[][] arrayRefVar; (or) dataType [][]arrayRefVar; (or) dataType arrayRefVar[][]; (or) dataType []arrayRefVar[];
  • 28. Example of Multidimensional Java Array. declare, instantiate, initialize and print the 2Dimensional array. //Java Program to illustrate the use of multidimensional array class Testarray3{ public static void main(String args[]){ //declaring and initializing 2D array int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //printing 2D array for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } }}
  • 29. Addition of 2 Matrices in Java //Java Program to demonstrate the addition of two matrices in Java class Testarray5{ public static void main(String args[]){ //creating two matrices int a[][]={{1,3,4},{3,4,5}}; int b[][]={{1,3,4},{3,4,5}}; //creating another matrix to store the sum of two matrices int c[][]=new int[2][3]; //adding and printing addition of 2 matrices for(int i=0;i<2;i++){ for(int j=0;j<3;j++){ c[i][j]=a[i][j]+b[i][j]; System.out.print(c[i][j]+" "); } System.out.println();//new line } }}
  • 30. multiply two matrices of 3 rows and 3 columns //Java Program to multiply two matrices public class MatrixMultiplicationExample{ public static void main(String args[]){ //creating two matrices int a[][]={{1,1,1},{2,2,2},{3,3,3}}; int b[][]={{1,1,1},{2,2,2},{3,3,3}}; //creating another matrix to store the multiplication of two matrices int c[][]=new int[3][3]; //3 rows and 3 columns //multiplying and printing multiplication of 2 matrices for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ c[i][j]=0; for(int k=0;k<3;k++) { c[i][j]+=a[i][k]*b[k][j]; }//end of k loop System.out.print(c[i][j]+" "); //printing matrix element }//end of j loop System.out.println();//new line } }}
  • 31. 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: • char[] ch={'j','a','v','a','p','o','i','n','t'}; • String s=new String(ch); • is same as: • String s="java"; • Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc. • The java.lang.String class implements Serializable, Comparable a nd CharSequence interfaces.
  • 32. CharSequence Interface • The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in Java by using these three classes. • The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes. • We will discuss immutable string later. Let's first understand what String in Java is and how to create the String object.
  • 33. What is String in Java? 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 the 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";//It doe sn't create a new instance Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object. There are two ways to create String object: 1.By string literal 2.By new keyword
  • 34. • only one object will be created. Firstly, JVM will not find any string object with the value "Welcome" in string constant pool that is why it will create a new object. After that it will find the string with the value "Welcome" in the pool, it will not create a new object but will return the reference to the same instance.
  • 35. 2) By new keyword String s=new String("Welcome");//creates two objects and one reference variable 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 a heap (non-pool). Why Java uses the concept of String literal? To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).
  • 36. Java String Example StringExample.java public class StringExample{ public static void main(String args[]){ String s1="java";//creating string by Java s tring 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");//creatin g Java string by new keyword System.out.println(s1); System.out.println(s2); System.out.println(s3); }} Output: java strings Example The above code, converts a char array into a String object. And displays the String objects s1, s2, and s3 on console using println() method.
  • 37. Java String class methods The java.lang.String class provides many useful methods to perform operations on sequence of char values. No. Method Description 1 char charAt(int index) It returns char value for the particular index 2 int length() It returns string length 3 static String format(String format, Object... args) It returns a formatted string. 4 static String format(Locale l, String format, Object... args) It returns formatted string with given locale. 5 String substring(int beginIndex) It returns substring for given begin index. 6 String substring(int beginIndex, int endIndex) It returns substring for given begin index and end index. 7 boolean contains(CharSequence s) It returns true or false after matching the sequence of char value. 8 static String join(CharSequence delimiter, CharSequence... elements) It returns a joined string. 9 static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) It returns a joined string. 10 boolean equals(Object another) It checks the equality of string with the given object. 11 boolean isEmpty() It checks if string is empty. 12 String concat(String str) It concatenates the specified string. 13 String replace(char old, char new) It replaces all occurrences of the specified char value. 14 String replace(CharSequence old, CharSequence new) It replaces all occurrences of the specified CharSequence. 15 static String equalsIgnoreCase(String another) It compares another string. It doesn't check case.
  • 38. String Handling • Concept of String • Immutable String • String Comparison • String Concatenation • Concept of Substring • String class methods and its usage • StringBuffer class • StringBuilder class • Creating Immutable class • toString() method • StringTokenizer class
  • 39. Immutable String in Java A String is an unavoidable type of variable while writing any application program. String references are used to store various attributes like username, password, etc. In Java, String objects are immutable. Immutable simply means unmodifiable or unchangeable. Once String object is created its data or state can't be changed but a new String object is created. Output: Sachin Testimmutablestring.java class Testimmutablestring{ public static void main(String args[]){ String s="Sachin"; s.concat(" Tendulkar");//concat() method appends the string at the end System.out.println(s);//will print Sachin be cause strings are immutable objects } }
  • 40. Now it can be understood by the diagram given below. Here Sachin is not changed but a new object is created with Sachin Tendulkar. That is why String is known as immutable.
  • 41. As you can see in the above figure that two objects are created but s reference variable still refers to "Sachin" not to "Sachin Tendulkar". But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar" object. For example: Testimmutablestring1.java class Testimmutablestring1{ public static void main(String args[]){ String s="Sachin"; s=s.concat(" Tendulkar"); System.out.println(s); } } Output: Sachin Tendulkar
  • 42. Why String objects are immutable in Java? • As Java uses the concept of String literal. Suppose there are 5 reference variables, all refer to one object "Sachin". If one reference variable changes the value of the object, it will be affected by all the reference variables. That is why String objects are immutable in Java. • 1. ClassLoader: • A ClassLoader in Java uses a String object as an argument. Consider, if the String object is modifiable, the value might be changed and the class that is supposed to be loaded might be different. • To avoid this kind of misinterpretation, String is immutable. • 2. Thread Safe: • As the String object is immutable we don't have to take care of the synchronization that is required while sharing an object across multiple threads. • 3. Security: • As we have seen in class loading, immutable String objects avoid further errors by loading the correct class. This leads to making the application program more secure. Consider an example of banking software. The username and password cannot be modified by any intruder because String objects are immutable. This can make the application program more secure. • 4. Heap Space: • The immutability of String helps to minimize the usage in the heap memory. When we try to declare a new String object, the JVM checks whether the value already exists in the String pool or not. If it exists, the same value is assigned to the new object. This feature allows Java to use the heap space efficiently. • Why String class is Final in Java? • The reason behind the String class being final is because no one can override the methods of the String class. So that it can provide the same
  • 43. Java String compare We can compare String in Java on the basis of content and reference. It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc. There are three ways to compare String in Java: By Using equals() Method By Using == Operator By compareTo() Method The String class equals() method compares the original content of the string. It compares values of string for equality. String class provides the following two methods: • public boolean equals(Object another) compares this string to the specified object. • public boolean equalsIgnoreCase(String another) compares this string to another string, ignoring case. class Teststringcomparison1{ public static void main(String args[]){ String s1="Sachin"; String s2="Sachin"; String s3=new String("Sachin"); String s4="Saurav"; System.out.println(s1.equals(s2));//true System.out.println(s1.equals(s3));//true System.out.println(s1.equals(s4));//fals e
  • 44. In the above code, two strings are compared using equals() method of String class. And the result is printed as boolean values, true or false. class Teststringcomparison2{ public static void main(String args[]){ String s1="Sachin"; String s2="SACHIN"; System.out.println(s1.equals(s2));//false System.out.println(s1.equalsIgnoreCase(s2));//true } }
  • 45. 2) By Using == operator • The == operator compares references not values. class Teststringcomparison3{ public static void main(String args[]){ String s1="Sachin"; String s2="Sachin"; String s3=new String("Sachin"); System.out.println(s1==s2);//true (because both refer to same instan ce) System.out.println(s1==s3);//false(because s3 refers to instance cre ated in nonpool) } }
  • 46. • 3) String compare by compareTo() method • The above code, demonstrates the use of == operator used for comparing two String objects. • 3) By Using compareTo() method • The String class compareTo() method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string. • Suppose s1 and s2 are two String objects. If: • s1 == s2 : The method returns 0. • s1 > s2 : The method returns a positive value. • s1 < s2 : The method returns a negative value.
  • 47. Teststringcomparison4.java class Teststringcomparison4{ public static void main(String args[]){ String s1="Sachin"; String s2="Sachin"; String s3="Ratan"; System.out.println(s1.compareTo(s2));//0 System.out.println(s1.compareTo(s3));//1(because s1>s3) System.out.println(s3.compareTo(s1));//-1(because s3 < s1 ) } }
  • 48. String Concatenation in Java • In Java, String concatenation forms a new String that is the combination of multiple strings. There are two ways to concatenate strings in Java: 1.By + (String concatenation) operator 2.By concat() method class TestStringConcatenation 1{ public static void main(String args[]){ String s="Sachin"+" Tendulka r"; System.out.println(s);//Sachin Tendulkar } }
  • 49. The Java compiler transforms above code to this: String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toStrin g(); • In Java, String concatenation is implemented through the StringBuilder (or StringBuffer) class and it's append method. String concatenation operator produces a new String by appending the second operand onto the end of the first operand. The String concatenation operator can concatenate not only String but primitive values also. For Example: class TestStringConcatenation2{ public static void main(String args[]){ String s=50+30+"Sachin"+40+40; System.out.println(s);//80Sachin4040 } } After a string literal, all the + will be treated as string concatenation operator.
  • 50. 2) String Concatenation by concat() method The String concat() method concatenates the specified string to the end of current string. Syntax: public String concat(String another) class TestStringConcatenation3{ public static void main(String ar gs[]){ String s1="Sachin "; String s2="Tendulkar"; String s3=s1.concat(s2); System.out.println(s3);//Sachin Tendulkar } }
  • 51. There are some other possible ways to concatenate Strings in Java, 1. String concatenation using StringBuilder class • StringBuilder is class provides append() method to perform concatenation operation. The append() method accepts arguments of different types like Objects, StringBuilder, int, char, CharSequence, boolean, float, double. public class StrBuilder { /* Driver Code */ public static void main(String args[]) { StringBuilder s1 = new StringBuilder("H ello"); //String 1 StringBuilder s2 = new StringBuilder(" World"); //String 2 StringBuilder s = s1.append(s2); //Strin g 3 to store the result System.out.println(s.toString()); //Dis plays result } }
  • 52. 2. String concatenation using format() method • String.format() method allows to concatenate multiple strings using format specifier like %s followed by the string values or objects. public class StrFormat { /* Driver Code */ public static void main(String args[ ]) { String s1 = new String("Hello"); //String 1 String s2 = new String(" World"); //String 2 String s = String.format("%s%s",s 1,s2); //String 3 to store the result System.out.println(s.toString()); //Displays result } }
  • 53. Substring in Java • A part of String is called substring. In other words, substring is a subset of another String. Java String class provides the built-in substring() method that extract a substring from the given string by using the index values passed as an argument. In case of substring() method startIndex is inclusive and endIndex is exclusive. 1.public String substring(int startIndex): This method returns new String object containing the substring of the given string from specified startIndex (inclusive). The method throws an IndexOutOfBoundException when the startIndex is larger than the length of String or less than zero. 2.public String substring(int startIndex, int endIndex): This method returns new String object containing the substring of the given string from specified startIndex to endIndex. The method throws an IndexOutOfBoundException when the startIndex is less than zero or startIndex is greater than endIndex or endIndex is greater than length of String.
  • 54. Using String.split() method: The split() method of String class can be used to extract a substring from a sentence. It accepts arguments in the form of a regular expression. Output: Hello, My name is Sachin import java.util.*; public class TestSubstring2 { /* Driver Code */ public static void main(String args[]) { String text= new String("Hello, My name is Sachin"); /* Splits the sentence by the delimeter passed as an argument */ String[] sentences = text.split("s"); for(String w:sentences){ System.out.println(w); } } }
  • 55. Java String Class Methods The java.lang.String class provides a lot of built-in methods that are used to manipulate string in Java. • Java String toUpperCase() and toLowerCase() method Output: SACHIN sachin Sachin public class Stringoperation1 { public static void main(String ar[]) { String s="Sachin"; System.out.println(s.toUpperCase());//S ACHIN System.out.println(s.toLowerCase());//s achin System.out.println(s);//Sachin(no chang e in original) } }
  • 56. Java String trim() method The String class trim() method eliminates white spaces before and after the String. Stringoperation2.java public class Stringoperation2 { public static void main(String ar[]) { String s=" Sachin "; System.out.println(s);// Sachin System.out.println(s.trim());//Sachin } } Output: Sachin Sachin
  • 57. Java String startsWith() and endsWith() method The method startsWith() checks whether the String starts with the letters passed as arguments and endsWith() method checks whether the String ends with the letters passed as arguments. public class Stringoperation3 { public static void main(String ar[]) { String s="Sachin"; System.out.println(s.startsWith("Sa"));//true System.out.println(s.endsWith("n"));//true } } true true
  • 58. Java String charAt() Method The String class charAt() method returns a character at specified index. public class Stringoperation4 { public static void main(String ar[]) { String s="Sachin"; System.out.println(s.charAt(0));//S System.out.println(s.charAt(3));//h } } Output: S h
  • 59. Java String length() Method The String class length() method returns length of the specified String. public class Stringoperation5 { public static void main(String ar[]) { String s="Sachin"; System.out.println(s.length());//6 } }
  • 60. Java StringBuffer Class • Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class in Java is the same as String class except it is mutable i.e. it can be changed. Constructor Description StringBuffer() It creates an empty String buffer with the initial capacity of 16. StringBuffer(String str) It creates a String buffer with the specified string.. StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length. Important Constructors of StringBuffer Class
  • 61. public synchronized StringBuffer append(String s) It is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc. public synchronized StringBuffer insert(int offset, String s) It is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc. public synchronized StringBuffer replace(int startIndex, int endIndex, String str) It is used to replace the string from specified startIndex and endIndex. public synchronized StringBuffer delete(int startIndex, int endIndex) It is used to delete the string from specified startIndex and endIndex. public synchronized StringBuffer reverse() is used to reverse the string.
  • 62. public int capacity() It is used to return the current capacity. public void ensureCapacity(int minimumCapacity) It is used to ensure the capacity at least equal to the given minimum. public char charAt(int index) It is used to return the character at the specified position. public int length() It is used to return the length of the string i.e. total number of characters. public String substring(int beginIndex) It is used to return the substring from the specified beginIndex. public String substring(int beginIndex, int endIndex) It is used to return the substring from the specified beginIndex and endIndex.
  • 63. What is a mutable String? A String that can be modified or changed is known as mutable String. StringBuffer and StringBuilder classes are used for creating mutable strings. 1) StringBuffer Class append() Method The append() method concatenates the given argument with this String. class StringBufferExample{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello "); sb.append("Java");//now original string is changed System.out.println(sb);//prints Hello Java } } Output: Hello Java
  • 64. 2) StringBuffer insert() Method The insert() method inserts the given String with this string at the given position. class StringBufferExample2{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello "); sb.insert(1,"Java");//now original string is changed System.out.println(sb);//prints HJavaello } } Output: HJavaello
  • 65. 3) StringBuffer replace() Method The replace() method replaces the given String from the specified beginIndex and endIndex. class StringBufferExample3{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello"); sb.replace(1,3,"Java"); System.out.println(sb);//prints HJavalo } } Output: HJavalo
  • 66. StringBuffer reverse() Method The reverse() method of the StringBuilder class reverses the current String. class StringBufferExample5{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello"); sb.reverse(); System.out.println(sb);//prints olleH } } Output olleH
  • 67. Java StringBuilder Class 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 Constructor Description StringBuilder() It creates an empty String Builder with the initial capacity of 16. StringBuilder(String str) It creates a String Builder with the specified string. StringBuilder(int length) It creates an empty String Builder with the specified capacity as length.
  • 68. Important methods of StringBuilder class Method Description public StringBuilder append(String s) It is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc. public StringBuilder insert(int offset, String s) It is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc. public StringBuilder replace(int startIndex, int endIndex, String str) It is used to replace the string from specified startIndex and endIndex. public StringBuilder delete(int startIndex, int It is used to delete the string from specified startIndex and endIndex.
  • 69. public StringBuilder reverse() It is used to reverse the string. public int capacity() It is used to return the current capacity. public void ensureCapacity(int minimumCapacity) It is used to ensure the capacity at least equal to the given minimum. public char charAt(int index) It is used to return the character at the specified position. public int length() It is used to return the length of the string i.e. total number of characters. public String substring(int beginIndex) It is used to return the substring from the specified beginIndex. public String substring(int beginIndex, int endIndex) It is used to return the substring from the specified beginIndex and endIndex.
  • 70. StringBuilder append() method The StringBuilder append() method concatenates the given argument with this String. class StringBuilderExample{ public static void main(String args[]){ StringBuilder sb=new StringBuilder("Hello "); sb.append("Java");//now original string is changed System.out.println(sb);//prints Hello Java } } Output: Hello Java
  • 71. StringBuilder insert() method class StringBuilderExample2{ public static void main(String args[]){ StringBuilder sb=new StringBuilder("Hello "); sb.insert(1,"Java");//now original string is changed System.out.println(sb);//prints HJavaello } } Output: HJavaello
  • 72. StringBuilder replace() method class StringBuilderExample3{ public static void main(String args[]){ StringBuilder sb=new StringBuilder("Hello"); sb.replace(1,3,"Java"); System.out.println(sb);//prints HJavalo } } Output: HJavalo
  • 73. Difference between String and StringBuffer No. String StringBuffer 1) The String class is immutable. The StringBuffer class is mutable. 2) String is slow and consumes more memory when we concatenate too many strings because every time it creates new instance. StringBuffer is fast and consumes less memory when we concatenate t strings. 3) String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method. StringBuffer class doesn't override the equals() method of Object class. 4) String class is slower while performing concatenation operation. StringBuffer class is faster while performing concatenation operation. 5) String class uses String constant pool. StringBuffer uses Heap memory
  • 74. Difference between StringBuffer and StringBuilder N o. StringBuffer StringBuilder 1) StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously. StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously. 2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer. 3) StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5
  • 75. Type Conversion and Casting • If the two types are compatible, then Java will perform the conversion automatically. For example, it is always possible to assign an int value to a long variable. • However, not all types are compatible, and thus, not all type conversions are implicitly allowed. • For instance, there is no automatic conversion defined from double to byte. still possible to obtain a conversion between incompatible types. • cast, performs an explicit conversion between incompatible types.
  • 76. Java’s Automatic Conversions • When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met: • The two types are compatible. • The destination type is larger than the source type. When these two conditions are met, a widening conversion takes place the int type is always large enough to hold all valid byte values, so no explicit cast statement is required.
  • 77. 1. For widening conversions, the numeric types, including integer and floating-point types, are compatible with each other. 2. However, there are no automatic conversions from the numeric types to char or boolean. 3. char and boolean are not compatible with each other. Casting Incompatible Types: if you want to assign an int value to a byte variable? 1. This conversion will not be performed automatically, because a byte is smaller than an int. 2. This kind of conversion is sometimes called a narrowing conversion, since you are explicitly making the value narrower so that it will fit into the target type.
  • 78. • To create a conversion between two incompatible types, use cast. • A cast is simply an explicit type conversion (target-type) value int a; byte b; // ... b = (byte) a; A different type of conversion will occur when a floating-point value is assigned to an integer type: truncation. if the value 1.23 is assigned to an integer, the resulting value will simply be 1.
  • 79. Type conversions that require casts class Conversion { public static void main(String args[]) { byte b; int i = 257; double d = 323.142; System.out.println("nConversion of int to byte."); b = (byte) i; System.out.println("i and b " + i + " " + b); System.out.println("nConversion of double to int."); i = (int) d; System.out.println("d and i " + d + " " + i); System.out.println("nConversion of double to byte."); b = (byte) d; System.out.println("d and b " + d + " " + b); } } This program generates the following output: Conversion of int to byte. i and b 257 1 Conversion of double to int. d and i 323.142 323 Conversion of double to byte. d and b 323.142 67
  • 80. Automatic Type Promotion in Expressions byte a = 40; byte b = 50; byte c = 100; int d = a * b / c; intermediate term a * b easily exceeds the range of either of its byte operands • Java automatically promotes each byte, short, or char operand to int when evaluating an expression. This means that the subexpression a * b is performed using integers—not bytes. Thus, 2,000, the result of the intermediate expression, 50 * 40, is legal even though a and b are both specified as type byte. byte b = 50; B = b * 2; // Error! Cannot assign an int to a byte! 50 * 2, a perfectly valid byte value, back into a byte variable. However, because the operands were automatically promoted to int the result has also been promoted to int but type int, cannot be assigned to a byte without the use of a cast. byte b = 50; b = (byte)(b * 2);
  • 81. Operators: Java provides a rich operator environment. Most of its operators can be divided into the following four groups: arithmetic, bitwise, relational, and logical. Arithmetic Operators :Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. Operator Result + Addition – Subtraction (also unary minus) * Multiplication / Division % Modulus ++ Increment += Addition assignment –= Subtraction assignment *= Multiplication assignment /= Division assignment %= Modulus assignment – – Decrement += compound assignment operator.
  • 82. The Basic Arithmetic Operators • The basic arithmetic operations—addition, subtraction, multiplication, and division— all behave as you would expect for all numeric types. • The minus operator also has a unary form that negates its single operand. The Modulus Operator int x = 42; double y = 42.25; System.out.println("x mod 10 = " + x % 10); System.out.println("y mod 10 = " + y % 10); Output: x mod 10 = 2 y mod 10 = 2.25
  • 83. • Arithmetic Compound Assignment Operators • a = a + 4; • In Java, you can rewrite this statement as shown here: • a += 4; • Increment and Decrement
  • 84. The Bitwise Operators: Java defines several bitwise operators that can be applied to the integer types, long, int, short, char, and byte. 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
  • 85. The Bitwise Logical Operators: The bitwise logical operators are &, |, ^, and ~.
  • 86. The Bitwise 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 • The Bitwise 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
  • 87. The Left Shift value << num class ByteShift { public static void main(String args[]) { byte a = 64, b; int i; i = a << 2; b = (byte) (a << 2); System.out.println("Original value of a: " + a); System.out.println("i and b: " + i + " " + b); } } • The output generated by this program is shown here: • Original value of a: 64 • i and b: 256 0
  • 88. Relational Operators: The relational operators determine the relationship that one operand has to the other. Operator Result == Equal to != Not equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to int a = 4; int b = 1; boolean c = a < b;
  • 89. Boolean Logical Operators: The Boolean logical operators shown here operate only on boolean operands & Logical AND | Logical OR ^ Logical XOR (exclusive OR) || Short-circuit OR && Short-circuit AND ! Logical unary NOT &= AND assignment |= OR assignment ^= XOR assignment == Equal to != Not equal to ?: Ternary if-then-else
  • 90. In Java logical operators, if the evaluation of a logical expression exits in between before complete evaluation, then it is known as Short-circuit. • A short circuit happens because the result is clear even before the complete evaluation of the expression, and the result is returned. Short circuit evaluation avoids unnecessary work and leads to efficient processing. 1. AND(&&) short circuit: In the case of AND, the expression is evaluated until we get one false result because the result will always be false, independent of the further conditions. If there is an expression with &&(logical AND), and the first operand itself is false, then a short circuit occurs, the further expression is not evaluated, and false is returned.
  • 91. //Short-circuiting using AND(&&) operator. import java.io.*; class ShortCirAND { public static void main(String arg[]) { if (false && true && true) { System.out.println("This output " + "will not " + "be printed"); } else { System.out.println("This output " + "got printed actually, " + " due to short circuit"); } if (true && true && true) { System.out.println("This output " + "gets print" + " as there will be" + " no Short circuit"); } else { System.out.println("This output " + "will not " + "be printed"); } } } Output This output got printed actually, due to short circuit This output gets print as there will be no Short circuit
  • 92. //OR(||) short circuit: class ShortCirOR { public static void main(String arg[]) { if (true || false || false) { System.out.println("This output " + "got printed actually, " + " due to short circuit"); } else { System.out.println("This output " + "will not " + "be printed"); } if (false || false || true) { System.out.println("This output " + "gets print" + " as there will be" + " no Short circuit"); } else { System.out.println("This output " + "will not " + "be printed"); } } } Output This output got printed actually, due to short circuit This output gets print as there will be no Short circuit
  • 93. The Assignment Operator int x, y, z; x = y = z = 100; // set x, y, and z to 100 The ? Operato expression1 ? expression2 : expression3 class Ternary { public static void main(String args[]) { int i, k; i = 10; k = i < 0 ? -i : i; // get absolute value of i System.out.print("Absolute value of "); System.out.println(i + " is " + k); i = -10; k = i < 0 ? -i : i; // get absolute value of i System.out.print("Absolute value of "); System.out.println(i + " is " + k); } } The output generated by the program is shown here: Absolute value of 10 is 10 Absolute value of -10 is 10
  • 94. Wrapper classes in Java • The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive. • Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into primitives automatically. • The automatic conversion of primitive into an object is known as autoboxing and vice-versa unboxing.
  • 95. Use of Wrapper classes in Java: Java is an object-oriented programming language, so we need to deal with objects many times like in Collections, Serialization, Synchronization, etc. 1. Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it will not change the original value. But, if we convert the primitive value in an object, it will change the original value. 2. Serialization: We need to convert the objects into streams to perform the serialization. If we have a primitive value, we can convert it in objects through the wrapper classes. 3. Synchronization: Java synchronization works with objects in Multithreading. 4. java.util package: The java.util package provides the utility classes to deal with objects. 5. Collection Framework: Java collection framework works with objects only. All classes of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.
  • 96. The eight classes of the java.lang package are known as wrapper classes in Java. Primitive Type Wrapper class boolean Boolean char Character byte Byte short Short int Integer long Long float Float double Double
  • 97. Autoboxing • The automatic conversion of primitive data type into its corresponding wrapper class is known as autoboxing. • For example, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to Boolean, double to Double, and short to Short. Output: 20 20 20 Wrapper class Example: Primitive to Wrapper public class WrapperExample1{ public static void main(String ar gs[]){ //Converting int into Integer int a=20; Integer i=Integer.valueOf(a);//con verting int into Integer explicitly Integer j=a;//autoboxing, now co mpiler will write Integer.valueOf(a ) internally System.out.println(a+" "+i+" "+j);
  • 98. Unboxing • The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing. It is the reverse process of autoboxing. Output: 3 3 3 • Wrapper class Example: Wrapper to Primitive public class WrapperExample2{ public static void main(String args[]){ //Converting Integer to int Integer a=new Integer(3); int i=a.intValue();//converting Integer to i nt explicitly int j=a;//unboxing, now compiler will writ e a.intValue() internally System.out.println(a+" "+i+" "+j); }}
  • 99. Class Fundamentals 1. Perhaps the most important thing to understand about a class is that it defines a new data type. 2. Once defined, this new type can be used to create objects of that type. 3. Thus, a class is a template for an object, and an object is an instance of a class. Because an object is an instance of a class, you will often see the two words object and instance used interchangeably When you define a class, you declare its exact form and nature. 4. You do this by specifying the data that it contains and the code that operates on that data. 5. While very simple classes may contain only code or only data, most real-world classes contain both. As you will see, a class’ code defines the interface to its data.
  • 100. class classname { type instance-variable1; type instance-variable2; // ... type instance-variableN; type methodname1(parameter-list) { // body of method } type methodname2(parameter-list) { // body of method } // ... type methodnameN(parameter-list) { // body of method } } • The data, or variables, defined within a class are called instance variables. • The code is contained within methods. Collectively, the methods and variables defined within a class are called members of the class. • In most classes, the instance variables are acted upon and accessed by the methods defined for that class. • Thus, as a general rule, it is the methods that determine how a class’ data can be used.
  • 101. 1. Variables defined within a class are called instance variables because each instance of the class (that is, each object of the class) contains its own copy of these variables. 2. Thus, the data for one object is separate and unique from the data for another. 3. All methods have the same general form as main(), which we have been using thus far. 4. However, most methods will not be specified as static or public. class Box { double width; double height; double depth; } • Here is a class called Box that defines three instance variables: width, height, and depth. Box mybox = new Box(); // create a Box object called mybox • mybox will be an instance of Box. each time you create an instance of a class, you are creating an object that contains its own copy of each instance variable defined by the class. every Box object will contain its own copies of the instance variables width, height, and depth • To access these variables, you will use the dot (.) operator. The dot operator links the name of the object with the name of an instance variable. • mybox.width = 100;
  • 102. class Box { double width; double height; double depth; } class BoxDemo { public static void main(String args[]) { Box mybox = new Box(); double vol; mybox.width = 10; mybox.height = 20; mybox.depth = 15; vol = mybox.width * mybox.height * mybox.depth; System.out.println("Volume is " + vol); } }
  • 103. • Refere BoxDemo Example • You should call the file that contains this program BoxDemo.javabecause the main( ) method is in the class called BoxDemo, not the class called Box. • When you compile this program, you will find that two .class files have been created, one for Box and one for BoxDemo. • The Java compiler automatically puts each class into its own .class file. It is not necessary for both the Box and the BoxDemo class to actually be in the same source file. • You could put each class in its own file, called Box.java and BoxDemo.java, respectively. • As stated earlier, each object has its own copies of the instance variables. This means that if you have two Box objects, each has its own copy of depth, width, and height. • It is important to understand that changes to the instance variables of one object have no effect on the instance variables of another. • Refer BoxDemo2 Example • As you can see, mybox1’s data is completely separate from the data contained in mybox2.
  • 104. class Box { double width; double height; double depth; } class BoxDemo2 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; / * assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // compute volume of first box vol = mybox1.width * mybox1.height * mybox1.depth; System.out.println("Volume is " + vol); // compute volume of second box vol = mybox2.width * mybox2.height * mybox2.depth; System.out.println("Volume is " + vol); } }
  • 105. Declaring Objects 1. Obtaining objects of a class is a two-step process. First, you must declare a variable of the class type. 2. This variable does not define an object. 3. Instead, it is simply a variable that can refer to an object. Second, you must acquire an actual, physical copy of the object and assign it to that variable. 4. You can do this using the new operator. The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns a reference to it. 5. This reference is, more or less, the address in memory of the object allocated by new. 6. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated. 7. Box mybox = new Box(); or; Box mybox; // declare reference to object mybox = new Box(); // allocate a Box object
  • 106. • The first line declares mybox as a reference to an object of type Box. • After this line executes, mybox contains the value null, which indicates that it does not yet point to an actual object. • Any attempt to use mybox at this point will result in a compile-time error. • The next line allocates an actual object and assigns a reference to it to mybox. After the second line executes, you can use mybox as if it were a Box object. • But in reality, mybox simply holds the memory address of the actual Box object.
  • 107. Assigning Object Reference Variables Box b1 = new Box(); Box b2 = b1; • You might think that b2 is being assigned a reference to a copy of the object referred to by b1. • That is, you might think that b1 and b2 refer to separate and distinct objects. • However, this would be wrong. Instead, after this fragment executes, b1 and b2 will both refer to the same object. • The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. • It simply makes b2 refer to the same object as does b1. Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they are the same object.
  • 108. • Although b1 and b2 both refer to the same object, they are not linked in any other way. • For example, a subsequent assignment to b1 will simply unhook b1 from the original object without affecting the object or affecting b2. For example: Box b1 = new Box(); Box b2 = b1; b1 = null; • Here, b1 has been set to null, but b2 still points to the original object.
  • 109. Introducing Methods: classes usually consist of two things: instance variables and methods This is the general form of a method: type name(parameter-list) { // body of method } Adding a Method to the Box Class class Box { double width; double height; double depth; void volume() { System.out.print("Volume is "); System.out.println(width * height * depth); } } class BoxDemo3 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // display volume of first box mybox1.volume(); // display volume of second box mybox2.volume(); } }
  • 110. Returning a Value class Box { double width; double height; double depth; // compute and return volume double volume() { return width * height * depth; } } class BoxDemo4 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } }
  • 111. Adding a Method That Takes Parameters // This program uses a parameterized method. class Box { double width; double height; double depth; // compute and return volume double volume() { return width * height * depth; } // sets dimensions of box void setDim(double w, double h, double d) { width = w; height = h; depth = d; } } class BoxDemo5 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // initialize each box mybox1.setDim(10, 20, 15); mybox2.setDim(3, 6, 9); // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } }
  • 112. Constructors 1. It can be tedious to initialize all of the variables in a class each time an instance is created. 2. Even when you add convenience functions like setDim( ), it would be simpler and more concise to have all of the setup done at the time the object is first created. 3. Because the requirement for initialization is so common, Java allows objects to initialize themselves when they are created. 4. This automatic initialization is performed through the use of a constructor. 1. A constructor initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically similar to a method. 2. Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes. 3. Constructors look a little strange because they have no return type, not even void. 4. This is because the implicit return type of a class’ constructor is the class type itself. 5. It is the constructor’s job to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object immediately
  • 113. class Box { double width; double height; double depth; // This is the constructor for Box. Box() { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } // compute and return volume double volume() { return width * height * depth; } } class BoxDemo6 { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } } Output: Constructing Box Constructing Box Volume is 1000.0 Volume is 1000.0
  • 114. Parameterized Constructors While the Box( ) constructor in the preceding example does initialize a Box object, it is not very useful—all boxes have the same dimensions. What is needed is a way to construct Box objects of various dimensions. The easy solution is to add parameters to the constructor class Box { double width; double height; double depth; // This is the constructor for Box. Box(double w, double h, double d) { width = w; height = h; depth = d; } // compute and return volume double volume() { return width * height * depth; } } class BoxDemo7 { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(3, 6, 9); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } } Volume is 3000.0 Volume is 162.0
  • 115. The this Keyword • Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. this can be used inside any method to refer to the current object. • That is, this is always a reference to the object on which the method was invoked. • You can use this anywhere a reference to an object of the current class’ type is permitted. // A redundant use of this. Box(double w, double h, double d) { this.width = w; this.height = h; this.depth = d; } This version of Box( ) operates exactly like the earlier version. The use of this is redundant, but perfectly correct. Inside Box( ), this will always refer to the invoking object. While it is redundant in this case, this is useful in other contexts, one of which is explained in the next section.
  • 116. Instance Variable Hiding • It is illegal in Java to declare two local variables with the same name inside the same or enclosing scopes. Interestingly, you can have local variables, including formal parameters to methods, which overlap with the names of the class’ instance variables. • However, when a local variable has the same name as an instance variable, the local variable hides the instance variable. This is why width, height, and depth were not used as the names of the parameters to the Box( ) constructor inside the Box class. • If they had been, then width would have referred to the formal parameter, hiding the instance variable width. While it is usually easier to simply use different names, there is another way around this situation. • Because this lets you refer directly to the object, you can use it to resolve any name space collisions that might occur between instance variables and local variables. • For example, here is another version of Box( ), which uses width, height, and depth for parameter names and then uses this to access the instance variables by the same name: Box(double width, double height, double depth) { this.width = width; this.height = height; this.depth = depth; }
  • 117. Garbage Collection • Since objects are dynamically allocated by using the new operator, you might be wondering • how such objects are destroyed and their memory released for later reallocation. In some • languages, such as C++, dynamically allocated objects must be manually released by use of • a delete operator. Java takes a different approach; it handles deallocation for you automatically. • The technique that accomplishes this is called garbage collection. • It works like this: when no • references to an object exist, that object is assumed to be no longer needed, and the memory • occupied by the object can be reclaimed. There is no explicit need to destroy objects as in C++. • Garbage collection only occurs sporadically (if at all) during the execution of your program. • It will not occur simply because one or more objects exist that are no longer used. Furthermore, • different Java run-time implementations will take varying approaches to garbage collection, • but for the most part, you should not have to think about it while writing your programs.
  • 118. The finalize( ) Method Sometimes an object will need to perform some action when it is destroyed. For example, if an object is holding some non-Java resource such as a file handle or character font, then you might want to make sure these resources are freed before an object is destroyed. To handle such situations, Java provides a mechanism called finalization. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector. To add a finalizer to a class, you simply define the finalize( ) method. The Java run time calls that method whenever it is about to recycle an object of that class. Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed. The garbage collector runs periodically, checking for objects that are no longer referenced by any running state or indirectly through other referenced objects. Right before an asset is freed, the Java run time calls the finalize( ) method on the object. The finalize( ) method has this general form: protected void finalize( ) { // finalization code here } It is important to understand that finalize( ) is only called just prior to garbage collection. It is not called when an object goes out-of-scope, for example. This means that you cannot know when—or even if—finalize( ) will be executed. Therefore, your program should provide other means of releasing system resources, etc., used by the object. It must not rely on finalize( ) for normal program operation.
  • 119. A Stack Class: one of the archetypal examples of encapsulation: the stack. A stack stores data using first-in, last- out ordering. That is, a stack is like a stack of plates on a table—the first plate put down on the table is the last plate to be used. Stacks are controlled through two operations traditionally called push and pop. To put an item on top of the stack, you will use push. To take an item off the stack, you will use pop. class Stack { int stck[] = new int[10]; int tos; Stack() { tos = -1; } void push(int item) { if(tos==9) System.out.println("Stack is full."); else stck[++tos] = item; } int pop() { if(tos < 0) { System.out.println("Stack underflow."); return 0; } else return stck[tos--]; } } class TestStack { public static void main(String args[]) { Stack mystack1 = new Stack(); Stack mystack2 = new Stack(); for(int i=0; i<10; i++) mystack1.push(i); for(int i=10; i<20; i++) mystack2.push(i); System.out.println("Stack in mystack1:"); for(int i=0; i<10; i++) System.out.println(mystack1.pop()); System.out.println("Stack in mystack2:"); for(int i=0; i<10; i++) System.out.println(mystack2.pop()); } }
  • 120. This program generates the following output: Stack in mystack1: 9 8 7 6 5 4 3 2 1 0 Stack in mystack2: 19 18 17 16 15 14 13 12 11 10
  • 121. Overloading Methods • In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. • When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. • Method overloading is one of the ways that Java supports polymorphism. • If you have never used a language that allows the overloading of methods, then the concept may seem strange at first. • When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call. • Thus, overloaded methods must differ in the type and/or number of their parameters. • While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method. When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call.
  • 122. class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } } This program generates the following output: No parameters a: 10 a and b: 10 20 double a: 123.25 Result of ob.test(123.25): 15190.5625
  • 123. Overloading Constructors: overloading normal methods, you can also overload constructor methods class Box { double width; double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d;} Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box} Box(double len) { width = height = depth = len; double volume() { return width * height * depth;}} class OverloadCons { public static void main(String args[]) { Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); } Volume of mybox1 is 3000.0 Volume of mybox2 is -1.0 Volume of mycube is 343.0
  • 124. Using Objects as Parameters: So far, we have only been using simple types as parameters to methods. However, it is both correct and common to pass objects to methods. For example, consider the following short program: class Test { int a, b; Test(int i, int j) { a = i; b = j; } boolean equals(Test o) { if(o.a == a && o.b == b) return true; else return false; } } class PassOb { public static void main(String args[]) { Test ob1 = new Test(100, 22); Test ob2 = new Test(100, 22); Test ob3 = new Test(-1, -1); System.out.println("ob1 == ob2: " + ob1.equals(ob2)); System.out.println("ob1 == ob3: " + ob1.equals(ob3)); } } This program generates the following output: ob1 == ob2: true ob1 == ob3: false
  • 125. class Box { double width; double height; double depth; Box(Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth;} Box(double w, double h, double d) { width = w; height = h; depth = d;} Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box} Box(double len) { width = height = depth = len;} double volume() { return width * height * depth;}} class OverloadCons2 { public static void main(String args[]) { Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); Box myclone = new Box(mybox1); // create copy of mybox1 double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); vol = mycube.volume(); System.out.println("Volume of cube is " + vol); vol = myclone.volume(); System.out.println("Volume of clone is " + vol);} } Here, Box allows one object to initialize another.
  • 126. Introducing Access Control • As you know, encapsulation links data with the code that manipulates it. However, encapsulation provides another important attribute: access control. • Through encapsulation, you can control what parts of a program can access the members of a class. By controlling access, you can prevent misuse. Java’s access specifiers are public, private, and protected. Java also defines a default access level. protected applies only when inheritance is involved. • The other access specifiers are described next. When a member of a class is modified by the public specifier, then that member can be accessed by any other code. When a member of a class is specified as private, then that member can only be accessed by other members ofits class. • Now you can understand why main( ) has always been preceded by the publics pecifier. It is called by code that is outside the program—that is, by the Java run-timesystem. When no access specifier is used, then by default the member of a class is publicwithin its own package, but cannot be accessed outside of its package. (Packages arediscussed in the following chapter.)
  • 127. In the classes developed so far, all members of a class have used the default access mode, which is essentially public. However, this is not what you will typically want to be the case. Usually, you will want to restrict access to the data members of a class—allowing access only through methods. Also, there will be times when you will want to define methods that are private to a class. This program demonstrates the difference between public and private. class Test { int a; // default access public int b; // public access private int c; // private access // methods to access c void setc(int i) { // set c's value c = i; } int getc() { // get c's value return c;} } class AccessTest { public static void main(String args[]) { Test ob = new Test(); // These are OK, a and b may be accessed directly ob.a = 10; ob.b = 20; // This is not OK and will cause an error // ob.c = 100; // Error! // You must access c through its methods ob.setc(100); // OK System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc()); } }
  • 128. Understanding static • There will be times when you will want to define a class member that will be used independently of any object of that class. Normally, a class member must be accessed only in conjunction with an object of its class. • However, it is possible to create a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword static. • When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. You can declareboth methods and variables to be static. • The most common example of a static member ismain( ).main( ) is declared as static because it must be called before any objects exist. Instance variables declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable. Methods declared as static have several restrictions: 1. They can only call other static methods. 2. They must only access static data. 3. They cannot refer to this or super in any way. (The keyword super relates to inheritance and is described in the next chapter.) If you need to do computation in order to initialize your static variables, you can declare a static block that gets executed exactly once, when the class is first loaded. The following example shows a class that has a static method, some static variables, and a static initialization block:
  • 129. // Demonstrate static variables, methods, and blocks. class UseStatic { static int a = 3; static int b; static void meth(int x) {System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static { System.out.println("Static block initialized."); b = a * 4; } public static void main(String args[]) { meth(42); } } 1. As soon as the UseStatic class is loaded, all of the static statements are run. 2. First, a is set to 3, then the static block executes, which prints a message and then initializes b to a * 4 or 12. 3. Then main( ) is called, which calls meth( ), passing 42 to x. 4. The three println( ) statements refer to the two static variables a and b, as well as to the local variable x. Here is the output of the program: Static block initialized. x = 42 a = 3 b = 12 Outside of the class in which they are defined, static methods and variables can be used independently of any object. To do so, you need only specify the name of their class followed by the dot operator. For example, if you wish to call a static method from outside its class, you can do so using the following general form: classname.method( )
  • 130. • Here, classname is the name of the class in which the static method is declared. • As you can see, this format is similar to that used to call non-static methods through object-reference variables. • A static variable can be accessed in the same way— by use of the dot operator on the name of the class. • This is how Java implements a controlled version of global methods and global variables. • Inside main( ), the static method callme( ) and the static variable b are accessed through their class name StaticDemo. class StaticDemo { static int a = 42; static int b = 99; static void callme() { System.out.println("a = " + a); } } class StaticByName { public static void main(String args[]) { StaticDemo.callme(); System.out.println("b = " + StaticDemo.b); } } Here is the output of this program: a = 42 b = 99
  • 131. Introducing final • A variable can be declared as final. Doing so prevents its contents from being modified. • This means that you must initialize a final variable when it is declared. • For example: final int FILE_NEW = 1; final int FILE_OPEN = 2; final int FILE_SAVE = 3; final int FILE_SAVEAS = 4; final int FILE_QUIT = 5; • Subsequent parts of your program can now use FILE_OPEN, etc., as if they were constants, without fear that a value has been changed. • It is a common coding convention to choose all uppercase identifiers for final variables. Variables declared as final do not occupy memory on a per- instance basis. • Thus, a final variable is essentially a constant. The keyword final can also be applied to methods, but its meaning is substantially different than when it is applied to variables. • This second usage of final is described in the next chapter, when inheritance is described.
  • 132. Nested and Inner Classes • It is possible to define a class within another class; such classes are known as nested classes. • The scope of a nested class is bounded by the scope of its enclosing class. • Thus, if class B is defined within class A, then B does not exist independently of A. • A nested class has access to the members, including private members, of the class in which it is nested. • However, the enclosing class does not have access to the members of the nested class. • A nested class that is declared directly within its enclosing class scope is a member of its enclosing class. • It is also possible to declare a nested class that is local to a block. • There are two types of nested classes: static and non-static. • A static nested class is one that has the static modifier applied. Because it is static, it must access the members of its enclosing class through an object. • That is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used. • The most important type of nested class is the inner class. • An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do.
  • 133. The class named Outer has one instance variable named outer_x, one instance method named test( ), and defines one inner class called Inner. // Demonstrate an inner class. class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner.display(); } // this is an inner class class Inner { void display() { System.out.println("display: outer_x = " + outer_x); } } } class InnerClassDemo { public static void main(String args[]) { Outer outer = new Outer(); outer.test(); } } Output from this application is shown here: display: outer_x = 100
  • 134. • The main( ) method of InnerClassDemo creates an instance of class Outer and invokes its test( ) method. • That method creates an instance of class Inner and the display( ) method is called. It is important to realize that an instance of Inner can be created only within the scope of class Outer. • The Java compiler generates an error message if any code outside of class Outer attempts to instantiate class Inner. • (In general, an inner class instance must be created by an enclosing scope.) You can, however, create an instance of Inner outside of Outer by qualifying its name with Outer, as in Outer.Inner. • An inner class has access to all of the members of its enclosing class, but the reverse is not true. • Members of the inner class are known only within the scope of the inner class and may not be used by the outer class
  • 135. // This program will not compile. class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner.display(); } // this is an inner class class Inner { int y = 10; // y is local to Inner void display() { System.out.println("display: outer_x = " + outer_x); } } void showy() { System.out.println(y); // error, y not known here! } } class InnerClassDemo { public static void main(String args[]) { Outer outer = new Outer(); outer.test(); } } Here, y is declared as an instance varia
  • 136. • Although we have been focusing on inner classes declared as members within an outer class scope, it is possible to define inner classes within any block scope. • For example, you can define a nested class within the block defined by a method or even within the body of a for loop, as this next program shows. // Define an inner class within a for loop. class Outer { int outer_x = 100; void test() { for(int i=0; i<10; i++) { class Inner { void display() { System.out.println("display: outer_x = " + outer_x); } } Inner inner = new Inner(); inner.display(); }}} class InnerClassDemo { public static void main(String args[]) { Outer outer = new Outer(); outer.test(); The output from this version of the program is shown here. display: outer_x = 100 display: outer_x = 100 display: outer_x = 100 display: outer_x = 100 display: outer_x = 100 display: outer_x = 100 display: outer_x = 100 display: outer_x = 100 display: outer_x = 100 display: outer_x = 100 • While nested classes are not applicable to all stiuations, they are particularly helpful when handling events. We will return to the topic of nested classes in Chapter 22. • There you will see how inner classes can be used to simplify the code needed to handle certain types of events. • You will also learn about anonymous inner classes, which are inner classes that don’t have a name. • One final point: Nested classes were not allowed by the original 1.0 specification for Java.
  • 137. Java Singleton Class: Singleton Design Pattern in Java. Singleton is a design pattern that ensures that a class can only have one object. To create a singleton class, a class must implement the following properties: 1. Create a private constructor of the class to restrict object creation outside of the class. 2. Create a private attribute of the class type that refers to the single object. 3. Create a public static method that allows us to create and access the object we created. Inside the method, we will create a condition that restricts us from creating more than one object. class SingletonExample { // private field that refers to the object private static SingletonExample singleObject; private SingletonExample() { // constructor of the SingletonExample class } public static SingletonExample getInstance() { // write code that allows us to create only one object // access the object as per our need }} 1. private static SingletonExample singleObject - a reference to the object of the class. 2. private SingletonExample() - a private constructor that restricts creating objects outside of the class. 3. public static SingletonExample getInstance() - this method returns the reference to the only object of the class. Since the method static, it can be accessed using the class name.
  • 138. Use of Singleton in Java: Singletons can be used while working with databases. They can be used to create a connection pool to access the database while reusing the same connection for all the clients class Database { private static Database dbObject; private Database() { } public static Database getInstance() { // create object if it's not already created if(dbObject == null) { dbObject = new Database(); } // returns the singleton object return dbObject; } public void getConnection() { System.out.println("You are now connected to the database."); }} class Main { public static void main(String[] args) { Database db1; // refers to the only object of Database db1= Database.getInstance(); db1.getConnection();} } You are now connected to the database. 1. We have created a singleton class Database. 2. The dbObject is a class type field. This will refer to the object of the class Database. The private constructor Database() prevents object creation outside of the class. 3. The static class type method getInstance() returns the instance of the class to the outside world. In the Main class, we have class type variable db1. 4. We are calling getInstance() using db1 to get the only object of the Database. The method getConnection() can only be accessed using the object of the Database. 5. Since the Database can have only one object, all the clients can access the database through a single connection.