0% found this document useful (0 votes)
30 views

Core Java Basics

The document provides an overview of core Java basics including: 1. Common programming concepts like data types, variables, operators, and control structures. 2. Key Java concepts such as classes, objects, encapsulation, inheritance, polymorphism, packages and exception handling. 3. Additional Java topics like abstract classes, interfaces, access modifiers, and collections frameworks.

Uploaded by

pravin kumbhar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Core Java Basics

The document provides an overview of core Java basics including: 1. Common programming concepts like data types, variables, operators, and control structures. 2. Key Java concepts such as classes, objects, encapsulation, inheritance, polymorphism, packages and exception handling. 3. Additional Java topics like abstract classes, interfaces, access modifiers, and collections frameworks.

Uploaded by

pravin kumbhar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Core Java Basics:

1. Basics of any programing language.


2. What is Class
3. What is Object
4. Encapsulation
5. Constructors
6. Inheritance & Types of Inheritance
7. Polymorphism
a. Method Overloading
b. Method Overriding
8. Static Variables / Methods / Block
9. Super & This
10. Abstract class & Abstract methods
11. Interfaces
12. Packages
13. Access Modifiers
14. Exception Handling
15. Collections Interfaces
16. Final, Finalize and finally
17. Strings
1.Basics of any programing language:
Let’s try to understand the basics of any programing language before moving to Java:

Below are the common / basic futures of any programming language:

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.

Declarition and initilization of variable

datatype variablename=value

Ex: int a=10;

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. !=

3. Equality Operator / comparison:


a. == which checks for equality

4. Concatenation Operator:
b. +: is used to value with string or string with value

Ex: String a="Ashok"

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;

This block of statements will be executed only if the condition is true.

2.if-else:
syn: if(condition)

statements;

else

statements;

}
3.else-if
syn: if(condition)

statements;

else if(condition)

statements;

}
else

statements;

4.Nested if: writing if inside if

Example: Here we are writing one if inside another if condition itself.

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.

Same is applicable for loops as well.

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 .

Control statements (loops):


are used to execute set of statements as per defined number of times. All the programming
languages have below 3 types of loops.

1. while
2. for
3. do-while
4. for each(Enhanced loop)

1. While Loop:
Syntax:

initialization;

while (condition)

statements;

incrimination / decrementation of number

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){

// your code goes here

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:

for(initialization; condition; incrimination / decrementation of number)

statements;

Example:

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

Statements;

3.do-while syn:
do

statements;

incrimination / decrementation of number


}while(condition);

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;

incrimination / decrementation of number

}while(i<=10);

4. for each
Syntax:

for(initialization)

statements;

Example:

For(int i:rollNo)

Statements;

Note: For each loop mostly used for array.

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:

Data type arrayname []

Example: int rolno[];

Allocating Memory for Arrays:

int rolno[] = new int[1000];

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.

Initializing / assigning the values for Arrays:

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;

And it goes on….. Till

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. Single dimension array: Example int rolno[] = new int[1000];


2. Multi dimension array: Example int x[][]=new int[10][20];
Methods / Functions:
Functions/Method: A method is a block of code that performs a specific task(like
addition ,Subtraction and multiplication).

Why are functions used?

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.

3.Functions make the code more readable and easy to understand.

The syntax for function declaration is :

return-type function_name (parameter 1, parameter2, …… parameter n){ //function_body

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

It is the unique name of that function.

It is always recommended to declare a function before it is used.

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 –

int add (int num1, int num2)

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.

Life and scope of this variable with the block only.

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.

main is called by JVM(java Virtual Machine).

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

We will discuss each of these topics in the below.

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.

Syn: class Class_Name

Data members(variables)

Data functions

Ex: class Car

String steering;

String break;

int wheels;
void run()

void reverseGear()

-How to Declare a class?

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.

Syn: Class_Name objname = new Class_Name();

Ex: Car maruthi = new Car();

Car Skoda = new Car();

-How to create object of class.

We can create object of class using new keyword.

-How to initialize object /store data to object

-1.By Reference variable

-2.By Method

-3.By constructor (Will discuss in separate session )

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.

Why is encapsulation also called data-hiding?

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.

Constructor are mainly used to initialization of the data.


If there is no constructor in a class, compiler automatically creates a default constructor

There are basically three rules defined for the constructor.

1. Constructor name must be the same as its class name


2. Constructor must have no explicit return type.
3.A java constructor cannot be abstract ,static ,and final.
Note: We can have private, protected, public or default constructor in java.

Syntex of Constrctor:

Class className()

className()//

//constructor body
//initialize value of the class attrabitues
}}

Types of constructors:

1. Default constructor (no-arguments constructor)


2. Parameterized constructor

1.Default Constructor/Implicitly Constructor:


Constructor has no parameter is known as default constructor.
If you do not have any constructor in class by default compiler is going to add one default
constructor.
Syntax of default constructor:

class_name()

Initilization statements;

2.Parameterized constructor/Explicitly Constructor:

A constructor that have parameters is known as parameterized constructor.

Syntax of Parameterized constructor:

class_name(data type variable name, data type variable name)

Initialization statements;

Why use parameterized constructor?

Parameterized constructor is used to provide different values to the objects.

Difference between constructor and functions:

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.

3.No need to call constructor whereas functions must be called.


6.Inheritance:
Creating a new class from the existing class is called as inheritance.

Inheritance is a mechanism in which one object acquires all the properties and behaviors of
parent object.

Inheritance it is used for re-usability of code.

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.

Why use Inheritance?

● For Method Overriding (So Runtime Polymorphism).


● For Code Reusability.

Syntax of Inheritance

class Subclass-name extends Superclass-name

//methods and fields

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

//methods and fields

class Child extends Father

//methods and fields

2.Multilevel Inheritance:

class GrandFather

class Father extends GrandFather

//methods and fields

class Child extends Father

//methods and fields

Can I overload the main method? Yes

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?

A:The method which is having public static void main(String args)


Can we inherit the constructor?

A: No, we can inherit the constructor.

Note: 1. We can inherit the default constructor but we cannot inherit the parameterize
constructor.

2.inheritance, it is not support for constructor overloading.

3.If you are use same method name of both parent and child class only child class method
will display.

4.Final class can not be extend.

7.Polymorphism:
Means many forms. More than one method will have same name.

Polymorphism is achieved in two ways

1. Compile time polymorphism


2. Run time polymorphism

Compile time polymorphism:


The polymorphism which is implemented at the compile time is known as compile-time
polymorphism. Example - Method Overloading
It is achieved using method overloading and constructor overloading

- 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
}
}

Advantages of method overloading: Method overloading increases the readability of the


program

Different ways to overload the method

1. By changing number of arguments


2. By changing the data type

Note: Method Overloading is not possible by changing the return type of the method

Can we overload main() 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.

9.” this” keyword


This is a keyword which represents the current class object.

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();

Note: this cannot be used static context.

10. Abstraction
Exposing only required /important things is called abstraction.

Abstraction can achieve using Abstract class and Interface.

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

Eg. Abstract Class A(){

Points/Rules for Implementing Abstract class:

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.

1. It can only be used in abstract class.


2. It doesn’t contain any body “{ }” and always ends with “;”.
3. Abstract methods must be overridden in sub-class otherwise it will also become a
abstract class.
Syntax of Abstract class:

Example of abstract class:

abstract class A{}

Example of abstract method:

Abstract void abstractMethodName();//no method body

2.Interface
What is interface?

Ans: An interface is just like a class or An interface is a blueprint of a class.

which contains only static, ptivate , abstract and default methods.

Interface nothing but deles between client and developer.

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

It cannot be instantiated just like abstract class.

To achieve interface java provides a keyword called implements.

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:

1. We cannot create object for interface.


2. An interface does not contain any constructor.
3. All of the methods in an interface are by default abstract and public.(Before JDK 1.8)
4. Methods in interface are static and default (From JDK 1.8).
5. Methods in interface are private (From JDK 1.9).
6. Interface variables are by default public +static +constant/final.
7. Interface methods must be overwriting inside the implementing class.
8. An interface is not extended by a class; it is implemented by class.
9. Interface can extend multiple interfaces.
Note:
1. A class extends another class.
2. An interface extends another interface.
3. A Class can implement many interfaces.
Syntax:

Interface <interface name>{

//declare constant fields .interface fields public and constant by default.

//declare methods .Methods are public abstract by default.

Why use Interface?

•It is used to achieve fully abstraction.

•By interface, we can support the functionality of multiple inheritance.

The java compiler adds public and abstract keywords before the interface method and
public, static and final keywords before data members.

Multiple inheritances in Java by interface:

If a class implements multiple interfaces, or an interface extends multiple interfaces i.e.


known as multiple inheritance.

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:

1.It’s always executed before the constructor.

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:

If you declare any variable as static, it is known static variable.

The static variable can be used to refer the common property of all objects (that is not
unique for each object)

e.g. company name of employees,college name of students etc.

The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable:

It makes your program memory efficient (i.e., it saves memory).

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 belongs to the class rather than object of a class.

A static method can be invoked without the need for creating an instance of a class.

Static methods called by class name.

ex classname.methodName();

Static method can access only static data member(Variables) and can change the value of it.

static functions should be called with help of class name.

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:

It Is used to initialize (assign values) to the static variable.

Static block will be given top most priority and this block will be executed before main itself.

It is executed before main method at the time of class loading.

13.Why main method is static?


Because object is not required to call static method if it were non-static method, jvm create
object first then call main() method that will lead the problem of extra memory allocation

Why do you write public static void before main method?

-JVM will call main functions in the below

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.

import: If you want to show location of class to another class.

A package is a group of similar types of classes, interfaces and sub-packages.

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.

•Package provids access protection.

Creation of Package:

Package packageName; // this package contains class called Example

Class Example

Data & Methods

How to access package from another package?


There are three ways to access the package from outside the package.

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;

3. fully qualified name.

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.

Example: import packageName.*

Using packagename.classname:

If you import package.classname then only declared class of this package will be accessible.

Example: import of packageName.ClassName

Using fully qualified name

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.

There are 4 types of access modifiers:

1.private - The private modifier is accessible only within class.


2.default - The default modifier is accessible only within package.
3.protected
4.public

Private:
The private access modifier is accessible only within class.

A simple example of private access modifier


class A

private int x=40;

private void method1()

System.out.println("Hello java");

public class Simple

public static void main(String args[])

A obj=new A();

System.out.println(obj.x);//Compile Time Error

obj.method1();//Compile Time Error

Role of Private Constructor:

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

void msg(){System.out.println("Hello java");}

}
public class B

public static void main(String args[])

A obj=new A();//Compile Time Error

Note: A class cannot be private or protected except nested class.

Default:
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package.

Example of default access modifier

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

public static void main(String args[])

{
A obj = new A();//Compile Time Error

obj.method1();//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.

It can't be applied on the class.

Example of protected access modifier

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

protected void method1()

System.out.println("Hello");

//save by B.java

package pack2;

import pack1.*;

class B extends A

{
public static void main(String args[])

A obj = new A();

obj.method1();

Output:Hello

Public:
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.

Example of public access modifier

//save by A.java

package pack;

public class A

public void msg()

System.out.println("Hello");

//save by B.java

package mypack;

import pack.*;

class B

public static void main(String args[])

A obj = new A();


obj.msg();

Access modifiers by a simple table.

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.

● Dictionary Meaning: Exception is an abnormal condition.


● In java, exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.

Advantage of Exception Handling:

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

Checked exceptions: Compile Time 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.

Unchecked exceptions :Runtime exceptions:

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.

Common scenarios of Exception Handling where exceptions may occur:

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.

int a=50/0;//Arithmetic Exception


2. Scenario where NullPointerException occurs: If we have null value in any variable,
performing any operation by the variable occurs an NullPointerException.

String s=null;

System.out.println(s.length());//NullPointerException

3. Scenario where NumberFormatException occurs: The wrong formatting of any value,


may occur NumberFormatException. Suppose I have a string variable that have
characters, converting this variable into digit will occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException

4. Scenario where ArrayIndexOutOfBoundsException occurs: If you are inserting any


value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown
below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
What is the super class in exception handling?
Ans: Throwable is a super class of all exception.

Five keywords used in Exception handling:

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).

2. finally must be followed by try or catch block.

Syntax of try with finally block

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.

Why use finally block?

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).

Difference between catch and finally?

Ans: catch block will execute only if there is an exception but finally block will be executed
all the time.

Finally, block is used for cleaning of the code.

4.Throw:
The throw keyword is used to create a custom error. It is used to throw single exception for
a method.

Syntax: throw new exeception_class(“Error Message”);

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.

Syntax of throws keyword:

void method_name() throws exception_class_name

statements;

Differences between throw keyword and throws keyword

● throw is used to explicitly throw an exception.


● throws is used to declare an exception.
● throw is followed by an instance.
● throws is followed by class.
● throw is used within the method.
● throws is used with the method signature.
● You cannot throw multiple exception
● You can declare multiple exception e.g.public void method()throws
IOException,SQLException

17.Final Keyword in Java:


The final keyword in java is used to restrict the user. The final keyword can be used in many
contexts. Final can be

● 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.

Final is a keyword which can be used with the below.

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:

If you make any method as final, you cannot override it.

Final class:

If you make any class as final, you cannot extend it.

Is final method inherited?

final method is inherited but you cannot override it.

Can we initialize blank final variable?

Yes, but only in constructor.


18.Strings:
String are sequence of char values or collection of characters.
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.

String: is immutable (cannot be change) class.

We can create object of two ways

String s = 'saba';

String ss = new String ("Suasdfa");

String used string pull concept.

Methods of string class are -length, replace all ,substring,charat,index of etc

In Java we have equals method in two classes one in object class and another is in string
class.

Object class equals check address

String class equals check contents of string.

No. Method Description


1 char charAt(int index) returns char
value for the
particular index
2 int length() returns string
length
3 String toLowerCase() returns a string
in lowercase.
4 String toUpperCase() returns a string
in uppercase.
5 String toLowerCase(Locale l) returns a string
in lowercase
using specified
locale.
6 String toUpperCase(Locale l) returns a string
in uppercase
using specified
locale.
7 String replace(CharSequence old, CharSequence new) replaces all
occurrences of
the specified
CharSequence.
8 String replace(char old, char new) replaces all
occurrences of
the specified
char value.
9 int indexOf(int ch) returns the
specified char
value index.
10 String substring(int beginIndex) returns substring
for given begin
index.
11 boolean isEmpty() checks if string is
empty.
12 String substring(int startIndex, int endIndex) Returns a new
string that is a
substring of
string.
13 boolean contains(CharSequence s) returns true or
false after
matching the
sequence of
char value.
14 String trim() removes
beginning and
ending spaces of
this string.
15 Boolean startWith(String str) Check if the
string start with
the specified
substring
16 Boolean startWith(String str,int startIndex) Check if the
string start with
the specified
substring
starting from the
specified index
17 static String format(String format, Object... args) returns a
formatted string.
18 static String format(Locale l, String format, Object... returns
args) formatted string
with given
locale.
19 static String join(CharSequence delimiter, returns a joined
CharSequence... elements) string.
20 static String join(CharSequence delimiter, Iterable<? returns a joined
extends CharSequence> elements) string.
21 boolean equals(Object another) checks the
equality of string
with the given
object.

22 String concat(String str) concatenates


the specified
string.
23 static String equalsIgnoreCase(String another) compares
another string. It
doesn't check
case.
24 String[] split(String regex) returns a split
string matching
regex.
25 String[] split(String regex, int limit) returns a split
string matching
regex and limit.
26 String intern() returns an
interned string.

27 int indexOf(int ch, int fromIndex) returns the


specified char
value index
starting with
given index.
28 int indexOf(String substring) returns the
specified
substring index.
29 int indexOf(String substring, int fromIndex) returns the
specified
substring index
starting with
given index.
30 static String valueOf(int value) converts given
type into string.
It is an
overloaded
method.
19.Collections:
Collections in java is a framework that provides an architecture to store and manipulate the
group of objects.

All the operations that you perform on a data such as searching, sorting, insertion,
manipulation, deletion etc. can be performed by Java Collections.

What is Collection in java?


It is a root interface of the collection framework.
A collection is used to represent a group of objects as single unit.
What is framework in java

● provides readymade architecture.


● represents set of classes and interface.

What is the Collection framework

The collection framework represents a unified architecture for storing and manipulating
group of objects. It has:

1. Interfaces and its implementations i.e. classes

What is the collections?

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

The Following classes are implementes Queue interface


1.priorityqueue 2.arrayDeque 3.Linkedlis.
Map Interface
1. Set is the child interface of the collection interface.
2. Key and values are paired.
3. Key cannot be duplicated.
4. Values can be duplicates.
eg.Emp id and Emp Name

The Following classes are implementes Map interface


1.HashMap 2.LinkedHashMap
Methods of Collection interface:
are many methods declared in the Collection interface. They are as follows:

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.

List : Interface Methods:


all methods are abstract methods

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

1. Create Homogenous arraylist-String-Create Collection


2. Print the arraylist
3. Create Another array list-Create Collection-Empty
4. add collection - using addAll-collection
5. Print
6. RemoveAll-collection
7. print
8. Print-Using for loop /for each/iterator
9. take size of array
10. print using get command
11. hasNext - For iterator
12. next - Reter the elements.
13. Using Collections class:Sort arraly list
14. Reverse order
15. Shuffle arraylist
16. Print
17. create string array
18. create arrayList and create array in to array list(Arrays.asList).
19. Print

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

How LinkedList works?


Elements stored in container - In random address location
Node - null--P x N p y n--Null

Linked List methods: Generic Methods


Insert:
add(obj):append the specified objectss/element to the end of the list
add(index,obj):insert the specified obj/element at the specified index position in the list
addAll(collection):appends all the element in the specified collections to the end of the list

Remove:
1.remove(obj)
2.remove(index)
3.removeAll(Collection)

Retrieve/Access:
1.get(index)

Replace:
1.set(index,obj)

Clare()-remove all the elements from the list

Stack :based on LIFO-LIST IN FIRST OUT


queue : based on FIFO -FIST IN FIRST OUT

Additional methods in linked list for stack and queue operations.

1.addFirst()-adds an item to the beginning of the list


2.addLast()-adds an item to the end of the list
3.removeFirst()-remove an item from the beginning of the list.
4.removeLast()-remove an item from the end of the list
5.getFirst()-get the item at the beginning of the list
6.getLast()-get the item at the end of the list
7.pop()-pops and element from the stack represented by the list
8.push()-pushes the element to the stack represented by the list
9.peek()-retrieves the first element of the list.
10.peekFirst()-Retrieves ,but does not remove ,the first element of this list
11.peekLast()-Retrieves does not remove ,the last element of this is llist ,or return null if
this lis tis empty.

Reading methods from linked list


1/For loop
2.For..each loop
3.Iterator method

Note :Apply above collections class - Methods

Pritical-1 Linked list:


1. Declare LinkedList -Homogenous
2. add elements
3. print
4. add element in first index
5. print
6. add collection2 in to collection1 -Using addAll methos
7. print
8. remove element by string or index
9. print
10. Remove collection -2:removeAll()
11. get and print element of position of 1st :using get method
12. Replace 1st position by "":Using set method
13. print
14. check element is exist or not in linked list: using contains method
15. print

Piratical -2:stack and quaue methods


1. create linked list for string
2. add elements
3. print
4. add element using -addFirst
5. print
6. add element using -addLast
7. print
8. removeFirst
9. print
10. remove last
11. print
12. getFirst//print
13. getLast//print
14. push operations
15. obj.push(obj)
16. print
17. obj.pop();
18. print
19. peek

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

Insert Elements to HashSet.


add()-Insert the specified elements to the set
addAll()-inserts all the elements of the specified collection to the set

Remove Elements:
remove()-removes the specified element from the set
removeAll()-removes all the elements from the set

Other methods :

contains(object)-Searches the HashSet for the specified element sand


returns a Boolean result.
containsAll(collection)-
isEmpty - check if the HashSet is empty
size()-Retunes the size of HashSet.
Clare()-remove all the elements from HashSet.

Read Elements of HashSet.:


1.For
2.For each
3.etrator

Note :Sorting operation is not possible in HashSet..

You can apply sorting operations after converting HashSet to ArrayList.

In Java, HashSet is commonly used if we have to access elements randomly or search


operations are required.
It is because elements in a hash table are accessed using hash code.
Pratical-1 HashSet-Class
1.Declare HashSet. - For heterogeneous data
2.Declare HashSet. - For Homogenours data string
3.Add Elements
4.print
5.addAll - Method
6.Print
7.remove-string
8.print
9.removeAll - Collection
10.print
11.Search-Containts using if else statement.
12.containsAll
13.isEmpty - Pirnt
14.size-print
15.clare

HashSet - For set Operations

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

Note : Please fallow hashSet practical examples.

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

How to use Queue Interface :


1.Linked List (c)
2.Priority queue (c)

Difference:
LL -Insercation order maintain PQ- Auto sort.
LL-Duplicates allowed PQ -Duplicates allowed.
LL-Heterogenous data PQ-Homogenous data stored

Methods: in Queue Interface


Add Element :
Add()-Inserts the specified element into the queue. If the task is successful, add() returns
true , if not it throws an exception.
Offer()-inserts the specified element into the queue. I the task is successful, offer() return
true , if not it returns false.

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.

Piratical: Priority queue:


1.add collection.
2.add -print
3.add Using offer method
4.element() -print check after Clare
5.pick()-print-Return null if queue is empty
6.remove()-print -
7.print
8.poll-print
9.print
10.print using for and for each

Note :Practical -(LinkedList) 2 same as above.


and heterogenous data.

Map Interface:
-->Hash Map,Hash Table

Java Map Interface:


1.Collection of key and value pair or collection of entry
2.Stored the data key and value.
3.No duplicates allowed in key.
4.Deplicaes allowed in value.

Classes that implements map interface:


1.HashMap
2.HashTable
3.LinkedHash Map

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.

When to use Hash Map:


We more number of search operations are required.

Create hash map:


//hashMap creation with 8 capicity and 0.6 load factor.
HashMap<K,V> nmbers = new HashMap();

K represents the key type and v represents the keys of values.

Example :
HashMap<String,Integer> number = new HashMap<>();

Basic Operations in Hash Map:


Add Element:
put()-methods - add single element
putAll()-Inserts all the key/value mappings from the specified map to the 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

19.Print all the entry using entrySet() method.

Print values using


1.For loop
2.For each

Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.

Methods of Iterator interface


There are only three methods in the Iterator interface. They are:

No. Method Description


1 public It returns true if the iterator has
boolean more elements otherwise it returns
hasNext() false.
2 public It returns the element and moves
Object the cursor pointer to the next
next() element.
3 public It removes the last elements
void returned by the iterator. It is less
remove() used.
List vs ArrayList in Java

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.

List interface creates a collection of ArrayList creates an array of objects where


elements that are stored in a sequence the array can grow dynamically.
and they are identified and accessed
using the index.

You might also like