AshokIT Core Java
AshokIT Core Java
Ashok
Core Java
Material
By Mr. Ashok
1
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Chapter – 1
• Java Introduction
• Java Features
• Java Installation
• Java Program Execution Flow
• Java Programming Elements
• Java Programs Development
• Compilation
• Execution
• Translators
• JVM Architecture
2
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
What is Java
-> Java is a programming language
-> Java developed by James Gosling & his team in 1991 at Sun Microsystem Company
-> Initially they named it as ‘OAK’ programming language
-> In 1995, OAK language renamed to JAVA
Note: Oracle Corporation acquired Sun Microsystem in 2010. Now java is under license of
Oracle corporation
-> Java is a free & open-source software
-> 3 billion devices run on Java language
-> Java is one of the most popular languages in the world
-> Java can run on any platform (It is platform independent)
3
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
2) Platform Independent: Unlike other programming languages such as C, C++ etc which
are compiled into platform specific machines. Java is guaranteed to be write-once, run-
anywhere language.
When we compile java code it will generate bytecode. This bytecode is platform
independent and can be run on any machine, plus this bytecode format also provide
security. Any machine with Java Runtime Environment can run Java Programs.
4
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
5
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
➔ After installing java, we can see below two folders (JDK & JRE)
Note: After installing java software, we need to set PATH for java software to use it.
Step-2) Set Path for Java
-> Go To Environment Variables
-> Go To System Environment Variables
-> Edit Path
-> Add path up to JDK bin directory
6
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Step-3) Verify PATH Setup (Open command prompt and execute below command)
Note: If you are getting message like above that means, java installation and PATH setup is
success.
Step-1: We will write source code and we will save that code in a file using .java extension
Step-2: We will compile source code using java compiler (it will generate byte code)
Step-3: We will execute .class file ( JVM will convert byte code into machine code & gives
output)
7
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
-> Package statement is used to group our classes. At most we can write only one package
statement in one java program and package statement should be the first statement in the
program.
-> Import statements are used to import one program into another program. We can write
multiple import statements in one program (It depends on requirement). We should write
import statements after package statement only.
-> Class is the most import part in java program. Class is a plan to define program elements.
Inside class we will write variables and methods.
-> Variables are used to store the data. We can write any no. of variables inside a class.
-> Methods are used to perform action. Application business logic we will write inside
methods. A can class can have any no. of methods.
Developing First Java Program
Step-1: Open any text editor (notepad / notepad ++ / edit plus)
Step-2: Write below java program
8
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
➔ We are able to see .class file that means our program compilation is successful.
-> We are able to see “Welcome To Ashok IT” as output of our program that means our
program executed successfully.
Note: In Realtime, we will use IDE to develop java programs/ project.
9
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Translators
-> Translators are used to convert from one format to another format
-> We have 3 types of translators
1) Interpreter
2) Compiler
3) Assembler
-> Interpreter will convert the program line by line (performance is slow)
-> Compiler will convert all the lines of program at a time (performance is fast)
-> Assembler is used to convert assembler programming languages into machine language
JVM
-> JVM stands for Java Virtual Machine (We can't see with our eyes)
-> JVM will be part of JRE software
-> JVM is responsible for executing java programs
-> JVM will allocate memory required for program execution & de-allocate memory when it
is not used
-> JVM will convert byte code into machine understandable format
JVM Architecture
10
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
11
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Chapter - 2
• Variables
• Data Types
• Identifiers & Rules
• Reserved Words
• Java Coding Standards
• Java comments
• Reading Data From keyboard
12
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Variables
-> variables are used to store the data during program execution
-> We need to specify type of the variable to store the data
-> To specify type of data we will use 'data types'
-> To declare the variable in Java, we can use following syntax
Data types
-> Data types are used to specify type of the data
-> Data types are divided into 2 categories
1) Primitive Data Types
2) Non-Primitive Data Types
13
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Once a primitive data type has been declared its type can never change, although in most
cases its value can change. These eight primitive types can be put into four groups.
14
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
15
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Identifiers in Java
All Java components require names. Name used for classes, methods, interfaces and
variables are called Identifier.
Identifier must follow some rules. Here are the rules:
Rule-1 : The only allowed characters in java identifiers are:
➔ a to z
➔ A to Z
➔ 0 to 9
➔ $
➔ _ (underscore)
name -----> valid
name@ -----> invalid
age# ------> invalid
age ---→ valid
Rule-2 : Identifier should not start with digit (First letter shouldn’t be digit)
1age --------> invalid
age2 ------> valid
name3 -----> valid
_name -----> valid
$name ------> valid
@name ------> invalid
$_amt --------> valid
_1bill -----------> valid
Rule-3: Java reserved keywords cannot be used as an identifier (53 reserved words available
in java)
int byte = 20; -------> invalid bcz byte is a reserved word
byte for = 25; -------> invalid bcz for is a reserved word
int try = 30; ------> invalid bcz try is a reserved word
long phno = 797979799 -----> valid
16
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Rule - 5: Identifiers in Java are case sensitive; foo and Foo are two different identifiers.
Java Keywords
-> In Java we have total 53 reserved words, those are classified like below
17
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
18
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Note: Variables & Methods naming conventions are same. But methods will have
parenthesis ( ( ) ) variables will not have parenthesis.
19
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Java Comments
-> In java we have 3 types of comments
-> Commented code will not participate in compilation & execution
Note: Java compiler will skip commented lines of code
1) single line comments
Syntax:
// this is single line comment
2) multi line comments (when we don't want to compile multiple lines of code)
/*
commented code
*/
3) documentation comments (Used to generate API documentation)
/**
*
* @author ashok
*
*/
20
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
21
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
22
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Knowledge Check
1) What is full stack development?
2) Explain software project architecture
3) What are the roles & responsibilities of full stack developer
4) What is database and why we need it?
5) What is programming language & why we need programming language?
6) What is JAVA?
7) What are the features of java?
8) What is the difference between C and Java?
9) What type of applications we can develop using java & brief them
10) What is the difference between JDK, JRE and JVM?
11) What is the execution flow of java program?
12) What is the difference between interpreter and compiler?
13) Write JVM architecture & explain JVM components
14) What is JIT?
15) Write Java data types with size, range and default values
16) What is variable and how to create variables
17) Explain Java program elements
18) Write a java program to print welcome message
19) Write a java program on variables declaration, initialization
20) How many types of comments available in java
21) What is identifier and what are rules available for identifier
22) What are the reserved words in java
23) Write Java Naming Conventions for packages, classes, variables and methods
23
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Chapter – 3
• Operators
- Arithmetic
- Relational
- Logical
- Assignment
- New
• Control Statements
- Conditional Statements
- Looping Statements
- Transfer Statements
24
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Operators
-> Operator is a symbol which tells to the compiler to perform some operation.
-> Java provides a rich set of operators do deal with various types of operations.
-> Sometimes we need to perform arithmetic operations then we use plus (+) operator for
addition, multiply (*) for multiplication etc.
-> Operators are always essential part of any programming language.
-> Java operators can be divided into following categories:
• Arithmetic operators
• Relation operators
• Logical operators
• Assignment operators
• Conditional operators
• Misc. operators
Arithmetic operators
Arithmetic operators are used to perform arithmetic operations like: addition, subtraction
etc and helpful to solve mathematical expressions.
The below table contains Arithmetic operators.
25
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Post-Increment (Ex: a ++): Value is first used for computing the result and then
incremented.
26
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Pre-Increment (Ex: ++ a): Value is incremented first and then the result is computed.
Post-decrement (Ex: a--): Value is first used for computing the result and then
decremented.
Pre-decrement (Ex: --a): Value is decremented first and then the result is computed.
27
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
28
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Logical operators
Logical Operators are used to check conditional expression. For example, we can use logical
operators in if statement to evaluate conditional based expression. We can use them into
loop as well to evaluate a condition.
Java supports following 3 logical operators. Suppose we have two variables whose values
are: a=true and b=false.
Assignment Operators
Assignment operators are used to assign a value to a variable. It can also be used combine
with arithmetic operators to perform arithmetic operations and then assign the result to the
variable. Assignment operator supported by Java are as follows:
29
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
30
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Conditional operator
It is also known as ternary operator because it works with three operands. It is short
alternate of if-else statement. It can be used to evaluate Boolean expression and return
either true or false value
Syntax : epr1 ? expr2 : expr3
In ternary operator, if epr1 is true then expression evaluates after question mark (?) else
evaluates after colon (:). See the below example.
instanceOf operator
It is a java keyword and used to test whether the given reference belongs to provided type
or not. Type can be a class or interface. It returns either true or false.
Example:
Here, we created a string reference variable that stores “Ashok IT”. Since it stores string
value so we test it using instance operator to check whether it belongs to string class or not.
See the below example.
31
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
new operator
. (Dot) operator
-> This operator used to access the members of the class using reference or column like
follows
Eg:
reference.variable
reference.method()
ClassName.variable
ClassName.method()
-> This operator can also be used to refer or identify the class from a package
Eg:
java.lang.NoSuchMethodError
java.lang.String
......
32
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
33
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
34
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
35
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
36
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Assignment
1) Write a java program to check given number is even number or odd number
2) Write a java program to check given number is prime number or not
3) Write a java program to check given number is divisible by 5 or not
4) Write a java program to check given character is alphabet or digit
37
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Switch statement
-> Java switch statement compares the value and executes one of the case blocks based on
the condition.
-> It is same as if…else if ladder. Below are some points to consider while working with
switch statements:
38
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
39
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
40
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
41
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
42
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
43
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Continue Statement
-> In Java, the continue statement is used to skip the current iteration of the loop. It jumps
to the next iteration of the loop immediately.
-> We can use continue statement with for loop, while loop and do-while loop as well.
Return statement
-> return is a transferring statement which is used to stop the continuity of method
execution.
44
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
45
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
5
54
543
5432
54321
Knowledge Check
1) What is Operator and why we need operators?
2) List down all the operators available in Java?
3) What is the difference between Relational & Logical Operators?
4) What is the purpose of 'new' operator?
5) What is the purpose of 'dot(.)' operator?
6) What is the purpose of instance of operator?
7) What is the difference between "=" and "==" operators?
8) What is the purpose of Control Statements & List down all the control statements
available in java?
9) Write a java program on if - else if - else ladder
10) Write a java program on 'switch' case
11) What is the difference between while & do-while loops
12) Write a java program on 'while' loop
13) What is the difference between 'while' loop & 'for' loop
14) Write a java program on 'for' loop
15) Write a java program on 'nested for loop'
16) What is the difference between 'break' and 'continue' & 'return' keywords
17) Write a java program using 'break' keyword
18) Write a java program using 'continue' keyword
46
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Chapter – 4
• Arrays
• String
• StringBuffer
• StringBuffer
• Command Line Args
47
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Arrays
-> Array is an object which contains elements of similar data type
-> Array is a container object that hold values of homogeneous type.
-> Array is also known as static data structure because size of an array must be specified at
the time of its declaration.
-> Array starts from zero index and goes to n-1 where n is length of the 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 treated as an object and stores into heap memory. It allows to store
primitive values or reference values.
48
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
-> In the above example, we created an array arr of int type and can store 5 elements. We
iterate the array to access its elements and it prints five times zero to the console. It prints
zero because we did not set values to array, so all the elements of the array initialized to 0
by default.
-> Here, we are assigning values at the time of array creation. It is useful when we want to
store static data into the array.
-> We can set value based on index position also
49
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
50
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Multi-Dimensional Array
A multi-dimensional array is very much similar to a single dimensional array. It can have
multiple rows and multiple columns unlike single dimensional array, which can have only
one row index.
It represents data into tabular form in which data is stored into row and columns.
51
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Strings
-> String is an object that represents sequence of characters.
Ex: "hello”, "ashokit"
-> In Java, String is represented by String class which is available java.lang package
-> One important thing to notice about string object is that string objects are immutable
that means once a string object is created it cannot be changed.
How to create String object in Java?
-> To handle string data in Java, we need an object of string class. Basically, there are three
ways to create a String object in Java.
1) By string literal.
2) By new keyword.
3) By converting character arrays into strings
Working with String literal
-> String literal in Java is created by using double quotes.
String str = "hello";
-> The string literal is always created in the string constant pool.
-> In Java, String constant pool is a special area that is used for storing string objects.
-> Whenever we create a string literal in Java, JVM checks string constant pool first. If the
string already exists in string constant pool, no new string object will be created in the string
pool by JVM.
-> JVM uses the same string object by pointing a reference to it to save memory. But if string
does not exist in the string pool, JVM creates a new string object and placed it in the pool.
52
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
For example:
String s1 = "Hello";
String s2 = "Hello";
53
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
-> Now JVM will create the second object as a copy for literal “Hello” in string constant pool
for future purposes. There is no explicit reference variable pointing to the copy object in the
pool but internally, JVM maintains the reference variable implicitly.
-> Remember that the object created in the SCP area is not eligible for garbage collection
because implicitly, the reference variable will be maintained by JVM itself.
By converting Character Arrays into String
-> The third way to create strings is by converting the character arrays into string. Let’s take
a character type array: arr[ ] with some characters as given below:
char arr[ ] = {'j','a','v','a'};
-> Now create a string object by passing array name to string constructor like this:
String s = new String(arr);
-> Now string object ‘s’ contains string “java”. It means that all the characters of the array
are copied into string.
-> If you do not want all the characters of the array into string then you can also mention
which character you need, like this:
String s = new String(arr, 1,3);
-> From the above statement, total of three characters will be copied into string s. Since the
original characters are j-a-v-a. So, the counting will start from 0 i.e 0th character in the array
is ‘j’ and the first character is ‘a’. Starting from ‘a’, total of three characters ‘aja’ will copy
into string s.
How many total objects will be created in memory for following string objects?
String s1 = new String("ashokit");
String s2 = new String("ashokit");
String s3 = "ashokit";
String s4 = "ashokit";
54
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
1. During the execution of first statement using new operator, JVM will create two objects,
one with content in heap area and another as a copy for literal “ashokit” in the SCP area for
future purposes as shown in the figure.
The reference variable s1 is pointing to the first object in the heap area.
2. When the second statement will be executed, for every new operation, JVM will create
again one new object with content “ashokit” in the heap area.
But in the SCP area, no new object for literal will be created by JVM because it is already
available in the SCP area. The s2 is pointing to the object in the heap area as shown in the
figure.
3. During the execution of third and fourth statements, JVM will not create a new object
with content “ashokit” in the SCP area because it is already available in string constant pool.
It simply points the reference variables s3 and s4 to the same object in the SCP. They are
shown in the above figure.
Thus, three objects are created, two in the heap area and one in string constant pool.
String Manipulations
String class provided several methods to perform operations on Strings
#1) Length
The length is the number of characters that a given string contains. String class has a
length() method that gives the number of characters in a String.
55
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
#2) concatenation
Although Java uses a ‘+’ operator for concatenating two or more strings. A concat() is an
inbuilt method for String concatenation in Java.
56
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
57
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
58
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
59
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
StringBuffer Class
-> StringBuffer class is used to create a mutable string object. It means, it can be changed
after it is created.
-> It is similar to String class in Java both are used to create string, but stringbuffer object
can be changed.
-> StringBuffer class is used when we have to make lot of modifications to our string.
-> It is also thread safe i.e multiple threads cannot access it simultaneously.
StringBuffer defines 4 constructors.
StringBuffer(): It creates an empty string buffer and reserves space for 16 characters.
StringBuffer(int size): It creates an empty string and takes an integer argument to set
capacity of the buffer.
StringBuffer(String str): It creates a stringbuffer object from the specified string.
StringBuffer(charSequence []ch): It creates a stringbuffer object from the charsequence
array.
60
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Note: In the above program Output is such because String objects are immutable objects.
Hence, if we concatenate on the same String object, it won't be altered But StringBuffer
creates mutable objects. Hence, it can be altered.
61
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
#2) insert() :
This method inserts one string into another. Here are few forms of insert() method
#3) reverse()
This method reverses the characters within a StringBuffer object.
62
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
#4) replace()
This method replaces the string from specified start index to the end index.
#5) capacity()
This method returns the current capacity of StringBuffer object.
63
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
StringBuilder (String str): create a StringBuilder object and initialize it with string str.
StringBuilder (CharSequence seq): It creates stringbuilder object by using CharSequence
object.
-> When we want a mutable String without thread-safety then StringBuilder should be used
-> When we want a mutable String with thread-safety then StringBuffer should be used
-> When we want an Immutable object then String should be used.
64
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
-> When we pass command-line arguments, they are treated as strings and passed to the
main method in the string array argument.
-> The arguments have to be passed as space-separated values.
-> We can pass strings and primitive data types as command-line arguments.
-> The arguments will be converted to strings and passed into the main method string array
argument.
Java Program with Command Line Arguments
65
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
66
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
OOPS
-> Programming languages are divided into 2 types
1) Procedure Oriented Languages
Ex: C, Cobol, Pascal etc.....
2) Object Oriented Languages
Ex: Java, C#, Python etc.....
-> In Procedure Oriented programming language, we will develop functions & procedures
-> If we want to add more functionalities then we need to develop more functions
-> Maintaining & Managing more functions is difficult task
-> In PoP, data is exposed globally
-> In Pop, there is no security
-> If we want to develop a project using OOP lanaguage then we have to use Classes &
Objects
-> Any language which follows OOPS Principles is called as OOP Language
-> Object Oriented languages provides security for our data
-> The main advantage of OOPS is code re-usability
OOPS Principles
1) Encapsulation
2) Abstraction
3) Polymorphism
4) Inheritance
Encapsulation
-> Encapsulation is used to combine our variables & methods as single entity / unit
-> Encapsulation provides data hiding
-> We can achieve encapsulation using Classes
class Demo {
//variables
// methods
}
67
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Abstraction
-> Abstraction means hiding un-necessary data and providing only required data
-> We can achieve Abstraction using interfaces & abstract classes
Ex : we will not bother about how laptop working internally
We will not bother about how car engine starting internally
Polymorphism
-> Exhibiting multiple behaviours based on situation is called as Polymorphism
Ex:-1 : in below scenario + symbol having 2 different behaviours
10 + 20 ===> 30 (Here + is adding)
"hi" + "hello" ==> hihello (here + is concatinating)
Ex:-2:
When i come to class i will behave like a trainer
When i go to ofc i will behave like a employee
When i go to home i will behave like a family member
Inheritance
-> Extending the properties from one class to another class is called as Inheritance
Ex: child will inherit the properties from parent
-> The main aim of inheritance is code re-usability
Note: In java, one child can't inherit properties from two parents at a time
Class
-> Class is a plan or model or template
-> Class is a blue print of object
-> Class is used to declare variables & methods
-> Project means collection of classes
-> Once class is created then we can create any no.of objects for a class
-> 'class' keyword is used to create Classes in java
68
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Object
-> Any real-world entity is called as Object
-> Objects exist physically
-> Objects will be created based on the Classes
-> Without having the class, we can' create object (class is mandatory to create objects)
-> Object creation means allocating memory in JVM
-> 'new' keyword is used to create the objects
69
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Variables
-> Variables are used to store the data
int a = 10 ;
User u1 = new User ( );
Student s1 = new Student ( );
-> Variables are divided into 3 types
a) Global Variables / instance variables / non-static variables
b) static variables
c) local variables
Instance variables
-> Variables which are declared inside the class and outside the method are called as
instance variables
-> instance variables can be accessed by all the methods available in the class thats why the
are called as Global Variables.
-> Initialization is optional for instance variables
70
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Static Variables
-> The variables which are declared inside the class and outside the method with 'static'
keyword are called as static variables
-> Static variables are class level variables
-> When class is loaded into JVM then immediately memory will be allocated for static
variables
-> Memory will be allocated for static variables only once when the class is loaded into JVM
-> All objects of the class will maintain same copy of the static variables
-> Static variables we will access using class name
71
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Local Variables
-> The variables which are declared inside the method or constructor or block are called as
Local Variables
-> If we declare a variable with in the method, then that variable can be used / accessed
only with in that method
-> Before using local variables, we have to initialize them
-> If we create a variable with in the method, memory will be allocated for that variable
when that method is executing. After that method execution completed, local variable will
be deleted from memory
72
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Methods
-> Methods are used to perform some operation / action
-> In a class we can write any no. of methods including main method
-> Every method contains 2 parts
1) Method Declaration
2) Method Body
What is Method Declaration?
Method declaration means we are going to decide what is the name of the method, what
are the parameters it will take and what kind of value is return by the method.
73
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
-> here we can write 0 or more number of statements in between the pair of curly braces.
-> when we write 0 statements then it is called as null implementation
-> if the return type is specified as other than void then we must return a value from our
method using java keyword called " return ".
-> The datatype of the value we return must be match with the datatype that we specify as
return type.
-> But if return type specified as void, then we must not write any return value statement.
-> In java we can create any number of methods which are in any of the following 4
combinations of methods
1. method without return type, without parameters
2. method without return type, with parameters
3. method with return type, without parameters
4. method with return type, with parameters
74
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
75
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
76
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
77
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
78
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Types of Methods
-> Methods are divided into 2 types
1) instance / non – static methods ---> Object level methods
2) static methods ----> Class level methods
In a class, we can write any no. of instance and static methods
Not: To create static method we will use ‘static’ keyword.
-> When we write methods in java class, by default JVM will not execute them. To execute
our methods, we have to call them.
-> instance method will be called by using Object
objReference.methodName( .. ) ;
-> static method will be called by using Class Name
ClassName.methodName( .. );
Instance & Static methods Example
Note: When we have static method in same class then we can invoke/call it directly without
using classname.
In above program Line : 17, we are calling static method with classname, as the method is
available in same class we can call directly like below.
greet ( ) ;
79
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
1. public:
public is keyword/ modifier / access specifier which indicates the particular entity can be
accessed from any location. main() method should be declared as public so that JVM can
execute the main() method from any location.
2. static:
static is keyword/ modifier which indicates the particular method can access directly by
using class name.
main() method should be declared as static so that JVM can access the main() method
directly by using class name.
3. void:
void is keyword/ return type which indicates the particular method does not return any
value. JVM is not expecting any value to be return from main() method so that main()
method should have the return type as void.
4. main():
main is the name of the method(identifier) which is fixed according to sun micro system's
JVM implementation.
5. parameters of main () method (String args[])
parameters of main () method are mainly used to accept the command line arguments to
resolve the problem of hard coding.
Explain about System.out.println()
System.out.println() is statement used to display messages on the monitor.
System: System is a predefined class available in java. lang package
Out: out is reference variable of PrintStream class which is holding an object of PrintStream
class and declared in
System class as static variable. so that we can access this out variable directly with the help
of class name.
80
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Println () : println() is the instance method of PrintStream class. If we want to access this
method, we must create an object for PrintStream class but we don’t need to create any
object for PrintStream class because the object for PrintStream class is already created in
System class
Note: System.out is by default connected to monitor. System.in is by default connected to
keyboard.
Method Recursion
In Java, a method that calls itself is known as a recursive method. And, this process is known
as recursion.
Recursion Syntax
Any method that implements Recursion has two basic parts:
a) Method call which can call itself i.e. recursive
b) A precondition that will stop the recursion.
Note that a precondition is necessary for any recursive method as, if we do not break the
recursion then it will keep on running infinitely and result in a stack overflow error
81
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Assignment On Recursion
1) Check If a Number is a Palindrome Using Recursion
2) Reverse a String using Recursion in Java
3) Find Minimum Value in Array Using Recursion
Constructors
-> When we declare instance variables and not initialized with any value, then they
automatically initialized with default values.
-> but if we want to initialize instance variables with our own values then we can initialize
instance variables in following 2 locations,
1. At the time of declaration
2. Using Constructor
-> A constructor is a special method that is used to initialize an object / instance variables.
-> If we don't declare a constructor in the class then JVM builds a default constructor for
that class. This is known as default constructor.
Rules of the constructor
Default Constructor
-> In Java, a constructor is said to be default constructor if it does not have any parameter.
Default constructor can be either user defined or provided by JVM.
-> If a class does not contain any constructor, then during runtime JVM generates a default
constructor which is known as system define default constructor.
-> If a class contain a constructor with no parameter, then it is known as default constructor
defined by user. In this case JVM does not create default constructor.
82
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Based on the number of parameters, constructors are classified into following 2 types,
1) 0 Parameterized Constructor
2) Parameterized Constructor
0 parametrized constructor
-> If we declare any constructor without any parameters then it is called as 0 parametrized
constructor.
-> When we create object for the class then Constructor will be called.
83
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Parametrized constructor
If we declare any constructor with parameters then it is called as parameterized
constructor.
Note: When the constructor is having parameters, at the time of creating object we have to
pass those parameters.
// Program on Parameterized Constructor
84
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Constructor Overloading
-> Java Constructor overloading is a technique in which a class can have any number of
constructors that differ in parameter list.
In other words, defining two or more constructors with the same name but with different
signatures is called constructor overloading in java. It is used to perform different tasks.
-> The compiler differentiates these constructors by taking into account the number of
parameters in the list and their data type.
85
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
This keyword
In Java, this is a keyword which is used to refer current object of a class. we can it to refer
any member of the class. It means we can access any instance variable and method by using
this keyword.
The main purpose of using this keyword is to solve the confusion when we have same
variable name for instance and local variables.
We can use this keyword for the following purpose.
86
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Knowledge – Check
1) What is Class ?
2) What is Object ?
3) Why we need to Create Object ?
4) What is instance variable and why we need them ?
5) When memory will be allocated for instance variables ?
6) How many times memory will be allocated for instance variables ?
7) What is static variable and why we need them ?
8) When memory will be allocated for static variables ?
9) How many times memory will be allocated for static variables ?
10) What is Local Variable & Why we need Local Variable ?
11) When Memory will be allocated for local variable ?
12) What is Constructor why we need Constructor ?
13) What are the rules to write Constructor ?
14) What is Constructor Overloading & Why we need it ?
15) What is Method and Why we need methods ?
16) When to take method parameter and method return type ?
17) When to use primitive type for method parameters & return types ?
18) When to use Object as method parameter & return type?
19) What is Object Oriented Language ?
20) What are OOPS principles?
87
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
88
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
89
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Note:
1. If we create an object for parent class then we can access only the members of Parent
class
2. but if we create an object for child class then we can access the members of Both Parent
class and Child class
-> In the code above, we have a class Parent which has a method p1(). We then create a
new class Child which inherits the class Parent using the extends keyword and defines its
own method c1(). Now by virtue of inheritance the class Child can also access the public
method p1() of the class Parent.
// Inheritance Example – Accessing parent class variable in child class
90
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Types of Inheritances
Based on the no. of parent classes & child classes we can divide inheritance into below
types.
• Single Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Multiple Inheritance
91
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
-> In java every predefined class or user defined class are child classes of Object class either
directly or indirectly so that all members of the Object class we can directly use in any class.
-> When we declare a class and we are not extending from any class then compiler will
create the class by extending from Object class automatically.
but we declare a class by extending from any one class then compiler won’t extend from
Object class, hence we call Object class as java's super most class
super keyword
In Java, super keyword is used to refer to immediate parent class of a child class. In other
words super keyword is used by a subclass whenever it need to refer to its immediate super
class.
92
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
// Example of Child class calling Parent class constructor using super keyword
Note: When calling the parent class constructor from the child class using super keyword,
super keyword should always be the first line in the method/constructor of the child class.
Q. Can we use both this () and super () in a Constructor?
NO, because both super () and this () must be first statement inside a constructor. Hence,
we cannot use them together.
93
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
IS-A relationship
-> If class is extending from another class then it is called as Is-A relation.
-> Here we can access class1 information inside the class2 directly without creating an
object for class1.
Has-A relation
-> If a class contains other class object, then it is called as Has-A relation.
-> Here we can access class1 information inside the class2 only by using object of class1.
94
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Polymorphism
-> Polymorphism means defining one entity with multiple behaviours
-> In java we have following 2 types of poly morphisms.
1. Compile time polymorphism
2. Runtime Polymorphism
Method overloading
Method overloading means declaring multiple methods with same method name but having
different method signature.
In method overloading while writing the method signature we have to follow following 3
Rules
95
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
96
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Method overriding
-> If we want to achieve the run time polymorphism then we have to use method
overriding.
-> Method overriding means declaring 2 methods with same method signature in 2 different
classes which are having IS-A relation.
-> While Method overriding and writing the method signature, we must follow following
rules.
As you can see here Dog class gives it own implementation of eat() method. For method
overriding, the method must have same name and same type signature in both parent and
child class.
NOTE: Static methods cannot be overridden because, a static method is bounded with class
whereas instance method is bounded with object.
97
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Final keyword
-> final is a keyword or modifier which can be used at variables, methods & classes.
-> If we declare a variable as final then we can’t modify value of the variable. The variable
acts like a constant. Final field must be initialized when it is declared.
-> If we declare a method as final then we can't override that method
-> If we declare a class as final then we can't extend from that class. We cannot inherit final
class in Java.
// Program on final keyword
98
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Type casting
-> Type casting is the process of converting value from one type to another type.
-> We always do typecast between 2 different data types which are compatible.
Note: In between 2 same data types typecasting is not required.
-> In java we have following 2 types of type castings
1.type casting w.r.t primitive data types
2.type casting w.r.t reference types
Type casting wrt primitive data types
-> Type casting wrt primitive data types means converting value from one primitive data
type to other primitive data type
-> Type casting can be done only between compatible data types
-> Compatible data types are byte, short, int, long, float, double, char
-> we have following 2 types of Type casting w.r.t primitive data types
1) Widening
2) Narrowing
Widening
-> Widening means converting the value from lower data type into higher data type.
syntax:
higher datatype = (higher datatype) lower datatype ;
-> Here data type specified in between the pair of parentheses is called type casting.
-> In widening writing the type casting is optional
-> If we don’t write any type casting then compiler will write the type casting automatically
hence it is called as implicit type casting.
99
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Narrowing
-> narrowing means converting the higher data type value into smaller data type.
syntax:
lowerdatatype = (lowerdatatype) higherdatatype;
-> In narrowing writing the type casting is mandatory
-> In narrowing if we don’t write any type casting then compiler wont write any typecasting
because there is a chance of loss of some data so that user has to write the typecasting
explicitly hence it is called as explicit type casting.
100
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
1) Up Casting
2) Down Casting
Up casting
-> Up casting means storing the child class object into the parent class reference.
syntax:
parentreferencetype = (parentreferencetype) childreferencetype
Note: In up casting writing typecasting is optional
Down casting
-> Down casting means storing the Parent class object into the child class reference.
syntax: childreferencetype = (childreferencetype) parentreferencetype
Note: In down casting writing typecasting is mandatory
// Type Casting Example w.r.t to reference types
101
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
102
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Note:
-> All the variables declared in interface are public static final by default whether we specify
or not
-> All the methods declared in interface are public abstract by default whether we specify or
not
public: all the variables and methods declared in interface are public so that they can be
accessible from any where.
static: variables declared in interface are by default static so that they can be accessible
directly by using the interface name.
final: the variables declared in interface are by default final it means they are constant
whose value cannot be changed.
abstract: all the methods declared in interface are abstract because they don’t contain any
method body
103
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Implementing an Interface
-> Like abstract classes, we cannot create objects of interfaces.
-> To use an interface, other classes must implement it. We use the implements keyword to
implement an interface.
In the above example, we have created an interface named Language. The interface
includes an abstract method getName().
Here, the ProgrammingLanguage class implements the interface and provides the
implementation for the method.
104
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Interface Rules
• For an interface we cannot create any object directly but we can create reference
variable
• Once an interface is implemented by any class then that class must provide the
implementation for all the abstract methods available in the particular interface. This
class is also called as implementation class or child class.
• For example, if our class is not providing implementation for at least 1 method then
our class must be declared as abstract
• We cannot create an object for abstract class or interface but we can create an
object only for implementation class.
• Once an interface is created then any number of classes can implement that
interface
-> In Java, a class can implement multiple interfaces. For example,
-> Similar to classes, interfaces can extend other interfaces. The extends keyword is used for
extending interfaces. For example,
Here, the Polygon interface extends the Line interface. Now, if any class implements
Polygon, it should provide implementations for all the abstract methods of both Line and
Polygon.
105
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
106
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
107
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
• Default methods
• Static methods
• Public methods inherited from the Object class
108
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Note: If we observe above program, we are writing sum ( ) method different arguments. If
we want to add 5 numbers or 6 numbers or 7 numbers then writing multiple methods will
become difficult.
109
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
110
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
when we display the object of the class it will call Object class toString( ) method, if we want
to display object data then we have to override the toString() method inside the particular
class.
111
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
112
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
3. int hashCode()
-> This method returns hashcode of the particular object .
-> Hashcode is a unique identification number which holds address of the corresponding
object.
Note: We can also provide our own hashcode then we have to override the hashcode()
method inside corresponding class
113
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
4. boolean equals(Object o)
this method compares the 2 references whether they contain same object or not bydefault.
but if we want to compare the equality of the content of 2 objects then we have to override
equals() method with in the particular class.
114
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Note:
In String class already equals() method is overridden in such a way that it will compare the
equality of the content of 2 Strings.
115
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Note: StringBuffer class is not overriding equals() method so that in the above program
when we compare 2 StringBuffer objects using equals() method it will check reference of 2
objects but not equality of the content.
5. Object clone():
This method used to clone or copy the object so that we can take the backup for the object,
but in java every object is created in a way that, it can not be copied directly, if we want to
perform this special operations we must follow following rules.
1. the cloned object must be type casted to corresponding object
2. we must handle an exception called CloneNotSupportedException
3. corresponding class must implement a marked interface called Cloneable interface
116
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
117
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
6. finalize() in Java
The finalize() method is called by the Garbage Collector when there are no more references
to the object in question. Thus, finalize() is called just before an object is garbage collected.
7. wait () in Java
The wait () method causes a current thread to wait until another thread invokes the notify ()
or the notifyAll () method for the object in question.
Syntax:
public final void wait () throws InterruptedException
public final void wait (long timeout) throws InterruptedException
public final void wait (long timeout, int nanos) throws InterruptedException
8. notify()
The notify() method releases the wait on the waiting thread on the invoking object’s
monitor so that it can continue execution.
Syntax : public final void notify()
9. notifyAll()
The notifyAll() method releases the wait on all the waiting threads on the invoking object’s
monitor so that they can continue execution.
Syntax : public final void notifyAll()
Note: The notify() can be used to wake up only one thread that is waiting for a particular
object whereas notifyAll() can be used to wake up all the threads of a specific object.
118
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Knowledge – Check
1) What are Access Modifiers in Java?
2) When to use public, private, protected?
3) What is Inheritance?
4) What is Single Level and Multi-Level Inheritance?
5) Why Java Doesn’t support Multiple Inheritance?
6) What is Encapsulation?
7) Why to declare variables as private?
8) What is the need of setter and getter methods?
9) What is Polymorphism?
10) What is Method Overloading and why we need it?
11) What is Method Overriding and why we need it?
12) What is Abstract Method?
13) What is Interface and why we need interfaces?
14) What is Abstract Class and Why we need them?
15) Difference between Interface and Abstract Classes
16) What is Marker Interface and why we need them?
17) What is difference between this keyword and super keyword?
18) What is final keyword and when to use it?
19) What is the use of var args?
20) What is Object class?
21) What is Cloning?
22) Can you explain all methods of Object class?
23) When to override equals ( ) method ?
24) What is the difference between String class equals ( ) method and Object class
equals ( ) method ?
25) What is hashcode ?
26) How to create Object for a class without using new keyword?
119
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Chapter – 7
• Packages
• Wrapper Classes
• Exception Handling
120
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Packages in Java
-> In small projects, all the java files have unique names. So, it is not difficult to put them in
a single folder.
-> But, in the case of huge projects where the number of java files is large, it is very difficult
to put files in a single folder because the manner of storing files would be disorganized.
-> Moreover, if different java files in various modules of the project have the same name, it
is not possible to store two java files with the same name in the same folder because it may
occur naming conflict.
This problem of naming conflict can be overcome by using the concept of packages.
A package is nothing but group of related classes, interfaces, and sub-packages according
to their functionality.
Types of Packages in Java
There are two different types of packages in Java. They are:
1. Predefined Packages in Java (Built-in Packages)
2. User-defined Package
-> Built-in packages are existing java packages that come along with the JDK. For example,
java.lang, java.util, java.io, etc.
The package which is defined by the user is called a User-defined package. It is used to
create user-defined classes and interfaces.
121
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
122
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Static imports
static imports are special kind of import statements given in java 1.5 version which are used
to import the static members of any class into the program so that we can access those
static members directly without any class name or object.
123
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
124
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
-> While creating an object for Boolean Wrapper class if constructor takes primitive boolean
value as true it stores true otherwise if it takes primitive boolean value as false it stores
false.
125
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
-> While creating an object for Boolean Wrapper class if constructor takes primitive boolean
value in the form of string then if string value is true in any case (true, True,TRUE,...) then it
stores true otherwise if string value is other than true it stores false.
Eg:
Boolean b1 = new Boolean(); //CTE
Boolean b2 = new Boolean(true); //true
Boolean b3 = new Boolean(false); //false
Boolean b4 = new Boolean(True); //CTE
Boolean b5 = new Boolean("TRUE"); //true
Boolean b6 = new Boolean("false"); //false
Boolean b7 = new Boolean("suresh"); //false
Boolean b8 = new Boolean(null); //false
Boolean b9 = new Boolean(1); //CTE
126
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
127
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
128
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Exception Handling
Whenever we develop any application there is a chance of getting some errors in the
application. When exception occurs in the program then our program will be terminated
abnormally.
Exception handling is a mechanism to catch and throw Java exceptions so that the execution
of the program will not get disturbed.
What is an Exception?
Exception is an unwanted or unexpected event, which occurs during the execution of a
program, i.e. at run time, that disrupts the normal flow of the program’s instructions.
Exceptions can be caught and handled by the program. When an exception occurs within a
method, it creates an object. This object is called the exception object. It contains
information about the exception, such as the name and description of the exception and the
state of the program when the exception occurred.
An exception can occur for many reasons. Some of them are:
What is Error?
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer, and we should not try to handle
errors.
What is the difference between Exception and Error?
Error: An Error indicates a serious problem that a reasonable application should not try to
catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
129
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Exception Hierarchy
All exception types are subclasses of class Throwable, which is at the top of exception class
hierarchy.
Checked Exceptions
These are the exceptions that are checked at compile time. If some code within a method
throws a checked exception, then the method must either handle the exception or it must
specify the exception using the throws keyword.
Note: Checked exceptions are checked by the Java compiler so they are called compile time
exceptions.
Note that all checked exceptions are subclasses of Exception class. For example,
• ClassNotFoundException
• IOException
• SQLException etc..
// Example on Checked Exception
130
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Un Checked Exceptions
Unchecked exceptions are not checked by the compiler. When the buggy code is executed
then we will get exception at runtime, these are called runtime exceptions.
//example on Unchecked exception
try: The try block is used to enclose the suspected code. Suspected code is a code that may
raise an exception during program execution.
For example, if a code raise arithmetic exception due to divide by zero then we can wrap
that code into the try block.
131
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
catch : The catch block also known as handler is used to handle the exception. It handles the
exception thrown by the code enclosed into the try block. Try block must provide a catch
handler or a finally block.
The catch block must be used after the try block only. We can also use multiple catch block
with a single try block.
132
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
An exception will throw by this program as we are trying to divide a number by zero inside
try block. The program control is transferred outside try block. Thus, the line "This line will
not be executed" is never parsed by the compiler. The exception thrown is handled in catch
block. Once the exception is handled, the program control is continued with the next line in
the program i.e., after catch block. Thus, the line "After exception is handled" is printed.
Java try with Resource Statement
-> try with resource is a new feature of Java that was introduced in Java 7 and further
improved in Java 9. This feature add another way to exception handling with resources
management. It is also referred as automatic resource management. It close resources
automatically by using AutoCloseable interface..
-> Resource can be any like: file, connection etc and we don't need to explicitly close these,
JVM will do this automatically.
-> Suppose, we run a JDBC program to connect to the database then we have to create a
connection and close it at the end of task as well. But in case of try-with-resource we don’t
need to close the connection, JVM will do this automatically by using AutoCloseable
interface.
133
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
-> This try statement contains a parenthesis in which one or more resources is declared. Any
object that implements java.lang.AutoCloseable or java.io.Closeable, can be passed as a
parameter to try statement. A resource is an object that is used in program and must be
closed after the program is finished. The try-with-resources statement ensures that each
resource is closed at the end of the statement of the try block. We do not have to explicitly
close the resources.
Points to Remember
-> A resource is an object in a program that must be closed after the program has finished.
-> Any object that implements java.lang.AutoCloseable or java.io.Closeable can be passed as
a parameter to try statement.
-> All the resources declared in the try-with-resources statement will be closed
automatically when the try block exits. There is no need to close it explicitly.
-> We can write more than one resources in the try statement.
-> In a try-with-resources statement, any catch or finally block is run after the resources
declared have been closed.
134
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
finally block :
-> A finally keyword is used to create a block of code that follows a try block.
-> A finally block of code is always executed whether an exception has occurred or not.
-> Using a finally block, it lets you run any clean up type statements that you want to
execute, no matter what happens in the protected code.
-> A finally block appears at the end of catch block.
135
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
136
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
=> We can handle multiple Exceptions in Single Catch block also like below
137
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Throw :
-> The throw keyword is used to throw an exception explicitly.
-> By default all predefined exceptions are created and thrown implicitly and identified by
JVM
-> If we want to throw the exceptions explicitly then we have to use throw keyword.
138
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
139
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
1. All exception classes are extending from Exception class. So that to create user defined
exception we should create a class that extends any one of the following 2 classes
a) Exception (Checked Exceptions)
b) RuntimeException (Unchecked Exceptions)
2. Create a parameterized constructor which calls super class parameterized constructor to
set the Exception Message.
3. JVM don’t know when to generate the user defined exception and how to create and
throw the object for User defined exception so that we should explicitly create the object
for User defined exception and throw manually using throw keyword.
140
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Knowledge – Check
1) What is package and why we need packages?
2) What is Import in java?
3) What is static import?
4) What is Wrapper class?
5) When we have primitive types why to go for Wrapper Classes?
6) What is Auto Boxing and Auto Unboxing?
7) What is Exception Hierarchy in Java?
8) Checked Exceptions Vs Un-Checked Exceptions?
9) How to handle Exceptions?
10) What is try-catch-finally?
11) What is the difference between throws and throw?
12) What is try with resources?
13) Why to write Multiple Catch blocks & do you any alternate?
14) How to create and throw User Defined Exception?
15) What is JVM’s behaviour when Runtime Exception occurred?
16) What is Exception re-throw ?
17) Can you explain few checked exceptions?
18) Can you explain few Un-Checked exceptions?
19) Can you write a program which gives Stack Overflow Error?
20) What is the difference between final, finalize ( ) and finally block ?
141
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Chapter - 8
Collections Framework
142
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
COLLECTIONS
-> Array is an collection of fixed number of homogeneous data elements
OR
-> An array represents a group of elements of same data type.
-> The main advantage of array is we can represent huge number of elements by using
single variable. So, the readability of the code is improved.
Limitations of array:
-> Arrays are fixed in size that is once we create an array there is no chance of increasing or
decreasing the size of array based on our requirement. Hence to use array concept we must
know the size in advance which may not possible every time.
-> Arrays can hold only homogeneous data elements.
Example:
Car c = new Car [100];
c[0] = new Car(); // Valid
c[1] = new Bus(); //Invalid(Compile time Error)
-> We can resolve this problem by using Object type Array (Object [ ] )
Example:
Object[] o=new Object[100];
o[0]=new Car();
o[1]=new Bus();
-> Arrays concept is not implemented based on some data structure hence we cannot
expect ready-made method support. For every requirement we have to write the code
explicitly. To overcome the above limitations, we should go for collection concept.
-> Collections are growable in nature that is based on our requirement we can increase or
decrease the size hence memory point of view collections concept is recommended to use.
-> Collections can hold both homogeneous and heterogeneous objects.
-> Every Collection class is implemented based on some standard data structure hence for
every requirement ready-made method support is available. As a programmer we can use
these methods directly without writing the functionality on our own.
143
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Collection: If we want to represent a group of objects as single entity then we should go for
Collections.
Collection framework: It defines several classes and interfaces to represent a group of
Objects as single entity.
Q) What is the difference between Collection and Collections?
Ans) Collection is an interface which can be used to represent a group of Objects as a single
entity whereas Collections is an utility class present in java.util package to define several
utility methods for Collection Objects.
• Collection is an interface
• Collections is a Class
-> All the collection classes are available in “java.util” (utility) package.
-> All the collection interfaces and collection class and together as collection frame work.
-> All the collection classes are classified into three categories
1) List
2) Set
3) Queue
4) Map
1. List:
- This category is used to store group of individual elements where the elements can be
duplicated.
- List is an Interface whose object can not be created directly.
- To work with this category we have to use following implementations class of list interface
Ex: ArrayList, Linked list, Vector, Stack
144
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
2.Set:
- This category is used to store a group of individual elements. But they elements can’t be
duplicated.
- Set is an interface whose object cannot be created directly.
- To work with this category, we have to use following implementations class of Set
interface
Ex: HashSet, LinkedHashSet and TreeSet
3. Queue
-> This category is used to hold the elements about to be processed in FIFO(First In First Out)
order.
-> It is an ordered list of objects with its use limited to inserting elements at the end of the
list and deleting elements from the start of the list, (i.e.), it follows the FIFO or the First-In-
First-Out principle
Ex: PriorityQueue, BlockingQueue
4. Map:
- This category is used to store the element in the form key value pairs where the keys can’t
be duplicated, values can be duplicated.
- Map is an interface whose object cannot be created directly.
- To work with this category, we have to use following implementation classes of Map
interface
Ex: HashMap, LinkedHashMap, TreeMap, Hashtable
145
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Collections Hierarchy
List interface
-> It is the child interface of Collection
-> If we want to represent a group of individual objects where duplicates are allowed and
insertion order is preserved. Then we should go for List.
-> We can differentiate duplicate Objects and we can maintain insertion order by means of
index hence "index plays important role in List"
List interface defines the following specific methods.
1)boolean add(int index,Object o);
2)boolean addAll(int index,Collection c);
3)Object get(int index);
4)Object remove(int index);
5)Object Set(int index,Object o);//to replace
146
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
-> ArrayList and Vector classes implements RandomAccess interface so that any random
element we can access with the same speed.
-> RandomAccess interface present in util package and doesn't contain any methods. It is a
marker interface.
147
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
LinkedList
-> LinkedList is one of the implementation classes of Collection interface
-> The underlying data structure is double LinkedList
-> If our frequent operation is insertion or deletion in the middle then LinkedList is the best
choice
-> If our frequent operation is retrieval then LinkedList is not best option
-> Duplicate Objects are allowed
-> Insertion order is preserved
-> Heterogeneous Objects are allowed
-> NULL insertion is possible
-> Implements Serializable and Cloneable interfaces but not RandomAccess
Note: Usually we can use linked list to implement Stacks and Queues to provide support for
this requirement LinkedList class defines the following 6 specific methods.
1) void addFirst(Object o);
2) void addLast(Object o);
3) Object getFirst();
4) Object getLast();
148
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
5) Object removeFirst();
6) Object removeLast();
LinkedList Constructors:
1) LinkedList l=new LinkedList();
It creates an empty LinkedList Object.
2) LinkedList l=new LinkedList(Collection c);
To create an equivalent LinkedList Object for the given Collection.
149
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Vector
-> Vector is the implementation class of List interface which is also used to store group of
individual objects where duplicate values are allowed
-> Vector is exactly similar to ArrayList but ArrayList is not a synchronized class where Vector
is a synchronized class
-> Vector is also called legacy class because it is available from java 1.0 version.
Vector Class Constructors
1) Vector<E> v = new Vector<E>();
2) Vector<E> v = new Vector<E>(int capacity);
3) Vector<E> v = new Vector<E>(Collection obj);
Stack
-> Stack is a child class of Vector and implements List interface
-> Stack stores a group of objects b using a mechanism called LIFO
-> LIFO stands for Last in first out , it means last inserted element deleted first.
150
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
151
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Iterator
-> this cursor is used to access the elements in forward direction only
-> this cursor can be applied Any Collection (List, Set)
-> while accessing the methods we can also delete the elements
-> Iterator is interface and we cannot create an object directly.
-> if we want to create an object for Iterator, we have to use iterator () method
Creation of Iterator:
Iterator it = c.iterator();
here iterator() method internally creates and returns an object of a class which implements
Iterator interface.
Methods
1. boolean hasNext()
2. Object next()
3. void remove()
152
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
2. ListIterator
-> This cursor is used to access the elements of Collection in both forward and backward
directions
-> This cursor can be applied only for List category Collections
-> While accessing the methods we can also add,set,delete elements
-> ListIterator is interface and we can not create object directly.
-> If we want to create an object for ListIterator we have to use listIterator() method
creation of ListIterator:
ListIterator<E> it = l.listIterator();
here listIterator() method internally creates and returns an object of a class which
implements ListIterator interface.
Methods
1. boolean hasNext();
2. Object next();
3. boolean hasPrevious();
4. Object previous();
5. int nextIndex();
6. int previousIndex();
7. void remove();
8. void set(Object obj);
9. void add(Object obj);
153
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
3. Enumeration
-> this cursor is used to access the elements of Collection only in forward direction
-> this is legacy cursor can be applied only for legacy classes like Vector,Stack,Hashtable.
-> Enumeration is also an interface and we can not create object directly.
-> If we want to create an object for Enumeration we have to use a legacy method called
elements() method
Creation of Enumeration:
Enumeration e = v.elements();
here elements() method internally creates and returns an object of a class which
implements Enumeration interface.
Methods
1. boolean hasMoreElements()
2. Object nextElement();
154
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Set category
HashSet
-> HashSet is the implementation class of Set interface which is also used to store group of
individual objects but duplicate values are not allowed
-> HashSet internally follows hashtable structure where all the elements are stored using
hashing technique which will improve the performance by reducing the waiting time.
155
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
156
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
LinkedHashSet
-> LinkedHashSet is the implementation class of Set interface which is also used to store
group of individual objects but duplicate values are not allowed
-> LinkedHashSet internally follows hashtable + doubly linked list structures
-> LinkedHashSet is not a synchronized class
-> LinkedHashSet supports only one null value.
-> LinkedHashSet is called as ordered Collection because it is guarantee for insertion order
of elements.
Creation of LinkedHashSet:
LinkedHashSet<E> hs = new LinkedHashSet<E>();
LinkedHashSet<E> hs = new LinkedHashSet<E>(int capacity);
LinkedHashSet<E> hs = new LinkedHashSet<E>(int capacity,float loadfactor);
LinkedHashSet<E> hs = new LinkedHashSet<E>(Collection obj);
157
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
SortedSet:
1) It is child interface of Set
2) If we want to represent a group of "unique Objects" according to some sorting order
then we should go for SortedSet interface.
3) That sorting order can be either default natural sorting order OR customized sorting
order.
SortedSet interface defines the following 6 specific methods
1) Object first();
2) Object last();
3) SortedSet headSet(Object o);
It returns the elements whose elements are < o
4) SortedSet tailSet(Object o);
It returns the elements whose elements are >= o
5) SortedSet subSet(Object o1,Object o2);
It returns the elements whose elements are >=o1 and < o2
6) Comparator comparator();
Returns the comparator Object that describes under lying sorting technique. If we follow
default natural sorting order then this method returns null.
import java.util.SortedSet;
import java.util.TreeSet;
public class SortedSetDemo {
public static void main(String[] args) {
SortedSet ss=new TreeSet();
for(int i=10;i<=20;i++)
ss.add(i);
System.out.println(ss.first());//10
System.out.println(ss.last());//20
System.out.println(ss.headSet(16));//[10, 11, 12, 13, 14, 15]
System.out.println(ss.tailSet(18));//[18, 19, 20]
158
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
159
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
NULL acceptance:
For the empty TreeSet as the first element "null" insertion is possible but after inserting that
null if we try to insert any other value then we will get NullPointerException.
For the non-empty TreeSet if we try to insert null then we will get NullPointerException.
String class and all wrapper classes implements Comparable interface but StringBuffer class
does not implement Comparable interface hence in the above program we will get
ClassCastException.
Comparable interface:
160
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Comparable interface present in java.lang package and contains only one method
compareTo() method.
public int compareTo(Object obj);
Example: obj1.compareTo(obj2);
It returns -ve if obj1 comes before obj2
It returns +ve if obj2 comes before obj1
It returns 0 if obj1 and obj2 are equal
If we depend on default natural sorting order then internally JVM will use compareTo()
method to arrange Objects in sorting order.
161
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Comparator interface:
Comparator interface present in java.util package. It defines the
following two methods.
1) public int compare(Object o1,Object o2);
It returns -ve if o1 comes before o2
It returns +ve if o1 comes after o2
It returns 0 if o1 and o2 are equal
2) public boolen equals(Object o);
Whenever we are implementing comparator interface we have to provide implementation
only for compare() method.
Implementing equals() method is optional because it is already available from Object class
through inheritance.
Requirement:- Write a program to insert integer Objects into the TreeSet where the
sorting order is descending order.
Example:
import java.util.Comparator;
import java.util.TreeSet;
public class TreeSetComparator {
public static void main(String[] args) {
TreeSet ts=new TreeSet(new MyComparator());//---->1
ts.add(10);
ts.add(0);
ts.add(15);
ts.add(5);
ts.add(20);
System.out.println(ts);//[20, 15, 10, 5, 0]
}
162
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
}
class MyComparator implements Comparator {
public int compare(Object o1,Object o2) {
Integer i1=(Integer)o1;
Integer i2=(Integer)o2;
if(i1<i2)
return 1;
else if(i1>i2)
return -1;
else
return 0;
}
}
Comparable vs Comparator
For predefined Comparable classes default natural sorting order is already available, if we
are not satisfied with default natural sorting order then we can define our own customized
sorting order by Comparator.
For predefined non Comparable classes (Like StringBuffer) default natural sorting order is
not available, we have to define our own sorting order by using Comparator Object.
For our own classes(Like Customer,Student and Employee) we can define default natural
sorting order by using Comparable interface. The person who is using our class, if he is not
satisfied with default natural sorting order then he can define his own sorting order by
using Comparator Object.
Example:
import java.util.Comparator;
import java.util.TreeSet;
class Employee implements Comparable {
String name;
int eid;
163
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
164
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
t.add(e4);
t.add(e5);
System.out.println(t);
TreeSet t2=new TreeSet(new MyComparator());
t2.add(e1);
t2.add(e2);
t2.add(e3);
t2.add(e4);
t2.add(e5);
System.out.println(t2);
}
}
165
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Map category
Map interface is not child interface of Collection and hence we cannot apply Collection
interface methods. Map interface defines the following specific methods.
1) Object put(Obect key,Object value);
2) void putAll(Map m);
3) Object get(Object key);
4) Object remove(Object key);
5) boolean containsKey(Object key);
6) boolean containsValue(Object value);
7) boolean isEmpty();
8) int size();
9) void clear();
10) Set keySet(); //We will get the set of keys
11) Collection values(); //We will get the set of values
12) Set entrySet(); //We will get the set of entryset
HashMap
-> HashMap is the implementation class of Map interface which is used to store group of
objects in the form of Key-Value pairs where but Keys cannot be duplicated but values can
be duplicated
166
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
167
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
LinkedHashMap
-> LinkedHashMap is the implementation class of Map interface which is also used to store
group of3 objects in the form of Key-Value pairs where Keys can't be duplicated but values
can be duplicated
-> LinkedHashMap internally follows Hashtable + doubly linked list structures
-> LinkedHashMap is not a synchronized class
-> LinkedHashMap supports only one null value for Key Objects but we can store multiple
null values for Value Object
-> LinkedHashMap is called as ordered Map because it is guarantee for insertion order of
elements.
SortedMap:
-> It is the child interface of Map.
-> If we want to represent a group of key-value pairs according to some sorting order of
keys then we should go for SortedMap.
-> Sorting is possible only based on the keys but not based on values.
-> SortedMap interface defines the following 6 specific methods.
1) Object firstKey();
2) Object lastKey();
3) SortedMap headMap(Object key);
4) SortedMap tailMap(Object key);
5) SortedMap subMap(Object key1,Object key2);
6) Comparator comparator();
TreeMap
-> TreeMap is the implementation class of Map interface which is also used to store group
of objects in the form of Key-Value pairs where Keys can't be duplicated but values can be
duplicated.
-> TreeMap internally follows tree structure
-> TreeMap is not a synchronized class
-> TreeMap is called as unordered Map because it is not guarantee for insertion order of
elements, but. all elements are
168
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Hashtable
-> Hashtable is the implementation class of Map interface which is also used to store group
of objects in the form of Key-Value pairs where Keys can't be duplicated but values can be
duplicated
-> Hashtable is exactly similar to HasMap but Hashtable is a synchronized class where
HashMap is not a synchronized class
-> Hashtable does not support null values for both Keys and Values
Constructors:
1) Hashtable ht=new Hashtable();
It creates an empty Hashtable Object with default initial capacity 11 and default fill ratio
0.75
2) Hashtable ht=new Hashtable(int initialCapacity);
3) Hashtable ht=new Hashtable(int initialCapacity,float fillRatio);
4) Hashtable ht=new Hashtable(Map m);
169
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
IdentityHashMap
It is exactly same as HashMap except the following differences.
1) In the case of HashMap JVM will always use equals() method to identify duplicate keys.
2) But inn the case of IdentityHashMap JVM will use == (double equal to operator) to
identify duplicate keys.
Example:
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap hm=new HashMap();
Integer i1=new Integer(10);
Integer i2=new Integer(10);
hm.put(i1,"John");
hm.put(i2,"Smith");
System.out.println(hm);//{10=Smith}
}
}
In the above program i1 and i2 are duplicate keys because i1.equals(i2) returns true.
In the above proggram if we replace HashMap with IdentityHashMap then i1 and i2 are not
duplicate keys because i1==i2 returns false. In this case the output is as below.
Here 10==i1 is false
Here 10==i2 is false
WeakHashMap:
-> It is exactly same as HashMap except the following differences.
-> In the case of normal HashMap, an Object is not eligible for Garbage Collection even
though it does not have any references if it is associated with HashMap. That means
HashMap dominates Garbage Collector.
-> But in the case of WeakHashap if an Object does not have any references, then it is
always eligible GC even though if it is associated with WeakHashMap that means GC
dominates WeakHashMap.
170
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
In the above program if we replace WeakHashMap with normal HashMap then Object won't
be destroyed by the garbage collector.
Properties:
1) Properties class is the child class of Hashtable.
2) If anything changes frequently such type of values not recommended to hardcode in java
application because for every change we have to recompile, rebuild and redeploy the
application and even server restart also required. Sometimes it creates big business impact
to the client.
3) Such type of variables we have to hardcode in property files and we have to read the
values from the property files.
4) The main advantage in this approach is if there is any change in property files
automatically those changes will be available to java application just redeployment is
enough.
5) By using Properties Object, we can read and hold properties from property files into java
application.
171
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Constructor:
Properties p=new Properties ();
In Properties both key and value should be String type only.
Methods:
1) String getProperty (String propertyName);
2) String setProperty(String propertyName,String propertyValue);
3) Enumeration propertyNames();
4) void load(InputStream is);
5) void store(OutputStream os,String comment);
172
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Collections
-> Collections class is one of the utility classes in Java Collections Framework.
-> The java.util package contains the Collections class.
-> Collections class is basically used with the static methods that operate on the collections
or return the collection.
-> All the methods of this class throw the NullPointerException if the collection or object
passed to the methods is null.
Methods
173
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
174
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Knowledge – Check
1) What is Collection and why we need it?
2) What is Collection framework?
3) What is List and when to use it?
4) How ArrayList works internally?
5) How LinkedList works internally?
6) When to use ArrayList and When to Use LinkedList?
7) What is Cursor and How many cursors available?
8) What is Set?
9) How HashSet works internally?
10) What is TreeSet and when to use it?
11) What is Comparable?
12) What is Comparator?
13) How to sort Objects?
14) What is Map and when to use it?
15) What is Hash Map?
16) How HashMap works internally?
17) How to iterate a Map?
18) What is Weak HashMap?
19) What is Identity HashMap?
20) What is Collections?
21) What is Properties Class?
22) What are Fail-fast collection and Fail-Safe Collection?
175
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
176
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Chapter – 9
Multi - Threading
177
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Single tasking:
Single tasking means executing 1 task at a time. Here much of the processor time will be
wasted
because waiting time very high and processor gives response late.
Eg: DOS OS
Multi-tasking:
Multi-tasking means executing multiple tasks at the same time simultaneously. Here
processor time utilized in a proper manner and performance of the application by reducing
waiting time and processor gives response faster.
Eg: Windows OS, Student can listen and can write at a time
We can achieve multitasking in following 2 ways
1. Processor based multi-tasking
-> Processor based multi-tasking means executing multiple tasks at the same time
simultaneously where each task is independent of other tasks having separate memory and
resources
-> Processor based multi-tasking is an operating system approach
Eg:
java program,
listen to music,
download songs,
copy softwares,
chating,
....
2. Thread Based multi tasking
-> Thread based multi tasking means executing different parts of the same program at the
same time simultaneously where each task is independent sometimes or dependent
sometimes of other tasks which are having common memory and resources.
-> Thread based multi tasking is programming approach
-> Each different of the program is called Trheads
Eg: games, web based apps,....
178
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Thread vs Process :
Process : a program execution is often referred as process.
Thread : a Thread is subset(part) or sub process of the process.
(or)
A thread is flow of execution and for every thread separate independent job(task).
NOTE: weather it is process based or thread based the main objective multitasking is reduce
responsive time of the system and improve the performance.
Advantage of Multithreading
Multithreading reduces the CPU idle time that increase overall performance of the system.
Since thread is lightweight process then it takes less memory and perform context switching
as well that helps to share the memory and reduce time of switching between threads.
Main Thread
-> For every java program there will be a default thread by JVM which is called as Main
Thread.
-> The entry point for Main Thread is main() method
// wap to display the info of currently Running Thread
179
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
New: A thread begins its life cycle in the new state. It remains in this state until the start()
method is called on it.
Runnable: After invocation of start () method on new thread, the thread becomes runnable.
Running: A thread is in running state if the thread scheduler has selected it.
Waiting: A thread is in waiting state if it waits for another thread to perform a task. In this
stage the thread is still alive.
Terminated: A thread enter the terminated state when it completes its task.
180
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
181
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
182
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Q ) What is the difference between extending Thread class and implementing Runnable
interface
-> If we create any thread by extending Thread class then we have no chance for extending
from any other class.
-> But if we create any thread by implementing Runnable interface then we have a chance
for extending from any one class.
-> It is always recommended to create the user defined threads by implementing Runnable
interface only.
183
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Note: When we call start ( ) method it is creating thread and printing output like below
Thread-0 Thread Value:1
Thread-0 Thread Value:2
Thread-0 Thread Value:3
Thread-0 Thread Value:4
Thread-0 Thread Value:5
184
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Note: When we call run ( ) method it is not creating thread and printing output like below
with main thread
main Thread Value:1
main Thread Value:2
main Thread Value:3
main Thread Value:4
main Thread Value:5
185
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
186
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
1. synchronized blocks
If we want to synchronize a group of statements then we have to go for synchronized blocks
syntax:
synchronized(object) {
//statements
}
2. synchronized methods
If we want to synchronize all the statements of the particular method then we have to go
for synchronized methods.
syntax:
synchronized returntype methodname(parameters){
//statements;
}
Note: Thread synchronization concept is recommended to use only when we run multiple
threads which are acting on same object otherwise this concept is not required.
187
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
188
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
}
synchronized (resource1) {
System.out.println("Thread 2: locked resource
1");
}
}
}
};
t1.start();
t2.start();
}
}
Daemon Thread
-> Daemon threads is a low priority thread that provide supports to user threads. These
threads can be user defined and system defined as well.
-> Garbage collection thread is one of the systems generated daemon thread that runs in
background.
-> When a JVM founds daemon threads it terminates the thread and then shutdown itself, it
does not care Daemon thread whether it is running or not.
189
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Note: We must call wait(), notify(), notifyAll() methods in side the synchronized blocks or
synchronized methods otherwise it will throw a runtime exception called
IllegalMonitorStateException.
190
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
package in.ashokit;
int value;
boolean pro_thread = true;
Producer(Store sr) {
this.sr = sr;
}
191
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
i++;
}
}
}
Store sr;
Consumer(Store sr) {
this.sr = sr;
}
class ProducerConsumer {
public static void main(String args[]) {
Store sr = new Store();
Producer p = new Producer(sr);
Consumer c = new Consumer(sr);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
192
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Knowledge – Check
1) What is Multi - Threading?
2) Why we need multi-Threading?
3) What is Thread Schedular?
4) What is Thread Priority?
5) What is Thread Life Cycle?
6) How to create Thread?
7) Difference between start () method and run ( ) method ?
8) Thread vs Runnable
9) Runnable Vs Callable
10) What is Synchronization
11) Synchronized Method Vs Synchronized Block
12) What is Dead Lock
13) Write a java program which gives Dead Lock
14) What is Inter - Thread Communication
15) What is Producer – Consumer problem
16) What is Executor Framework
193
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Chapter – 10
▪ File Handling Introduction
▪ File
▪ FineReader
▪ FileWriter
▪ Serialization
▪ De-Serialization
194
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
File Handling
-> File handling is a crucial part of any programming language.
-> File handling means performing various operations on a file, like reading, writing, editing,
etc.
Common file handling operations
-> Java uses i/o stream to perform file-related operations. Let us understand the concept of
stream first.
Stream in Java
-> Stream is a concept of java that pipelines a sequence of objects to obtain the desired
result.
-> A stream cannot be called to be a data structure, rather it just takes input from the
collection of I/O.
-> A stream can be classified into two types: Byte Stream and Character Stream.
195
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Byte Stream:
The byte stream deals with mainly byte data. We know that one byte is equal to eight-bit.
Thus, this stream mainly deals with 8bit of data. This stream performs an Input-output
operation per 8bit of data.
The byte stream contains two stream classes, Input Stream classes and Output Stream
Classes.
1. Input Stream Classes: This stream helps take input(Read Data) from the collection in I/O
File.
2. Output Stream Classes: This stream helps to give output(Write Data) into the collection in
I/O File.
The most commonly used Input and Output Stream Classes are FileInputStream and
FileOutputStream.
Character Stream:
There is also Character Stream which allows I/O operation on 16bit of Unicode data at a
time. Character Stream takes 2 bytes of data at a time. It is faster as it can take double the
intake as compared to a byte stream. Character streams usually use Byte Stream classes to
implement operations.
The two main classes used in Character Stream are FileReader and FileWriter.
-> A file is a named location that can be used to store related information. For example,
-> main.java is a Java file that contains information about the Java program.
196
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Note: Using java program we can create both files and directories
-> The File class has many useful methods for creating and getting information about files.
For example:
197
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
198
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Scanner Class
-> Scanner class is mostly used to scan the input and read the input of primitive (built-in)
data types like int, decimal, double, etc.
-> Scanner class basically returns the tokenized input based on some delimiter pattern.
-> A Scanner class implements Iterator (string), Closeable, and AutoCloseable interfaces.
199
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
• java.io.serializable
• java.io.Externalizable
• ObjectInputStream
• ObjectOutputStream
Java Marker interface
Marker Interface is a special interface in Java without any field and method.
Marker interface is used to inform compiler that the class implementing it has some special
behaviour or meaning. Some examples of Marker interface are,
• java.io.serializable
• java.lang.Cloneable
• java.rmi.Remote
• java.util.RandomAccess
All these interfaces does not have any method and field. They only add special behaviour to
the classes implementing them.
To implement serialization and deserialization, Java provides two classes
ObjectOutputStream and ObjectInputStream.
ObjectOutputStream class
It is used to write object states to the file. An object that implements java.io.Serializable
interface can be written to strams. It provides various methods to perform serialization.
200
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.
// Serialization Example
201
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
202
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
203
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Knowledge – Check
1) What is File Handling
2) What is File class
3) What are the methods available in File class
4) What is FileReader and FileWriter
5) How to read data from a File
6) How to write data into File
7) BufferedReader class vs FileReader class
8) Copy data from One file into another file
9) Read data from two files and write into another file
10) Write a java program to count no.of words in a file
11) What is Scanner class
12) What is Serializable interface ?
13) What is Serialization ?
14) What is De-Serialization ?
15) What is serialVersionUID
16) What is transient keyword
204
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Chapter – 11
• Generics
• Garbage Collection
• Reflection API
• Inner Classes
205
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Java Generics
-> Generics was first introduced in Java 1.5. Now it is one of the most profound features of
java programming language.
-> Generic programming enables the programmer to create classes, interfaces and methods
in which type of data is specified as a parameter.
-> Generics provide type safety. Type safety means ensuring that an operation is being
performed on the right type of data.
Note: Before Generics was introduced, generalized classes, interfaces or methods were
created using references of type Object because Object is the super class of all classes in
Java, but this way of programming did not ensure type safety.
Note: This is also known as Diamond Notation of creating an object of Generic type.
Generic class
Generic class is a class which can hold any kind of objects, to create Generic class we have to
specify generic type <T> after the class name.
syntax:
-> We can take multiple Generic Types also for class like below
206
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Generic interfaces
We can also create a generic interface by specifying the <T> after the interface name.
syntax:
In the above program, we first passed an Integer type parameter to the Generic class. Then,
we passed a String type parameter to the same Generic class. Hence, we reused the same
class for two different data types. Thus, Generics helps in code reusability with ease.
207
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Uses of Reflection
• Developing IDE
• Debugging and Test tools
• Loading drivers and providing dynamic information
Disadvantages of Reflection
• Low performance
• Security risk
• Violation of Oops concept
208
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Class.forName ( )
-> Class is a predefined class available in java.lang package.
-> Inside Class we have a static method which is Class.forName(String cls). This method is
used to load classes into JVM using fully qualified name.
209
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
// Java program to access private variable outside the class using Reflection
-> By default private variables can’t be accessed outside of the class. By using Reflection api
we can access them outside of the class like below
210
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Note: Like fields and methods we can get Constructors info also using Reflection API.
211
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
This object of human named “Ashok” is now eligible for garbage collection.
An object is eligible for garbage collection if there are no references to it in the heap
memory.
There are a few ways to make an object eligible for garbage collection. They are:
Finalization in Java
-> As soon as the garbage collector clears the object, the compiler executes the finalize()
method.
-> This method generally contains actions which the JVM performs just before the object
gets deleted.
-> The Object class contains the finalize() method. Remember to override the finalize
method in the class whose objects will be garbage collected.
-> The finalize method throws a checked exception called “Throwable”.
212
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
213
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
-> Memory can be compacted after the garbage collector deletes the dead objects, so that
the remaining objects are in a contiguous block at the start of the heap.
The compaction process makes it easier to allocate memory to new objects sequentially.
214
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Here
A - outer class or top-level class
B - inner class
-> Here outer class can be default or public only but not private or protected or static
-> But inner class can be default or public or private or protected or static
-> The main advantage of Inner classes is that we can access the members of (both instance
and static) Outer class inside the inner class directly without taking the help of any object.
-> inner classes can also be called as helper classes
-> inner classes are hidden from other class of same package or other package
Types of inner classes
We have following 2 types of inner classes
1. non-static Inner classes
2. static Inner classes
1. non-static inner classes
-> If any inner class is created without using any static keyword then it is called as non-static
Nested classes or Inner classes
-> Non-static Nested or Inner classes can contain only non-static members(instance
members)
215
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
-> based on the place where we declare these inner classes are again classified into
following 3 types
1. Regular Inner class (member level)
2. Method local Inner class (statement level)
3. Anonymous Inner class(expression level
1. Regular Inner class
-> If an inner class is declared outside the methods of Outer class then it is called as Regular
Inner class.
-> Regular Inner class are always created at member level
-> Regular Inner class can be default or public or private or protected
syntax:
if we compile the above program compiler will generate .class for both outer class and inner
class
available in the program like follows,
1 Outer.class 2. Outer$Inner.class
// Creating an object for Regular Inner class inside the instance methods of Outer class
216
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
-> if we compile the above program then compiler will create following 2 .class files
1. Outer.class 2.Outer$1Inner.class
3. Anonymous Inner class
-> If any inner class is declared with out any name then it is called as Anonymous Inner class
-> Anonymous inner classes are always created at expression level
-> If we want to create Anonymous Inner classes we have to take the help of any existing
class or interface
-> At the time of creating the object of Anonymous Inner classes only Anonymous Inner
classes will be created.
-> For anonymous classes we can create only 1 object because it does't contain any name so
that memory can be utilized properly.
// anonymous inner class using Interface
217
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
218
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Knowledge – Check
1) What is Generics and why we need Generics?
2) What is Reflection API ?
3) What is the use of Class.forName ( )
4) How many ways available to create Object for a class ?
5) Write a java program to print methods available in the class
6) Write a java program to print variables available in the class
7) How to set values to private variables outside of class
8) What is Garbage Collection?
9) How Garbage Collection works in Java?
10) Which algorithm used by Garbage Collector?
11) How many types of Garbage Collectors available in Java?
12) What is Inner class?
13) Why we need inner classes?
14) How many types of inner classes available in Java?
15) What is Anonymous implementation ?
219
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Chapter - 12
JAVA 8 – New Features
220
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Java 8 Features
-> Java 8 introduced lot of new features
-> Java 8 version changed coding style with those new features
Main aim of java - 8
-> To simplify programming
-> To enable functional programming
-> To write more readable & concise code
New Features in Java 8
221
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
-> In this example we have only four classes that implements the interface, but imagine if
there are hundreds of classes implementing an interface it will become very difficult to
change all the classes which are implementing that interface. This is why in java 8, we have a
new concept “default methods”.
-> Default methods can be added to any existing interface and we do not need to
implement these methods in the implementation classes (if required we can override them
in implementation classes)
// java program on Interface – Default Method
222
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
223
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
224
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
225
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
226
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
227
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Predicate
-> It is used to perform some conditional check and returns true or false value
Ex: Check weather no is greater than 10 or not
Note: Predicate is boolean valued function in java 8
Syntax:
interface Predicate<T>{
boolean test(T k);
}
Predicate Joining
-> To combine multiple predicates, we will use predicate joining
-> In Predicate we have below methods
test () - > abstract method
p1.negate();
p1.and(p2);
p1.or(p2);
Note: negate(), and() , or() methods are default methods in Predicate interface
228
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
229
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
BiPredicate interface
-> The Predicate<T> takes only one parameter and returns the result. Now suppose we have
a requirement where we need to send two parameters (i.e person object and min age to
vote) and then return the result. Here, we can use BiPredicate<T, T>.
-> The BiPredicate<T, T> has a functional method test(Object, Object) . It takes in two
parameters and returns a boolean value.
230
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Supplier
-> Supplier is an interface that does not take in any argument but produces a value when
the get() function is invoked. Suppliers are useful when we don’t need to supply any value
and obtain a result at the same time.
-> The Supplier<T> interface supplies a result of type T.
-> It is a predefined functional interface
-> It contains only one abstract method i.e get ( )
-> Supplier will only returns the value R
Consumer
-> It is a predefined functional interface
-> It contains one abstract method i.e accept (T t)
-> Consumer will accept values and will perform operation but it won't return any value
-> A consumer can be used in all contexts where an object needs to be consumed. taken as
input, and some operation is performed on the object without returning any result.
231
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
BiConsumer<T,U>
This interface takes two parameters and returns nothing.
T - the type of the first argument to the operation
U - the type of the second argument to the operation.
This interface has the same methods as present in the Consumer<T> interface.
Function
-> Function is a category of functional interfaces that takes an object of type T and returns
an object of type R.
-> Until now, the functional interfaces that we’ve discussed have either not taken any
argument (Supplier), not returned any value (Consumer), or returned only a boolean
(Predicate).
-> Function interfaces are very useful as we can specify the type of input and output.
-> It is a predefined functional interface
232
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Function Chaining
-> To join one function with another function we will use Function Chaining
Assume that f1 & f2 are 2 functions
f1.andThen(f2) ----> First f1 will be applied and then followed by f2
f1.compose(f2) ----> First f2 will be applied and then followed by f1
compose(Function<? super V, ? extends T> before)
Returns a composed function that first applies the function provided as a parameter on the
input, and then applies the function on which it is called, to the result.
andThen(Function<? super R,? extends V> after)
This method returns a composed function that first applies the function on which it is called
on the input, and then applies the function provided as parameter, to the result.
233
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
BiFunction<T,U,R>
The BiFunction<T, U, R> is similar to Function<T, R> interface; the only difference is that the
BiFunction interface takes in two parameters and returns an output.
In the below example, we will create a BiFunction that takes two numbers as input and
returns their sum.
234
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
235
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
236
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
237
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
-> To avoid abnormal termination, we use the Optional class. In the following example, we
are using Optional. So, our program can execute without crashing.
238
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
-> Optional is a container object which may or may not contain a non-null value. You must
import java.util package to use this class. If a value is present, isPresent() will return true
and get() will return the value.
Java 8 StringJoiner
-> In java 8, a new class StringJoiner is introduced in the java.util package.
-> Using this class we can join more than one strings with the specified delimiter, we can
also provide prefix and suffix to the final string while joining multiple strings.
239
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Stream API
-> Stream API introduced in java 8
-> Collections are used to Store the data
-> Stream is used to process the data
Note: Collections & Streams both are not same.
-> The addition of stream api was one of the major features added to java8.
-> A stream in java can be defined as a sequence of elements from a source that supports
aggregate operations on them.
-> The source here refers to collection or array that provide data to stream
Few Important points about Streams
1) Stream is not a data structure. It is a bunch of operations applied to a source. The source
can be a collection, array or i/o channels.
2) Streams don't change the original data structure
3) There can be zero or more intermediate operations that transforms a stream into another
stream. Each intermediate operation is lazily executed
5) Terminal operations produce the result of the stream.
Stream Creation
-> In java 8 we can create stream in 2 ways
1) Stream.of(v1, v2, v3...)
2) stream() method
240
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
241
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
// Java program to filter the names which are starting with ”A”
242
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
243
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
244
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
-> When we have Collection inside another collection then to flaten that stream we will use
flatMap( ) method.
245
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Note: The above 3 methods are intermediate methods only. They perform operation and
returns new stream.
246
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
• findFirst()
• findAny( )
Collectors In Streams
-> Collectors operations are used to collect from Streams
-> We are having below methods to perform Collectors operations
Collectors.toList()
Collectors.toSet()
Collectors.toMap()
Collectors.toCollection() etc..
247
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
248
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
249
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Group By Operation
Parallel Streams
-> Streams is one of the major change added in java 1.8 version
-> Generally Streams will execute in Sequential manner
-> We can use parallel streams also to execute program faster by utilizing system resources
efficiently.
-> Parallel Streams introduced to improve performance of the program.
250
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
Java Spliterator
Like Iterator and ListIterator, Spliterator is a Java Iterator, which is used to iterate elements
one-by-one from a List implemented object. Some important points about Java Spliterator
are:
251
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
252
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
253
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
254
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
255
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com
Core Java Mr. Ashok
256
Ashok IT, Phone: +91 9985396677 , Email: [email protected], www.ashokitech.com