Java Notes
Java Notes
Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure programming
language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James Gosling is
known as the father of Java. Before Java, its name was Oak. Since Oak was already a registered company, so James
Gosling and his team changed the name from Oak to Java.
Features of Java:
The primary objective of Java programming language creation was to make it portable, simple and secure
programming language. Apart from this, there are also some excellent features which play an important role in the
popularity of this language. The features of Java are also known as Java buzzwords.
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple:
Java is easy to learn and its syntax is quite simple, clean and easy to understand. The confusing and ambiguous
concepts of C++ are either left out in Java or they have been re-implemented in a cleaner way.
Ex: Pointers and Operator Overloading are not there in java but were an important part of C++.
Object Oriented:
In java, everything is an object which has some data and behavior. Java can be easily extended as it is based on
Object Model. Following are some basic concepts of OOP's.
i. Object
ii. Class
iii. Inheritance
iv. Polymorphism
v. Abstraction
vi. Encapsulation
Robust:
The English mining of Robust is strong. Java is robust because:
● It uses strong memory management.
● There is a lack of pointers that avoids security problems.
● Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects
which are not being used by a Java application anymore.
● There are exception handling and the type checking mechanism in Java. All these points make Java robust.
Portable:
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any
implementation.
High-performance:
Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native
code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it
is slower than compiled languages, e.g., C, C++, etc.
Multi-threaded:
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks
at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for
each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc.
Dynamic:
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It
also supports functions from its native languages, i.e., C and C++.
Secure:
When it comes to security, Java is always the first choice. With java secure features it enables us to develop virus
free, temper free system. Java program always runs in Java runtime environment with almost null interaction with
system OS, hence it is more secure.
Platform Independent:
Unlike other programming languages such as C, C++ etc. which are compiled into platform specific machines. Java
is guaranteed to be write-once, run-anywhere language.
On compilation Java program is compiled into bytecode. This bytecode is platform independent and can be run on
any machine, plus this bytecode format also provides security. Any machine with Java Runtime Environment can
run Java Programs.
JVM:
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically exist.
It is a specification that provides a runtime environment in which Java bytecode can be executed. It can also run those
programs which are written in other languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform dependent because
the configuration of each OS is different from each other. However, Java is platform independent. There are three
notions of the JVM: specification, implementation, and instance.
JRE:
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime Environment is
a set of software tools which are used for developing Java applications. It is used to provide the runtime environment.
It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro Systems.
JDK:
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development
environment which is used to develop Java applications and applets. It physically exists. It contains JRE +
development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:
● Standard Edition Java Platform
● Enterprise Edition Java Platform
● Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an interpreter/loader (java),
a compiler (javas), an archiver (jar), a documentation generator (Javadoc), etc. to complete the development of a Java
Application.
Java Variables:
A variable is a container which holds the value while the Java program is executed. A variable is assigned with a data
type.
Variable is a name of memory location. There are three types of variables in java: local, instance and static.
Variable:
A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory location. It
is a combination of "vary + able" which means its value can be changed.
Types of Variables:
There are three types of variables in Java:
● local variable
● instance variable
● static variable
1) Local Variable:
A variable declared inside the body of the method is called local variable. You can use this variable only within that
method and the other methods in the class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
Ex:
public class VariableExample {
// instance variable
public String myVar="instance variable";
Ex:
public class InstanceVarExample {
String myInstanceVar="instance variable";
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link] = "Changed Text";
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}
3) Static variable:
A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the
static variable and share it among all the instances of the class. Memory allocation for static variables happens only
once when the class is loaded in the memory.
Ex:
public class StaticVarExample {
public static String myClassVar="class or static variable";
byte 0 1 byte
short 0 2 bytes
int 0 4 bytes
long 0L 8 bytes
Boolean:
The Boolean data type is used to store only two possible values: true and false. This data type is used for simple flags
that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Ex: Boolean one = false
Byte:
The byte data type is an 8-bit signed two’s complement integer. The byte data type is useful for saving memory in
large arrays.
Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its default
value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most required. It saves space
because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.
Ex: byte a = 45, byte b = -50
1. Arithmetic Operators:
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as basic
mathematical operations.
Ex:
2. Assignment Operators:
Java assignment operator is one of the most common operators. It is used to assign the value on its right to the
operand on its left.
Ex:
3. Unary Operators:
As the name suggests, The Unary operators in Java involve single operand. Java supports following unary operators:
Ex:
public class JavaExample {
public static void main(String args[]){
int num1=100;
int num2=200;
//increment
num1++;
//decrement
num2--;
}
}
4. Logical Operators:
Logical Operators are used to evaluate the outcome of conditions. There are three logical operators: AND (&&), OR
(||) and NOT (!). The AND and OR operators are used when multiple conditions are combined and we need to
evaluate the outcome as a whole.
Ex:
public class LogicalOperatorDemo {
public static void main(String args[]) {
boolean b1 = true;
boolean b2 = false;
Ex:
public class JavaExample {
public static void main(String args[]) {
int num1 = 10;
int num2 = 50;
if( num1 != num2 ){
[Link]("num1 and num2 are not equal");
}
else{
[Link]("num1 and num2 are equal");
}
result = ~num1;
[Link]("~num1: "+result);
//Left shift
[Link]("num<<2: "+(num<<2));
//Right shift
[Link]("num>>2: "+(num>>2));
}
}
additive +-
equality == !=
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
1. Simple if statement:
It evaluates a Boolean expression and enables the program to enter a block of code if the expression evaluates to true.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
EX:
public class Student {
public static void main (String [] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
[Link]("x + y is greater than 20");
}} }
[Link]-else statement:
The statements inside “if” would execute if the condition is true, and the statements inside “else” would execute if
the condition is false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else {
statement 2; //executes when condition is false
}
EX:
public class IfElseExample {
public static void main (String args []) {
int num=120;
if (num < 50) {
[Link]("num is less than 50");
} else {
[Link]("num is greater than or equal 50");
} }}
[Link]-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we can say
that it is the chain of if-else statements that create a decision tree where the program may enter in the block of code
where the condition is true. We can also define an else statement at the end of the chain.
Syntax:
if (condition 1) {
statement 1; //executes when condition 1 is true
}
else if (condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Ex:
public class IfElseIfExample {
public static void main (String args []) {
int num=1234;
if (num <100 && num>=1) {
[Link]("It’s a two-digit number");
} else if (num <1000 && num>=100) {
[Link]("It’s a three-digit number");
} else if (num <10000 && num>=1000) {
[Link]("It’s a four-digit number");
} else if (num <100000 && num>=10000) {
[Link]("It’s a five-digit number");
} else {
[Link]("number is not between 1 & 99999");
}}}
4. Nested if-statement:
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if statement.
Syntax:
if (condition 1) {
statement 1; //executes when condition 1 is true
if (condition 2) {
statement 2; //executes when condition 2 is true
} else {
statement 2; //executes when condition 2 is false
}}
Ex:
public class NestedIfExample {
public static void main (String args []) {
int num=70;
if (num < 100) {
[Link]("number is less than 100");
if (num > 50) {
[Link]("number is greater than 50");
}}}}
[Link] Statement:
Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks of code called
cases and a single case is executed based on the variable which is being switched. The switch statement is easier to
use instead of if-else-if statements. It also enhances the readability of the program.
Syntax:
switch (expression) {
case value1:
statement1;
break;
.
.
case valueN:
statementN;
break;
default:
default statement;
}
EX:
public class Switchclass {
public static void main (String [] args)
{
int day = 5;
String dayString;
switch (day) {
case 1:
dayString = "Monday";
break;
case 2:
dayString = "Tuesday";
break;
case 3:
dayString = "Wednesday";
break;
case 4:
dayString = "Thursday";
break;
case 5:
dayString = "Friday";
break;
case 6:
dayString = "Saturday";
break;
case 7:
dayString = "Sunday";
break;
// Default case
default:
dayString = "Invalid day";
} [Link](dayString);
}}
[Link] statements:
Loop statements are used to execute the set of instructions in a repeated order. The execution of the set of instructions
depends upon a particular condition.
we have three types of loops:
1. for loop
2. while loop
3. do-while loop
[Link] loop:
A for loop is used to repeat a specific block of code a known number of times. The for loop is mainly used when you
know exactly how many times the loop is about to be executed i.e., with what values will it start and with what values
it will end and what will be its test condition.
Syntax:
If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely
whenever outer loop executes.
EX:
public class NestedForExample {
public static void main (String [] args) {
for (int i=1; i<=3; i++) {
for (int j=1; j<=3; j++) {
[Link](i+" "+j);
}}}}
The for-each loop is used to traverse array or collection in Java. It is easier to use than simple for loop because we
don't need to increment value and use subscript notation.
It works on the basis of elements and not the index. It returns element one by one in the defined variable.
EX:
public class ForEachExample {
public static void main (String [] args) {
int arr [] = {12,23,44,56,78};
for (int i: arr) {
[Link](i);
} } }
[Link] loop:
The while loop is also used to iterate over the number of statements multiple times. However, if we don't know the
number of iterations in advance, it is recommended to use a while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the condition is
true, then the loop body will be executed; otherwise, the statements after the loop will be executed.
Syntax:
while(condition) {
//looping statements
}
EX:
class WhileLoopExample {
public static void main (String args []) {
int i=10;
while(i>1) {
[Link](i);
i--;
}}}
[Link]-while loop:
The do-while loop checks the condition at the end of the loop after executing the loop statements. When the number
of iterations is not known and we have to execute the loop at least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance.
Syntax:
do
{
//statements
} while (condition);
EX:
class DoWhileLoopExample {
public static void main (String args []) {
int i=10;
do {
[Link](i);
i--;
} while(i>1);
}}
[Link] statements:
The Java break statement is used to break loop or switch statement. It breaks the current flow of the program at
specified condition. In case of inner loop, it breaks only inner loop.
We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.
Syntax:
break;
EX:
public class BreakExample1 {
public static void main (String args []) {
int num =0;
while(num<=100)
{[Link]("Value of variable is: "+num);
if (num==2)
{break;
}num++;
} [Link]("Out of while-loop");
}}
2. Java Continue Statement:
The Java continue statement is used to continue the loop. It continues the current flow of the program and skips the
remaining code at the specified condition. In case of an inner loop, it continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.
Syntax:continue;
EX:
public class ContinueExample {
public static void main (String args []){
for (int j=0; j<=6; j++)
{ if (j==4)
{continue;
}
[Link](j+" ");
}}}
Java Comments:
Comments are used to stop the execution of the particular statements and also are used to provide information
explanation about variables, methods, class are any statement.
Types of Java Comments:
Syntax:
//This is single line comment
EX:
class Scomment
{
public static void main (String args [])
{
// Single line comment here
[Link]("Single line comment above");
}}
The multi-line comment is used to comment multiple lines of code. It can be used to explain a complex code snippet
or to comment multiple lines of code at a time (as it will be difficult to use single-line comments there).
Multi-line comments are placed between /* and */. Any text between /* and */ is not executed by Java.
Syntax:
/*
This
is
multi line
comment
*/
EX:
class Scomment
{
public static void main (String args [])
{
[Link]("Multi line comments below");
/*Comment line 1
Comment line 2
Comment line 3*/
}}
3) Java Documentation Comment:
Documentation comments are usually used to write large programs for a project or software application as it helps to
create documentation API. These APIs are needed for reference, i.e., which classes, methods, arguments, etc., are used
in the code.
To create documentation API, we need to use the Javadoc tool. The documentation comments are placed between
/** and */.
Syntax:
/**
*
*We can use various tags to depict the parameter
*Or heading or author name
*We can also use HTML tags
*
*/
EX:
/**
*This method is used to add two numbers
*@author I hub
*@param x, y
*@return integer value
*/
Java Arrays:
Normally, an array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, the elements of an array are stored
in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set
of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index
and so on.
Advantages
✔ Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
✔ Random access: We can get any data located at an index position.
Disadvantages
✔ Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To
solve this problem, collection framework is used in Java which grows automatically.
Syntax:
type var-name [];
OR
type [] var-name;
EX:
class Testarray {
public static void main (String args []) {
int a [] =new int [5] ;//declaration and instantiation
a [0] =10;//initialization
a [1] =20;
a [2] =70;
a [3] =40;
a [4] =50;
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}
Multidimensional Array:
Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other arrays.
These are also known as Jagged Arrays. A multidimensional array is created by appending one set of square
brackets ([]) per dimension.
Syntax:
data type [][] arrayrefvaribale;
or
datatype arrayrefvariable[][];
EX:
public class multiDimensional {
public static void main (String args [])
{
// declaring and initializing 2D array
int arr[][]
= {{2, 7, 9}, {3, 6, 1}, {7, 4, 2}};
// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
[Link](arr[i][j] + " ");
[Link]();
}}}
Static Non-static
A variable are method declare with a keyword A variable are method declare without any
static is a Static variable/method Static keyword is called a non-Static
variable/method
A static variable and static method can be used A Non-static method/variable can be used
directly in a static method with in the class. directly in a non-static method
A Non-static method/variable can’t be used
directly in a static method. They can be access
by creating a reference of the class.
Memory allocation for non-static
Memory allocation for static variable/method
variable/method is instance specific when ever
happens only one when the class is loaded in
and instance for the class is created the
the memory.
memory will be allocated.
Java OOPs Concepts:
Object-oriented programming System (OOPs) is a programming concept that is based on “objects”. The primary
purpose of object-oriented programming is to increase the readability, flexibility and maintainability of programs.
Popular programming languages that supports object oriented programming are: Java, C++, Python, C#, Perl,
JavaScript, Ruby, and Smalltalk etc.
● Object
● Class
● Abstraction
● Encapsulation
● Inheritance
● Polymorphism
Object:
Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard, bike, etc.
It can be physical or logical.
✔ An Object can be defined as an instance of a class.
The difference between state and behavior. The state of an object is a data item that can be represented in value
such as price of house, color, area; consider them as variables in programming. The behavior is like a method of the
class such as opendoor, closedoor, it is a group of actions that together can perform a task.
class House {
String address;
String color;
double area;
void openDoor() {
//Write code here
}
void closeDoor() {
//Write code here
}
...
...
}
Class:
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume any
space.
For example in the above given example House is considered as the CLASS.
Inheritance:
Acquiring the properties of a parent class by a child class by using keyword EXTENDS is called INHERITNCE
✔ Inheritance provides the idea of reusability of code and each sub class defines only those features that are
unique to it, rest of the features can be inherited from the parent class.
✔ The parent class is called the base class or super class. The child class that extends the base class is
called the derived class or sub class or child class.
✔ The biggest advantage of Inheritance is that the code in base class need not be rewritten in the child class.
The variables and methods of the base class can be used in the child class as well.
✔ Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and
methods of the existing class when you create a new class. You can use the same fields and methods already
defined in the previous class.
SYNTAX:
class A extends B
{
}
Ex:
class Teacher {
String designation = "Teacher";
String college = "Ihub";
void does() {
[Link]("Teaching");
}
}
public class TestingTeacher extends Teacher {
String main Subject = "Testing";
public static void main(String args[]) {
TestingTeacher obj = new TestingTeacher();
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]();
}
}
Types of inheritance in java:
● Single Inheritance
● Multilevel Inheritance
● Hierarchical Inheritance
● Multiple Inheritance
● Hybrid Inheritance
Single Inheritance:
Single inheritance refers to a child and parent class relationship where a class extends the another class.
Ex:
Multilevel Inheritance:
Multilevel inheritance refers to a child and parent class relationship where a class extends the child class. For
example class A extends class B and class B extends class C.
Ex;
Hierarchical Inheritance:
Hierarchical inheritance refers to a child and parent class relationship where more than one classes extends the same
class. For example, class B extends from class A and class C extends from class A.
EX:
Multiple Inheritance: Multiple inheritance refers to the concept of one class extending more than one classes,
which means a child class has two parent classes. Java doesn’t support multiple inheritance.
✔ Most of the new Oops languages like Small Talk, Java, C# do not support Multiple inheritance. Multiple
Inheritance is supported in C++.
Ex:
Hybrid Inheritance:
A hybrid inheritance is a combination of more than one types of inheritance. For example when class A and B
extends class C & another class D extends class A then this is a hybrid inheritance, because it is a combination of
single and hierarchical inheritance.
✔ It also provides the code reusability. The hybrid inheritance can be achieved by using the following
combinations:
● Single and Multiple Inheritance (not supported but can be achieved through interface)
● Multilevel and Hierarchical Inheritance
● Hierarchical and Single Inheritance
● Multiple and Multilevel Inheritance
Ex:
Polymorphism:
Polymorphism is a object oriented programming feature that allows us to perform a single action in different ways.
There are two types of Polymorphism
1. Run-time Polymorphism
2. Compile time Polymorphism
✔ In java we can achieve polymorphism by METHOD OVERLOADING, METHOD OVERRIDING.
For example, let’s say we have a class Animal that has a method animalSound(), here we cannot give
implementation to this method as we do not know which Animal class would extend Animal class. So, we make this
method abstract like this
Method Overloading:
If a class has multiple methods having same but different in parameters
(Or)
A method with same name or different number of parameters or type parameters with in the class is known as
Method Overloading.
Ex:
class Adder{
static int add(int a,int b) {
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1{
public static void main(String[] args) {
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}
}
Method Overriding:
If subclass (child class) has the same method as declared in the parent class is known as Method
Overriding
(or)
Method with same name and same number or type of parameters of parent class is overridden in the child
class.
Usage of Java Method Overriding:
● Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
● Method overriding is used for runtime polymorphism
Ex:
class Vehicle {
void run() {
[Link]("Vehicle is running");
}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]) {
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
[Link]();
}
}
Abstraction:
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
(Or)
Another way, it shows only essential things to the user and hides the internal details, For example, when you login to
your Amazon account online, you enter your user_id and password and press login, what happens when you press
login, how the input data sent to amazon server, how it gets verified is all abstracted away from the you.
Abstract class:
● An abstract class must be declared with an abstract keyword.
● It can have abstract and non-abstract methods.(method with the body)
● It cannot be instantiated.
● It can have constructors and static methods also.
● It can have final methods which will force the subclass not to change the body of the method.
● We can use 0 to 100% abstraction by using abstract class.
Ex:
//abstract class
abstract class Animal{
//abstract method
public abstract void animalSound();
}
public class Dog extends Animal{
Encapsulation:
Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a capsule which
is mixed of several medicines.
Ex:
● Make the instance variables private so that they cannot be accessed directly from outside the class. You can
only set and get values of these variables through the methods of the class.
● Have getter and setter methods in the class to set and get the values of the fields.
class EmployeeCount
{
private int numOfEmployees = 0;
public void setNoOfEmployees (int count)
{
numOfEmployees = count;
}
public double getNoOfEmployees ()
{
return numOfEmployees;
}
}
public class EncapsulationExample
{
public static void main(String args[])
{
EmployeeCount obj = new EmployeeCount ();
[Link](5613);
[Link]("No Of Employees: "+(int)[Link]());
}
}
Interface:
An interface in Java is a blueprint of a class. All the methods of a interface are the abstract methods by default the
variables declared and initialized in an interface are public, static and final. It has static constants and abstract methods .
● All the methods in an interface are implemented in the implemented class by using keyword implements
● We cannot instantiate an interface.
● By using interface we can achieve 100% abstraction in java.
● Multiple Inheritance is only possible through Interfaces.
Ex:
interface printable {
void print();
}
class A6 implements printable {
public void print() {
[Link]("Hello"); }
1. Private
2. Default
3. Protected
4. Public
[Link]:
A variable is a method declared as private in a class can be access with in the class only. That is, it cannot be
accessed with in the package outside the package subclass and outside the package.
EX:
class NUMBERS {
private double num = 100;
private int square (int x) {
return x*x;
}}
public class Test {
public static void main (String args []) {
NUMBERS obj = new NUMBERS ();
[Link]([Link]);
[Link](ob. Square (5));
}}
[Link]:
A variable is method without any keyword like public, private, protected is a default access modifier. It can be
accessed with in the class, with in the package only.
EX:
[Link]:
A variable is method declare as a protected can be access with in the class, with in the package outside the package
subclass only.
EX:
package j1;
public class A
{
protected void display ()
{
[Link](“Jigsaw Academy”);
}}
package j2;
import j1. *;
class B extends A
{
public static void main (String args [])
{
B obj = new B ();
obj. display ();
}}
[Link]:
A variable is a Method which is declare as a public can be access any ware in the project. That is with in the class,
with in the package, outside the package subclass only and outside package.
EX:
package s1;
public class A
{
public void display ()
{
[Link](“Jigsaw Academy”);
}}
package s2;
import s1. *;
class B
{
public static void main (String args [])
{
A obj = new A;
obj. display ();
}}
Access Modifier within class within package outside package by subclass only outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Constructors in Java:
● Constructor is a special method which has same name as class name and doesn’t have any return type.
● Constructors are used to initialize the objects
● Constructors are invoke (called) whenever there is an instance of a class is created.
● If there is no constructor declared in a class the java complier by default will create a default constructor
● There are two types of Constructors:
1. Default Constructor
2. Parameterized Constructor.
● A constructor must have no explicit return type
● A java Constructor cannot be abstract, static, final and synchronized.
● Constructors can be overloaded.
Example of default constructor:
String is basically an object that represents sequence of char values. An array of characters works same as Java string.
For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
Is same as:
String s="javatpoint";
✔ 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.
CharSequence Interface:
The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance
is created. For mutable strings, you can use StringBuffer and StringBuilder classes.
StringBuffer:
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class in Java is the
same as String class except it is mutable i.e. it can be changed.
✔ Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and
will result in an order.
StringBuilder:
Java StringBuilder class is used to create mutable (modifiable) String. The Java StringBuilder class is same as
StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.
Methods Description
replace() replaces the specified old character with the specified new character
String Example:
class Main {
public static void main(String[] args) {
// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";
// print strings
[Link](first); // print Java
[Link](second); // print Python
[Link](third); // print JavaScript
}
}
Collections in Java
The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects. A
Collection represents a single unit of objects, i.e., a group.
Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion,
manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue,
Deque) and classes (Array List, Vector, Linked List, Priority Queue, HashSet, Linked HashSet, Tree Set).
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure in which we can store
the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes Array List, LinkedList, Vector, and Stack.
Array List
The Array List class implements the List interface. It uses a dynamic array to store the duplicate element of different
data types. The Array List class maintains the insertion order and is non-synchronized. The elements stored in the
Array List class can be randomly accessed. Consider the following example.
Ex:
import [Link].*;
class JavaExample{
public static void main(String args[]){
//creating ArrayList of string type
ArrayList<String> arrList=new ArrayList<>();
LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to store the elements. It can store
the duplicate elements. It maintains the insertion order and is not synchronized. In LinkedList, the manipulation is fast
because no shifting is required.
Ex:
import [Link].*;
public class JavaExample{
public static void main(String args[]){
LinkedList<String> linkList=new LinkedList<>();
[Link]("Apple"); //["Apple"]
[Link]("Orange"); //["Apple", "Orange"]
Tree Set:
Tree Set stores elements in a red-black tree. It is substantially slower than HashSet. Tree Set class implements Sorted
Set interface, which allows Tree Set to order its elements based on their values, which means Tree Set elements are
sorted in ascending order.
Ex:
import [Link].*;
public class JavaExample{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<>();
[Link]("Paul");
[Link]("Ram");
[Link]("Aaron");
[Link]("Leo");
[Link]("Becky");
Iterator<String> it=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table for storage. Hashing is used
to store the elements in the HashSet. It contains unique items.
Ex:
import [Link].*;
public class JavaExample{
public static void main(String args[]){
HashSet<String> set=new HashSet<>();
[Link]("Paul");
[Link]("Ram");
[Link]("Aaron");
[Link]("Leo");
[Link]("Becky");
Iterator<String> it=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
LinkedHashSet:
LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the HashSet class and
implements Set interface. Like HashSet, it also contains unique elements. It maintains the insertion order and permits
null elements.
Ex:
import [Link].*;
public class JavaExample{
public static void main(String args[]){
LinkedHashSet<String> set=new LinkedHashSet<>();
[Link]("Paul");
[Link]("Ram");
[Link]("Aaron");
[Link]("Leo");
[Link]("Becky");
Iterator<String> it=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Map:
A map contains values on the basis of key, i.e., key and value pair. Each key and value pair is known as an entry. A
Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis of a key.
HashMap:
Java HashMap class implements the Map interface which allows us to store key and value pair, where keys should
be unique. If you try to insert the duplicate key, it will replace the element of the corresponding key. It is easy to
perform operations using the key index like updating, deletion, etc. HashMap class is found in the [Link] package.
HashMap in Java is like the legacy Hash table class, but it is not synchronized. It allows us to store the null elements
as well, but there should be only one null key. Since Java 5, it is denoted as HashMap<K, V>, where K stands for key
and V for value. It inherits the Abstract Map class and implements the Map interface.
Ex:
import [Link].*;
public class JavaExample{
public static void main(String args[]){
HashMap<Integer, String> hmap = new HashMap<>();
HashMap class:
Java Linked HashMap class is Hash table and Linked list implementation of the Map interface, with predictable
iteration order. It inherits HashMap class and implements the Map interface.
● Java Linked HashMap contains values based on the key.
● Java Linked HashMap contains unique elements.
● Java Linked HashMap may have one null key and multiple null values.
● Java Linked HashMap is non synchronized.
● Java Linked HashMap maintains insertion order.
Ex:
import [Link].*;
public class JavaExample{
public static void main(String args[]){
LinkedHashMap<Integer, String> hmap = new LinkedHashMap<>();
Exception:
Exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
Types of Java Exceptions:
There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception.
However, according to Oracle, there are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception:
The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked
exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-
time.
2) Unchecked Exception:
The classes that inherit the Runtime Exception are known as unchecked exceptions. For example, Arithmetic
Exception, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3) Error:
Error is irrecoverable. Some examples of errors are OutOfMemoryError, VirtualMachineError, Assertion Error etc.
Java provides five keywords that are used to handle the exception. The following table describes each.
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code. It means we can't use try
block alone. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use
catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is
handled or not.
Example:
public class JavaExceptionExample{
public static void main (String args []) {
try {
int data=100/0;
} catch (Arithmetic Exception e){[Link](e);
}
[Link]("rest of the code...");
} }