Core Java Basics
Core Java Basics
1. Data Types
2. Variables
3. Operators
4. Conditional Statements
5. Control Statements (loops)
6. Arrays
7. Functions / Methods
Data Types:
Data types are used to allocate memory and specify what type of data you are using in the
program.
All the data types are keywords which are having built in meaning. Below are the few data
types in Java.
1. int: which is used to store integer value and it will not accept any decimal value. It
allocates 4 bytes of memory.
2. long: which is used to store integer value and it will not accept any decimal value. It
allocates 8 bytes of memory
3. float: which is used to store decimal value. It allocates 4 bytes of memory
4. double: which is used to store decimal value. It allocates 8 bytes of memory
5. char: which is used to store single character and it use to take only one byte.
6. Short: which use to take 2 bytes of memory and stores integer value.
7. Boolean: which takes only true or false
8. Byte: which takes only byte memory
String:
It is not a data type but it is a predefined class. It allows to store set of characters.
Variables:
Variables are nothing but in which data is stored. It is nothing but memory location name by
which you can refer your data.
datatype variablename=value
int b=20
int c=a+b
Rules to follow for declaring the variable name:
1. Should start with lower case and first letter of the second word should start with
captial letter. i.e. firstName, orderNumber
2. Can start with _ (under score)
3. Can start with $
4. First letter cannot be a capital letter
5. It can contain numbers but not in the middle
6. No other special symbols allowed
Operators:
1. Arithmetic:
a. +
b. -
c. *
d. /
e. % (moduls) which gives remainder
2. Relation Operator:
a. >
b. <
c. >=
d. <=
e. !=
4. Concatenation Operator:
b. +: is used to value with string or string with value
int b=10
a+b=Ashok10
b+a=10Ashok
5. Logical Operators
a. &&(And operator)
b. ||(OR operator)
c. ! (logical not operator)
Conditional statements:
are used to execute set of statements based on the condition satisfaction.
1. if
2. else
3. else if
4. nested if
1.if:
Syn: if(condition)
statements;
2.if-else:
syn: if(condition)
statements;
else
statements;
}
3.else-if
syn: if(condition)
statements;
else if(condition)
statements;
}
else
statements;
If(conditions)
If(condition)
Statements;
Note: if you have only one statement inside the condition statement no need to write
opening curly bracket and close curly brackets.
Switch: Unlike if-then and if-then-else statements, the switch statement can have a number
of possible execution paths. A switch works with the byte, short, char, and int.
Syn:
Switch(expression)
case “a”:
statements;
break;
case “b”:
statements;
break;
default:
statements;
Note: Here “break” is a keyword which breaks the block in which it is used. Here it comes
outside switch after executing any of the case statements. If we do not write break here it
will continue to execute remaining case statements also.
Note :Continue : It is used to continue in the block of code .If we declare as continue in
block of code the remaining statements are not execute .
1. while
2. for
3. do-while
4. for each(Enhanced loop)
1. While Loop:
Syntax:
initialization;
while (condition)
statements;
Example:
int i=1;
while(i<=10)
{
statements;
i++ OR i=i+1;
From above code statements inside the loop will be repeated for 10 times.
You can implement an infinite loop using the while statement as follows:
boolean b=true;
while (b){
if(login==)
b=false
Note: You need to make sure make b value set to false to avoid infinite loop For Loop:
2.For Loop
Syntax:
statements;
Example:
Statements;
3.do-while syn:
do
statements;
The difference between do-while and while is that do-while evaluates its expression at the
bottom of the loop instead of the top. Therefore, the statements within the do block are
always executed at least once
Example:
do
Statements;
}while(i<=10);
4. for each
Syntax:
for(initialization)
statements;
Example:
For(int i:rollNo)
Statements;
Arrays:
Arrays is nothing but set of similar elements stored in single variable.
If we take a normal variable (int x;) it will take / store only one value at a time and we
cannot store more than one value.
Let’s say I would like to write a program where I want to store student role numbers for
college in which there are 1000 students available. If I use normal variable I have to declare
thousand variables like below:
int rolno1=1;
int rolno2=2;
int rolno3=3
And it goes on till
int rolno1000=1000;
Here you are spending more time in declaring variable rather than writing actual program.
So to avoid this we can go for using arrays where you can declare only one array variable
and store 1000 values in this variable.
Declaration of Arrays:
From above line we are declaring rolno variable as an array and we specifying size as 1000
which means rolno variable can be used to 1000 values in one array variable.
We are using “new” here new is a key word which basically used to allocate the memory.
We will discuss about “new” key word in coming topics in detail.
In above we understand that we have allocated the size of array as 1000 and stores 1000
integer values in the variable called rolno.
Let’s assign values for array: arrays index always starts with zero
rolno[0]=1;
rolno[1]=2;
rolno[2]=3;
rolno[3]=4;
rolno[999]=1000;
Since arrays starts with indexing zero last value will be stored always size – 1 which is 1000-
1= 999
Types of Array
1.If some functionality is performed at multiple places in software, then rather than writing
the same code, again and again, we create a function and call it everywhere. This helps
reduce code redundancy.
2.Functions make maintenance of code easy as we have to change at one place if we make
future changes to the functionality.
return-type
The return type of a function is the data type of the variable that that function returns.
For eg - If we write a function that adds 2 integers and returns their sum then the return
type of this function will be ‘int’ as we will return a sum that is an integer value.
When a function does not return any value, in that case the return type of the function is
‘void’.
function_name
Parameters
A function can take some parameters as inputs. These parameters are specified along with
their data types.
For eg- if we are writing a function to add 2 integers, the parameters would be passed like –
Types of functions/Methods :
1. Pre-defined: These functions are already defined and we can reuse these functions.
Example: main
2. User defined: Which we are going to define / write to our self.
Global Variable: Global variable is variable which can be access in entire program.
e.g., I declare any variable inside the class then this variable is known as global variable this
variable can be access in everywhere within the class.
Local Variable: Local variable is variable which is local to the block this variable can be
access within the block only.
e.g. Block can be a function or loop or block can be else if or block can be switch.
Main function
The main function is a special function as the computer starts running the code from the
beginning of the main function. Main function serves as the entry point for the program.
OOPs:
If any programming language that supports below futures, then that language is known as
OOPS language.
1. Class
2. Object
3. Polymorphism
4. Inheritance
5. Abstraction
6. Encapsulation
2. What is Class?
A class is a collection of variables and methods. Class is a logical entity and does not
consume any space. Class is a blueprint for creating object.
Data members(variables)
Data functions
String steering;
String break;
int wheels;
void run()
void reverseGear()
class <class_Name>{
Instance variable;// It means it is available in class but outside of the method .allocated
memory at runtime not compile time.
Methods ;//set of instructions/statements to perform a certain task.
Constructor; //it is a special type of method. The constructor name and class name it will
same. Constructor call after creating the object of the class.
}
3.What is Objects?
Objects are instance of the class and occupies some space in memory .Objects are real
world entity .Objects have some attribute and behaviour.
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen,
table, car etc. It can be physical or logical.
-2.By Method
Note: When an object is created using a new keyword, then space is allocated for the
variable in a heap, and the starting address is stored in the stack memory.
4. Encapsulation: /Data Hiding
What is Encapsulation?
Encapsulation is a mechanism of wrapping the data (variables) and code acting on the data
(methods) together as a single unit.(Encapsulation simply means binding object state(fields)
and behaviour(methods) together, If you are creating class, you are doing encapsulation.)
or
Encapsulation is the process of combining data and functions into a single unit called class.
Implementation of Encapsulation
1) Make the instance variables private so that they cannot be accessed directly from outside
the class. we can only set and get values of these variables through the methods of the
class.
2) Have getter and setter methods in the class to set and get the values of the fields.
we are trying to hide the data from the rest of the world by providing the methods to access
the data
5.Constructors
Constructor is a special type of method which will have same name of the class.
Constructor is invoked at the time of object creation and no need to call the constructors
like functions. Constructors will not return a value not even void also.
Syntex of Constrctor:
Class className()
className()//
//constructor body
//initialize value of the class attrabitues
}}
Types of constructors:
class_name()
Initilization statements;
Initialization statements;
1.Functiions will return a value whereas constructor will not return any value.
2.Constructors will have same name of the class whereas functions will have the different
name.
Inheritance is a mechanism in which one object acquires all the properties and behaviors of
parent object.
The idea behind inheritance is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you reuse (or inherit) methods and fields,
and you add new methods and fields to adapt your new class to new situations.
Syntax of Inheritance
The keyword extends indicates that you are making a new class that derives from an existing
class. In the terminology of Java, a class that is inherited is called a superclass. The new class
is called a subclass.
Types of Inheritance
1. Single level:When one class inherits another class, it is known as single level
inheritance.
2. Multi level: Multilevel inheritance is a process of deriving a class from another
derived class.
3. Multiple (Java will not support multiple inheritance directly but we can implemented
indirectly using interface)
4. Hybrid inheritance :- Hybrid inheritance is a combination of simple, multiple
inheritance and hierarchical inheritance. If you are inheriting more than one type of
inheritance then it is called as hybrid inheritance.
Java does not support multiple inheritance however it can implemented using Interfaces.
1.Single Inheritance:
class Father
2.Multilevel Inheritance:
class GrandFather
A:We can overload main method which means I can have more than one main method in
my program.
If you have more than one main method which main will execute first?
Note: 1. We can inherit the default constructor but we cannot inherit the parameterize
constructor.
3.If you are use same method name of both parent and child class only child class method
will display.
7.Polymorphism:
Means many forms. More than one method will have same name.
- Method Overloading.
- Constructor Overloading.
1.Method overloading:
If a class have multiple methods by same name but different parameters, it is known as
Method Overloading.
Suppose you have to perform addition of the given numbers but there can be any number
of arguments, if you write the method such as add1(int,int) for two parameters, and
add2(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs. So, we
perform method overloading to figure out the program quickly.
Example:
class myTest{
Void myMethod(int a,int b,int c){
//statement
}
Void myMethod(int a,int b){
//statement
}
Void myMethod(int a,String empNo){
//statement
}
}
Note: Method Overloading is not possible by changing the return type of the method
Yes, by method overloading. You can have any number of main methods in a class by
method overloading.
2.Constructor Overloading:
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists. The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
Example:
class myMethod {
myMethod(int a,int b,int c){
//statement
}
myMethod(int a,int b){
//statement
}
}
Runtime polymorphism:
Runtime polymorphism is also known as dynamic polymorphism. Method overriding is an
example of runtime polymorphism.
It is achieved using method Overriding and this concept is implemented using inheritance.
1.Method Overriding
1.More than one method will have the same name but one is in super class and another one
is in sub class
2.Method in the sub class should have same prototype
3.We can call using super key word of super class method
Note:
-The method must have the same name as in the parent class.
-The method must have the same parameter as in the parent class.
-A method declared final cannot be overridden.
-A method declared static cannot be overridden.
-The access level cannot be more restrictive than the overridden methods’s access level.
8. “Super” keyword
Super keyword refers to object of super class.
Super keyword it is used to call the super class variable, Method and constructor.
When to use?
Note :1. When the super class and sub-class variable and method name both are same then
it can used only.
2.To avoid confusion between super class and sub-class variables and methods that
have same name we should use super keyword.
Whenever the name of instance and local variable both are same then our runtime
environment JVM gets confused , which one is local variable and which one is instance
variable , to avoid this problem we can use this keyword.
It is also used when we want to call the default constructor of it’s own class.
Eg.class A{
A(){
{
A(int a){
this();
10. Abstraction
Exposing only required /important things is called abstraction.
1.Abstract class
2.Interface
1. Abstract Class:
A class which contains the abstract keyword in it’s declaration as abstract class.
or
Abstraction is the process in java to hide the information about implementation from the
user and provide required data.We Can Achieve from that hide the complexity and details
from the user
1. We cannot create object of abstract class ,to access it, it must be inherited from
another class.
2. It can have abstract and non-abstract methods. Abstract methods don’t have body
the body is provided by the sub-class (inherited from)
3. If a class contains partial implementation, then we should declare a class as abstract
4. It can have constructor and static methods.
5. It can have final methods which will force the subclass not to change the body of the
method.
Abstract Methods:
A method which contains abstract modifier at the time of declaration in called as abstract
method.
2.Interface
What is interface?
The interface is a mechanism to achieve fully abstraction in java. There can be only abstract
methods in the interface. It is used to achieve fully abstraction and multiple inheritance in
Java
Note:1. Before JDK 1.8 interface can only have abstract methods and all the abstract
methods of interface must be overridden in implementing class as well as methods are
public and abstract by default.
2.From JDK 1.8 onwards interface can have default and static methods.
3.From JDK 1.9 onwards interface can have private methods also, and we can declare this
private method as a static or non-static.
Points/Rules for Implementing Interface:
The java compiler adds public and abstract keywords before the interface method and
public, static and final keywords before data members.
Note: A class implements interface but One interface extends another interface
11.Instance block
Instance block is similar to method which has no name ,it can be written inside the class
only but not inside a method.
Note:
2.We can use variables only inside the instance block not method.
3.We write time-consuming code in side the instance block like -JDBC connectivity .
Eg. Class A {
// Code
}
12.Static key word in java
The static keyword is used in java mainly for memory management.
We may apply static keyword with variables, methods, blocks and nested class. The static
keyword belongs to the class than instance of the class.
● variable (also known as class variable)
● method (also known as class method)
● block
Static variable:
The static variable can be used to refer the common property of all objects (that is not
unique for each object)
The static variable gets memory only once in class area at the time of class loading.
Suppose there are 500 students in my college, now all instance data members will get
memory each time when object is created. All student have its unique rollno and name so
instance data member is good. Here, college refers to the common property of all objects.If
we make it static,this field will get memory only once
Static method:
If you apply static keyword with any method, it is known as static method.
A static method can be invoked without the need for creating an instance of a class.
ex classname.methodName();
Static method can access only static data member(Variables) and can change the value of it.
Note:
● The static method cannot use non static data member(Variables) or call non-static
method directly.
● this and super keywords cannot be used in static context.
Static block:
Static block will be given top most priority and this block will be executed before main itself.
1.static-we write it static JVM will call main method without any help of object only static
functions can be called with help of class name.
2.public -JVM should have permission to call main method so we write public so that jvm
can call the main method.
14.Package in Java:
Packages: Package statement in java means location where class is exit.
Package can be categorized in two form, built-in package and user-defined package. There
are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Advantage of Package:
•Package is used to categorize the classes and interfaces so that they can be easily
maintained.
Creation of Package:
Class Example
1. import packagename.*; It will import all the class and interfaces to this package. It is
recommended not to use this as it will impact on performance as it as to load all the class.
2. import packagename.classname;
Using packagename.*:
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
The import keyword is used to make the classes and interface of another package accessible
to the current package.
Using packagename.classname:
If you import package.classname then only declared class of this package will be accessible.
If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
15.Access Modifiers:
The access modifiers specify accessibility (scope) of a data member, method, constructor or
class.
Private:
The private access modifier is accessible only within class.
System.out.println("Hello java");
A obj=new A();
If you make any class constructor private, you cannot create the instance (object) of that
class from outside the class. For example:
class A
private A(){
}//private constructor
}
public class B
Default:
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package.
In this example, we have created two packages pack1 and pack2. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from
outside the package.
//save by A.java
package pack1;
class A
void method1(){System.out.println("Hello");}
//save by B.java
package pack2;
import pack1.*;
class B
{
A obj = new A();//Compile Time Error
In the above example, the scope of class A and its method method1() is default so it cannot
be accessed from outside the package.
Protected:
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor.
In this example, we have created the two packages pack1 and pack2. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
//save by A.java
package pack1;
public class A
System.out.println("Hello");
//save by B.java
package pack2;
import pack1.*;
class B extends A
{
public static void main(String args[])
obj.method1();
Output:Hello
Public:
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
//save by A.java
package pack;
public class A
System.out.println("Hello");
//save by B.java
package mypack;
import pack.*;
class B
16.Exception Handling
The exception handling is one of the powerful mechanisms provided in java.
It provides the mechanism to handle the run time errors so that normal flow of the
application can be maintained.
What is Exception?
An exception is unexcepted/abnormal/unwanted that situation occurs at runtime called
exception.
The core advantage of exception handling is that normal flow of the application is
maintained. Exception normally disrupts the normal flow of the application that is why we
use exception handling. Let's take a scenario:
1.statement 1;
2.statement 2;
3.statement 3;
4.statement 4;
5.statement 5;
6.statement 6;
7.statement 7;
8.statement 8;
9.statement 9;
10.statement 10;
Suppose there is 10 statements in your program and there occurs an exception at statement
5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform
exception handling, rest of the code will be executed. That is why we use exception
handling.
Types of Exception:
There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception. The sun microsystem says there are three types of
exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
A checked exception is an exception that is typically a user error or a problem that cannot
be foreseen by the programmer.
For example, if a file is to be opened, but the file cannot be found, an exception occurs.
These exceptions cannot simply be ignored at the time of compilation.
A runtime exception is an exception that occurs that probably could have been avoided by
the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the
time of compilation.
Errors:
These are not exceptions at all, but problems that arise beyond the control of the user or
the programmer. Errors are typically ignored in your code because you can rarely do
anything about an error. For example, if a stack overflow occurs, an error will arise. They are
also ignored at the time of compilation.
There are given some scenarios where unchecked exceptions can occur. They are as follows:
1. Scenario where Arithmetic Exception occurs: If we divide any number by zero, there
occurs an Arithmetic Exception.
String s=null;
System.out.println(s.length());//NullPointerException
1.try
2.catch
3.finally:
4.throw
5.throws
1.try :
The ‘try’ keyword used to specify the block where we should place an exception code.
Note: We cannot use only try block in the code.
2.catch:
The ‘catch’ block used to handle the exception. catch block will execute only if there is
exception. Catch block will not be executed if there is no exception.
Syntax of try with catch block
try
{
statements;20/0
}
catch(Exception_class_Name reference)
{
handle exception here;
}
Note: We can use more than one catch block for one try block.
3.Finally block:
The finally block is a block that is always executed. It is mainly used to perform some
important tasks such as closing connection, stream etc.
Note:1. Before terminating the program, JVM executes finally block(if any).
try
{
statements;
}
finally
{
handle exception here;
}
Rules:
● At a time only one Exception is occurred and at a time only one catch block is
executed.
● All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception.
finally block can be used to put "cleanup" code such as closing a file, closing connection etc
Note: For each try block there can be more catch blocks, but you can have only one finally
block.
Note: The finally block will not be executed if program exits(either by calling System.exit() or
by causing a fatal error that causes the process to abort).
Ans: catch block will execute only if there is an exception but finally block will be executed
all the time.
4.Throw:
The throw keyword is used to create a custom error. It is used to throw single exception for
a method.
Eg: Throw an exception if age is below 18(print “Access Denied”) if age 18 or older print
“Access granted”
5.Throws.
The throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow can be maintained.
statements;
● Final variable
● Final method
● Final class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block
only. We will have detailed learning of these. Let's first learn the basics of final keyword.
Finalize is a method which is going to be executed before garbage collector distorting the
object.
If you wanted to perform any actions before garbage collector distorting the object that
code we have to put it inside the finalize method.
Final variable:
If you make any variable as final, you cannot change the value of final variable (It will be
constant).
Final method:
Final class:
String s = 'saba';
In Java we have equals method in two classes one in object class and another is in string
class.
All the operations that you perform on a data such as searching, sorting, insertion,
manipulation, deletion etc. can be performed by Java Collections.
The collection framework represents a unified architecture for storing and manipulating
group of objects. It has:
It is a class it contains methods which are used to perform certain operation on the
collection object.It is available in java. util package
List (Interface(i) Child Interface)
1. List is the child interface of the collection interface.
2. Insertion order is preserved.
3. Duplicates object are allowed.
The following classes are implemented list interface
1.ArrayList 2. LinkList 3. Vector
Set (Interface(i) Child Interface)
1. Set is the child interface of the collection interface.
2. Insertion order is NOT preserved.
3. Duplicates object are NOT allowed.
The Following classes are implements set interface
1.HashSet 2. LinkedHashSet
Queue (Interface(i) Child Interface)
1. Set is the child interface of the collection interface.
2. objects are Prior to processing -FIFO First In First Out
No
Method Description
.
public boolean add(Object
1 is used to insert an element in this collection.
element)
public boolean is used to insert the specified collection elements in
2
addAll(Collection c) the invoking collection.
public boolean remove(Object
3 is used to delete an element from this collection.
element)
public boolean is used to delete all the elements of specified
4
removeAll(Collection c) collection from the invoking collection.
public boolean is used to delete all the elements of invoking collection
5
retainAll(Collection c) except the specified collection.
6 public int size() return the total number of elements in the collection.
7 public void clear() removes the total no of element from the collection.
public boolean
8 is used to search an element.
contains(Object element)
public boolean is used to search the specified collection in this
9
containsAll(Collection c) collection.
10 public Iterator iterator() returns an iterator.
11 public Object[] toArray() converts collection into array.
12 public boolean isEmpty() checks if collection is empty.
public boolean equals(Object
13 matches two collection.
element)
14 public int hashCode() returns the hashcode number for collection.
1.add(index,Object)
2.addAll(index,collection)
3.remove(index)
4.get(index))
5.set(index,object)
ArrayList (Class):
collection (i) -->List(i)--->ArrayList(class) available in java.util package
1.Hetrogenous and homogenious data
2.Duplicates element allowed.
3.Insercataion order is preserved.
4.Resiziable in array List(size of array fixed in array)
5.bydefault 10 size.
syntax:
Arrayliat al = new Arralylist();//Hetrogenous
Arrayliat <String> als = new Arralylist<String>(); //Homogenous data
Methods in ArrayList:
1.add(object)
2.add(index,object)
3.get(index)
4.set(index,object)
5.size()
6.clare()
7.remove(index)
8.containts(object)
9.addAll()
10.removeAll()
Collections class:
It is class avilabe in java.utils packag
All the methods are static methods in collections
1.sort()
2.sorting()
3.binarysearch()
4..shafaling()
Piratical -1 ArrayList
1. Add data to arraylist
2. print array list
3. size method
4. remove element -index= 1
5. Print array list after removing
6. get method -to access value/elements form array list
7. set method - to replace/change the value/elements from arraylist.
8. Print after set method
9. Insert element in array list -add(index,obj)
10. Print
11. Contains - to search element in array list
12. isempty-to check array list is empty
13. Clare - Remove all elements.
Pirtical -2 ArrayList
LinkedList(Class):
It is a class; Linked List implements List and Deque interface
We can use linked list when we have more interstation and delectation operations.
Link list used for stack and queue implementation.
Difference:
1.Frequently retrieving operations: AL-Yes LL-No
2.More Insert and delete operations : AL -No LL-Yes
Remove:
1.remove(obj)
2.remove(index)
3.removeAll(Collection)
Retrieve/Access:
1.get(index)
Replace:
1.set(index,obj)
HashSet(Classs):
collections(I)-->Set(I)-->HashSet(c)
1.Duplicaes not allowed. HashSet contains unique elements only.
2.Hashset allow null value.
3.Haset doesn’t maintain the insertion order , here element inserted on the basic of there
hash code.
3.Hashcode -To use identify the elements .
4.Not available index in HashSet.
5.Hashset is the best approach for search operations.
6.the initial default capacity of HashSet is 16, and the load of factor is 0.75
Creating a HashSet:
//HashSet with 8 capacity and 0.75 load factor
HashSet <Integer> number = new HashSet <Integer>(8,0.75);
Capacity : The capacity of the hash set is 8.Meaning , it can store 8 elements.
Load factor : The load factor of this hash set is 0.6. This means, whenever our hash set if
filled by 60%
the elements are moved to a new hash table.
The initial default capacity of HashSet is 16,and the load factor is 0.75
Remove Elements:
remove()-removes the specified element from the set
removeAll()-removes all the elements from the set
Other methods :
Set Operations:
A = {0,2,4,6,8}
B={1,2,3,4,5}
Output:
Union : [0,1,2,3,4,5,6,8]
Intersection : [2,4]
Difference: [8,0,6] A-B
Pritical-2
1.Add Collection - Integer
2.Add elements
3.All Collectin -Integer
4.Add Elements.
5.Union of two sets A and B using addAll methods
6.Print
7.intersection to two A and B -
8.retainAll(c)
9.print
10.difference of set A and B (A-B) setA.removeAll(setB);
11.print
12.check subset - Using containAll method
LinkedHashSet (Class) :
1.It is class, It’s implements set interface.
2.Duplicates not allowed
3.Insercation order maintain.
4.Hash Table and Linked List data structure
Difference:
Hash Set Linked HashSet
1.Duplicates not allowed 1.Duplicates not allowed
2.Insercation order not maintain. 2.Insercation order maintain.
3.Hash Table 3.Hash Table and Linked List
Piratical -1
1.Create linked hash set collection-Homogeneous
2.Add Elements.
3.Print and verify interaction order
4.Check duplicate order
Priority queue(Classs) :
Collection(i)-->Queue(i)-->child Interface -->dqueue,blockingqueue,blockingdequeue
Working:
1.FIFO -
2.Elements add from tell
3.Elements delete from front
Difference:
LL -Insercation order maintain PQ- Auto sort.
LL-Duplicates allowed PQ -Duplicates allowed.
LL-Heterogenous data PQ-Homogenous data stored
Access Element :
element()-Retunes the head of the queue, Throws an exception if the queue is empty.
peek()-Retunes the head of the queue. Retunes null if the queue is empty.
Remove element:
remove()-Returns and removes the head of the queue. Throws an exception if the queue is
empty.
poll()-Returns and removes the head of the queue ,Returns null if the queue is empty.
Map Interface:
-->Hash Map,Hash Table
Hash Map -:
1.It's provides functionality of the hash table data structure.
2.Insertion order is not preserved.
3.Duplicate key not allowed
4.Duplicates value is allowed.
5.Null key is allowed only one
6.Multiple null values are allowed.
Example :
HashMap<String,Integer> number = new HashMap<>();
Access Elements:
get() method-access the value from the HashMap.
chagne elements :
replace() method: to change the value associated with a kwy in a HashMap.
Remove Element:
remove() method: remove elements from a HashMap.
additional methods :
1.continsKey()-checks if the specified key is present in HashMap.
2.containsValue()-checks if HashMap contains the specified value.
3.size() - returns the number of items in hashmap.
4.isEmpty()-check if the HashMap is empty.
5.clare- clears all the entire from HashMap.
6.KeySet()-Return complete key set
7.Values()-Return the collection of string.
8.entryset()-Return the key/value pair.
Pritical-01:
1.create collection HashMap.
2.add elements to hashmap using put method.
3.print.
4.access the element - Using get() methos
5.Print
6.KeySet - Print the set of keys
7.Values()-Print the values
8.entrySet()-Return all the key/value pair.
9.Replace element - replace() and print.
10.Remove(k) - Key remove -Print
11.Remove(k,v)-Print
12.ContainsKey()-Print
13.ContainsValue()-Print+
14.Size
15.isEmpty
16.clare()
17.add collection 1 to 2 using putAll() method.
18.KeySet-print
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
LIST ARRAYLIST
List is an Interface. ArrayList is a Class.
List interface extends the Collection ArrayList extends AbstractList class and
framework. implements List interface.
List cannot be instantiated. ArrayList can be instantiated.
List interface is used to create a list of ArrayList class is used to create a dynamic
elements(objects) which are associated array that contains objects.
with their index numbers.