Overview of Programming Languages and Java
Overview of Programming Languages and Java
Type of program:
1. Low Level: low level programing language directly interact with machine hardware. Machine
language, assembly language (add, store, load).
2. High Level: high level language writes in human language but convert into machine language.
Java, C++, COBAL.
Complier: A compiler is a special program that translates a programming language's source code into
machine code, bytecode, or another programming language. The source code is typically written in a
high-level, human-readable language such as Java or C++. A programmer writes the source code in a
code editor or an integrated development environment (IDE) that includes an editor, saving the source
code to one or more text files. Compilers that translate source code to machine code target specific
operating systems and computer architectures.
Interpreter: Compilers are sometimes confused with programs called interpreters. Although the two are
similar, they differ in important ways. Interpreters do not generate IR code or save generated machine
code. They process the code one statement at a time at runtime, without pre-converting the code or
preparing it in advance for a particular platform. Interpreters are used for code written in scripting
languages such as Perl, PHP, Ruby, or Python.
Platform:
1. Platform is the place or a runtime environment on which our program is going to be execute.
2. Any hardware or software environment in which a program runs, is known as a platform.
3. Since Java has a runtime environment (JRE) and API, it is called a platform.
Platform Type:
1. Software platform
2. Hardware platform
3. Combination of both
Topics:
1. Source code: The code writes in human language and save is called source code.
2. Object code: After compiler the code make that called object code.
3. Explicit: which in can be explained called explicit
4. Implicit: which cannot be explained but can be understand by logic is called implicit. If x>y and
y>z then x>z we know by logic. Is called implicit
5. 32bit: 32-bit, in computer systems, refers to the number of bits that can be transmitted or
processed in parallel. In computer architecture, 32-bit integers, memory addresses, or
other data units are those that are 32 bits (4 octets) wide.
6. 64bit: In computer architecture, 64-bit integers, memory addresses, or other data units are
those that are 64 bits wide.
But now in windows, compiler convert source code in exc file. In exc file add necessary O.S file at
compiler time. So, there is no need for create object file. This exc file only run-in windows.
Java Architecture
Java Architecture is a collection of components, i.e., JVM, JRE, and JDK. It integrates the process of
interpretation and compilation. It defines all the processes involved in creating a Java program. Java
Architecture explains every step of how a program is compiled and executed. Java Architecture can be
explained by using the following steps: There is a process of compilation and interpretation in Java. Java
compiler converts the Java code into byte
code. After that, the JVM converts the byte
code into machine code. The machine code is
executed by the machine.
Now let's dive deep to get more knowledge about Java Architecture. As we know that the Java
architecture is a collection of components, so we will discuss every component into detail.
Components of Java Architecture: The Java architecture includes the three main components:
1. Java Virtual Machine (JVM)
2. Java Runtime Environment (JRE)
3. Java Development Kit (JDK)
A. Java Virtual Machine (JVM): The main feature of Java is Write Once Run Anywhere (WORA). The
feature states that we can write our code once and use it anywhere or on any operating system. Our
Java program can run any of the platforms only because of the Java Virtual Machine. It is a Java
platform component that gives us an environment to execute java programs. JVM's main task is to
convert byte code into machine code. JVM, first, loads the code into memory and verifies it. After
that, it executes the code and provides a runtime environment. Java Virtual Machine (JVM) has its
own architecture, which is given below:
JVM Architecture: JVM is an abstract machine that provides the environment in which Java
bytecode is executed. The falling figure represents the architecture of the JVM.
1. Class Loader: ClassLoader is a subsystem used to load class files. ClassLoader first loads the Java code
whenever we run it
2. Class Method Area: In the memory, there is an area where the class data is stored during the code's
execution. Class method area holds the information of static variables, static methods, static blocks, and
instance methods.
3. Heap: The heap area is a part of the JVM memory and is created when the JVM starts up. Its size cannot
be static because it increases or decrease during the application runs.
4. Stack: It is also referred to as thread stack. It is created for a single execution thread. The thread uses this
area to store the elements like the partial result, local variable, data used for calling method and
5. Returns etc.
6. Native Stack: It contains the information of all the native methods used in our application.
7. Execution Engine: It is the central part of the JVM. Its main task is to execute the byte code and execute
the Java classes. The execution engine has three main components used for executing Java classes.
8. Interpreter: It converts the byte code into native code and executes. It sequentially executes the code.
The interpreter interprets continuously and even the same method multiple times. This reduces the
performance of the system, and to solve this, the JIT compiler is introduced.
9. JIT Compiler: JIT compiler is introduced to remove the drawback of the interpreter. It increases the speed
of execution and improves performance.
10. Garbage Collector: The garbage collector is used to manage the memory, and it is a program written in
Java. It works in two phases, i.e., Mark and Sweep. Mark is an area where the garbage collector identifies
the used and unused chunks of memory. The Sweep removes the identified object from the Mark
11. Java Native Interface: Java Native Interface works as a mediator between Java method calls and native
libraries.
B. Java Runtime Environment (JRE): It provides an environment in which Java programs are executed. JRE
takes our Java code, integrates it with the required libraries, and then starts the JVM to execute it. JRE (Java
Runtime Environment) is a software package that provides Java class libraries, Java Virtual Machine (JVM), and
other components that are required to run Java applications is the superset of JVM. If you need to run Java
programs, but not develop them, JRE is what you need. You can download JRE from Java SE Runtime
Environment 8 Down.
C. Java Development Kit: It is a software development environment used in the development of Java
applications and applets. Java Development Kit holds JRE, a compiler, an interpreter or loader, and several
development tools in it. JDK (Java Development Kit) is a software development kit required to develop
applications in Java. When you download JDK, JRE is also downloaded with [Link] addition to JRE, JDK also
contains a number of development tools (compilers, JavaDoc, Java Debugger, etc.)
Class loading:
The Java ClassLoader is a part of the Java Runtime Environment that dynamically loads Java classes into
the Java Virtual Machine. The Java run time system does not need to know about files and file systems
because of classloaders. Java classes aren’t loaded into memory all at once, but when required by an
application. At this point, the Java ClassLoader is called by the JRE and these ClassLoaders load classes
into memory dynamically.
Not all classes are loaded by a single ClassLoader. Depending on the type of class and the path of class,
the ClassLoader that loads that particular class is decided. To know the ClassLoader that loads a class
the getClassLoader() method is used. All classes are loaded based on their names and if any of these
classes are not found then it returns a NoClassDefFoundError or ClassNotFoundException. A Java
Classloader is of three types:
Note: The ClassLoader Delegation Hierarchy Model always functions in the order Application
ClassLoader->Extension ClassLoader->Bootstrap ClassLoader. The Bootstrap ClassLoader is always
given the higher priority, next is Extension ClassLoader and then Application ClassLoader. Types of
ClassLoaders in Java
Not all classes are loaded by a single ClassLoader. Depending on the type of class and the path of class,
the ClassLoader that loads that particular class is decided. To know the ClassLoader that loads a class the
getClassLoader() method is used. All classes are loaded based on their names and if any of these classes
are not found then it returns a NoClassDefFoundError or ClassNotFoundException. A Java Classloader is
of three types:
Note: The ClassLoader Delegation Hierarchy Model always functions in the order Application
ClassLoader->Extension ClassLoader->Bootstrap ClassLoader. The Bootstrap ClassLoader is always given
the higher priority, next is Extension ClassLoader and then Application ClassLoader.
Principles of functionality are the set of rules or features on which a Java ClassLoader works. There are
three principles of functionality, they are:
1. Delegation Model: The Java Virtual Machine and the Java ClassLoader use an algorithm called the
Delegation Hierarchy Algorithm to Load the classes into the Java file. The ClassLoader works based
on a set of operations given by the delegation model. They are:
Whenever JVM comes across a class, it checks whether that class is already loaded or not.
If the Class is already loaded in the method area then the JVM proceeds with execution.
If the class is not present in the method area then the JVM asks the Java ClassLoader Sub-
System to load that particular class, then ClassLoader sub-system hands over the control to
Application ClassLoader.
Application ClassLoader then delegates the request to Extension ClassLoader and the Extension
ClassLoader in turn delegates the request to Bootstrap ClassLoader.
Bootstrap ClassLoader will search in the Bootstrap classpath(JDK/JRE/LIB). If the class is available
then it is loaded, if not the request is delegated to Extension ClassLoader.
Extension ClassLoader searches for the class in the Extension Classpath(JDK/JRE/LIB/EXT). If the
class is available then it is loaded, if not the request is delegated to the Application ClassLoader.
Application ClassLoader searches for the class in the Application Classpath. If the class is
available then it is loaded, if not then a ClassNotFoundException exception is generated.
2. Visibility Principle: The Visibility Principle states that a class loaded by a parent ClassLoader is visible
to the child ClassLoaders but a class loaded by a child ClassLoader is not visible to the parent
ClassLoaders. Suppose a class [Link] has been loaded by the Extension ClassLoader, then that
class is only visible to the Extension ClassLoader and Application ClassLoader but not to the
Bootstrap ClassLoader. If that class is again tried to load using Bootstrap ClassLoader it gives an
exception [Link].
3. Uniqueness Property: The Uniqueness Property ensures that the classes are unique and there is no
repetition of classes. This also ensures that the classes loaded by parent classloaders are not loaded
by the child classloaders. If the parent class loader isn’t able to find the class, only then the current
instance would attempt to do so itself.
VARIABLES IN JAVA
1. A variable is a container which holds the value while the Java program is executed.
2. A variable is assigned with a data type.
3. Variable is a name of memory location
DATA TYPES
Data types specify the different sizes and values that can be stored in the variable. There are two types
of data types in Java:
1) Primitive data types:
2) Non-primitive data types
Literals in Java: Any constant value which can be assigned to the variable is called literal/constant.
int x = 100;
1. Integral literals:
2. Floating-Point literal: this can be expressed using only decimal fractions, exponential notation.
3. Char literals: this literal have the type char and are an unsigned integer primitive type.
4. String literals: A sequence of characters within double quotes is referred to as string literals.
5. Boolean literals: Boolean literals allow only two values and thus are divided into two literals:
1. True: it represents a real Boolean value
2. False: it represents a false Boolean value
6. Null Literals: Null literal is a particular literal in Java representing a null value
TYPE CONVERTION: It is the process of converting one type of data into another type.
A. Widening / Type Promotion (implicit): Converting a lower datatype to a higher datatype
is known as widening. In this case the casting/conversion is done automatically therefore, it
is known as implicit type casting. In this case both datatypes should be compatible with each
other.
FUNDAMENTAL
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
Operator overload:
Some operator uses in various purpose. As like + operator use in integer as add , but in string it uses as
concatenation.
1. abstract: Java abstract keyword is used to declare an abstract class. An abstract class can provide
the implementation of the interface. It can have abstract and non-abstract methods.
2. boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold True and
False values only.
3. break: Java break keyword is used to break the loop or switch statement. It breaks the current flow
of the program at specified conditions.
4. byte: Java byte keyword is used to declare a variable that can hold 8-bit data values.
5. case: Java case keyword is used with the switch statements to mark blocks of text.
6. catch: Java catch keyword is used to catch the exceptions generated by try statements. It must be
used after the try block only.
7. char: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode
characters
8. class: Java class keyword is used to declare a class.
9. continue: Java continue keyword is used to continue the loop. It continues the current flow of the
program and skips the remaining code at the specified condition.
10. default: Java default keyword is used to specify the default block of code in a switch statement.
11. do: Java do keyword is used in the control statement to declare a loop. It can iterate a part of the
program several times.
12. double: Java double keyword is used to declare a variable that can hold 64-bit floating-point
number.
13. else: Java else keyword is used to indicate the alternative branches in an if statement.
14. enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are always
private or default.
15. extends: Java extends keyword is used to indicate that a class is derived from another class or
interface.
16. final: Java final keyword is used to indicate that a variable holds a constant value. It is used with a
variable. It is used to restrict the user from updating the value of the variable.
17. finally: Java finally keyword indicates a block of code in a try-catch structure. This block is always
executed whether an exception is handled or not.
18. float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.
19. for: Java for keyword is used to start a for loop. It is used to execute a set of instructions/functions
repeatedly when some condition becomes true. If the number of iteration is fixed, it is
recommended to use for loop.
20. if: Java if keyword tests the condition. It executes the if block if the condition is true.
21. implements: Java implements keyword is used to implement an interface.
22. import: Java import keyword makes classes and interfaces available and accessible to the current
source code.
23. instanceof: Java instanceof keyword is used to test whether the object is an instance of the specified
class or implements an interface.
24. int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
25. interface: Java interface keyword is used to declare an interface. It can have only abstract methods.
26. long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
27. native: Java native keyword is used to specify that a method is implemented in native code using JNI
(Java Native Interface).
28. new: Java new keyword is used to create new objects.
29. null: Java null keyword is used to indicate that a reference does not refer to anything. It removes the
garbage value.
30. package: Java package keyword is used to declare a Java package that includes the classes.
31. private: Java private keyword is an access modifier. It is used to indicate that a method or variable
may be accessed only in the class in which it is declared.
32. protected: Java protected keyword is an access modifier. It can be accessible within the package and
outside the package but through inheritance only. It can't be applied with the class.
33. public: Java public keyword is an access modifier. It is used to indicate that an item is accessible
anywhere. It has the widest scope among all other modifiers.
34. return: Java return keyword is used to return from a method when its execution is complete.
35. short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
36. static: Java static keyword is used to indicate that a variable or method is a class method. The static
keyword in Java is mainly used for memory management.
37. strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
38. super: Java super keyword is a reference variable that is used to refer to parent class objects. It can
be used to invoke the immediate parent class method.
39. switch: The Java switch keyword contains a switch statement that executes code based on test
value. The switch statement tests the equality of a variable against multiple values.
40. synchronized: Java synchronized keyword is used to specify the critical sections or methods in
multithreaded code.
41. this: Java this keyword can be used to refer the current object in a method or constructor.
42. throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword is
mainly used to throw custom exceptions. It is followed by an instance.
43. throws: The Java throws keyword is used to declare an exception. Checked exceptions can be
propagated with throws.
44. transient: Java transient keyword is used in serialization. If you define any data member as
transient, it will not be serialized.
45. try: Java try keyword is used to start a block of code that will be tested for exceptions. The try block
must be followed by either catch or finally block.
46. void: Java void keyword is used to specify that a method does not have a return value.
47. volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
48. while: Java while keyword is used to start a while loop. This loop iterates a part of the program
several times. If the number of iterations is not fixed, it is recommended to use the while loop.
Expression statements:
We can convert an expression into a statement by terminating the expression with a “;”.
A. If Statement: It is the most basic statement among all control flow statements in Java. It
evaluates a Boolean expression and enables the program to enter a block of code if the
expression evaluates to true.
if(condition) {
statement 1;
}
B. if-else statement: The if-else statement is an extension to the if-statement, which uses
another block of code, i.e., else block. The else block is executed if the condition of the if-block is
evaluated as false.
if(condition)
{
statement 1;
}
else{
statement 2;
}
Switch Statement:
1. Switch statements are similar to if-else-if statements.
2. The case variables can be int, short, byte, char, or enumeration, String type.
3. Cases cannot be duplicate
4. Default statement is executed when any of the case doesn't match the value of expression. It is
optional.
5. Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
6. While using switch statements, we must notice that the case expression will be of the same type
as the variable. However, it will also be a constant value.
Syntax:
switch (expression){
case value1:
statement1;
break;
case valueN:
statementN;
break;
default:
default statement;
}
code:
public class Student implements Cloneable {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
[Link]("number is 0");
break;
case 1:
[Link]("number is 1");
break;
default:
[Link](num).
}
}
}
Loop Statements:
In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true. However, loop statements are used to execute the set of instructions in a repeated
order.
1. for loop
2. while loop
3. do-while loop
A. For loop: It enables us to initialize the loop variable, check the condition, and
increment/decrement in a single line of code. We use the for loop only when we exactly know
the number of times, we want to execute the block of code.
code:
code:
public class Calculation {
public static void main(String[] args) {
int i = 0;
[Link]("Printing the \n");
while(i<=10) {
[Link] (i);
i = i + 2;
}
}
}
D. do-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. The syntax of the do-while loop is given below.
do
{
//statements
} while (condition);
code:
public class Calculation {
public static void main(String[] args) {
int i = 0;
[Link]("Printing the list of first 10 even numbers \n");
do {
[Link](i);
i = i + 2;
} while(i<=10);
}
}
Jump Statements:
Jump statements are used to transfer the control of the program to the specific statements. In other
words, jump statements transfer the execution control to the other part of the program. There are two
types of jump statements in Java,
break
1.
continue.
2.
A. Java break statement: As the name suggests, the break statement is used to break the current
flow of the program and transfer the control to the next statement outside a loop or switch
statement. However, it breaks only the inner loop in the case of the nested loop. The break
statement cannot be used independently in the Java program, i.e., it can only be written inside
the loop or switch statement.
The break statement example with for loop . Consider the following example in which we have
used the break statement with the for loop.
code:
public class BreakExample {
public static void main(String[] args) {
for(int i = 0; i<= 10; i++) {
[Link](i);
If ( i==6) {
break;
}
}
}
}
B. Java continue statement: Unlike break statement, the continue statement doesn't break the loop,
whereas it skips the specific part of the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in Java.
public class ContinueExample {
public static void main(String[] args) {
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4)
continue;
[Link](j);
}
}
}
}
Array is initialized:
1. Passing no value within the initializer: int arr[ 5 ] = { };
2. By passing specific values within the initializer: int arr[ 5 ] = { 1, 2, 3, 4, 5 };
3. Passing specific values within the initializer but not declaring the size: int arr[ ] = { 1, 2, 3, 4, 5 };
code:
class Testarray{
public static void main(String args[]){
int a [] =new int[5];
a[0]=10;
}
}
60
B. 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.
class Testarray4{
public static void main(String args[]){
int arr[] = {4,4,5};
Class c = [Link]();
String name = [Link]();
[Link](name);
}
}
Jagged Array:
Anonymous Array
String handling ---- 113
1. String is sequence of character. It is combination of character.
2. String is object in java.
3. String is immutable.
4. The process of performing operation over the string is called string handling.
5. String handle package
a. [Link]
b. [Link]
c. [Link]
d. [Link]
A. string class:
Create object of:
1. With new: Here memory allocation in heap memory area. Every time new create memory
allocated in heap memory.
string s = new String (“shuvo”)
2. Without new or string literal: In string literal, we just hold the string literal in variable. In java,
string literal treated as string object.
Whenever we creating the string object via literal it allocated memory in String constant poll.
Here same string value memory allocated for only one. Other share same memory.
String s = “shuvo”
Heap Memory
Heap Memory
String str= “hello”;
String PP = “hello”; Constrain pool area
String ob = new String(“shuvo”); “Hello”
String m = new String(“shuvo”) “Hello wold”
“shuvo”
“shuvo”
constructor:
1. StringBuffer()
2. StringBuffer(String str)
3. StringBuffer(int capacity)
method:
1. append(String s)
2. insert(int offset, String s)
3. replace(int startIndex, int endIndex, String str)
4. delete(int startIndex, int endIndex)
5. reverse()
6. capacity()
7. ensureCapacity(int minimumCapacity)
C. Java StringBuilder Class: Java StringBuilder class is used to create mutable (modifiable) String.
The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized.
As a language that has the Object-Oriented feature, Java supports the following fundamental concepts –
1. Classes
2. Objects
3. Inheritance
4. Polymorphism
5. Encapsulation
6. Abstraction
7. Instance
8. Method
9. Message Passing
CLASSES
1. A class is a blueprint of object.
2. Class is user defined data type.
3. Class declared by class key word.
4. The class body is enclosed between curly braces { }.
5. The data or variables, defined within a class are called instance variables.
6. The code is contained within methods.
7. Collectively, the methods and variables defined within a class are called members of the class
code:
public class Dog {
String breed;
int age;
void barking() {
}
}
Types of Classes:
1. Bean class
2. Pojo Class
3. Final Class
4. Static Class
5. Abstract Class
6. Concrete Class
7. Inner Class
8. Java Enum Class
9. Java Reflection
Other Special Classes in Java:
1. Immutable Class
2. Singleton Class
3. Object Class
4. Wrapper Class
C. Concreate class:
1. A concrete class is any normal class in a Java program. This class will not have any abstract
methods. All the methods in the concrete class are completely implemented.
2. A concrete class can inherit from another class, even an abstract class or implement an
interface. We can instantiate the concrete class and create its objects.
D. Object Class:
1. Object class is present in [Link] package.
2. Every class in Java is directly or indirectly derived from the Object class.
3. If a class does not extend any other class, then it is a direct child class of Object and if extends
another class then it is indirectly derived.
4. Therefore, the Object class methods are available to all Java classes.
5. Hence object class acts as a root of the inheritance hierarchy in any Java Program.
class Database {
private static Database ob;
private Database() {
}
public static Database getInstance() {
if(ob == null) {
ob = new Database();
}
return ob;
}
public void getConnection() {
[Link]("connected.");
}
}
class Main {
public static void main(String[] args) {
Database db;
db= [Link]();
[Link]();
}
}
## Singletons can be used while working with databases. They can be used to create a connection pool
to access the database while reusing the same connection for all the client
F. Wrapper Class:
1. The wrapper class convert primitive data type into object and object into primitive data type.
2. A Wrapper class is a class whose object wraps or contains primitive data types.
3. When we create an object to a wrapper class, it contains a field and in this field, we can store
primitive data types. In other words, we can wrap a primitive value into a wrapper class object.
code:
Interger y = new Interger(10);
int x = [Link]();
Auto-boxing: The automatic conversion of primitive data type into its corresponding wrapper
class is known as auto-boxing, for example, byte to Byte, char to Character, int to Integer, long
to Long, float to Float, Boolean to Boolean, double to Double, and short to Short. Since J2SE
5.0, auto-boxing and unboxing feature convert primitives into objects and objects into primitives
automatically
G. Java Enum:
Enum (enumeration) is a type that has a fixed set of constant values. We use the enum keyword to
declare enums.
code:
enum Size {
SMALL, MEDIUM, LARGE, EXTRALARGE
}
class Main {
public static void main(String [] args) {
[Link]([Link]);
[Link]([Link]);
}
}
METHOD
1. A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation.
2. Method creates in class.
3. It is used to achieve the reusability of code
4. We write a method once and use it many times.
5. We can also easily modify code using methods.
1. Access Specifier/Modifier: Access specifier or modifier is the access type of the method. It
specifies the visibility of the method. Java provides four types of access specifier:
2. Return Type: It specifies what type of value a method returns for example if a method has
an int return type then it returns an integer value. If the method does not return a value, its
return type is void.
3. Method Name: It is an identifier that is used to refer to the method in a program.
4. Method body: It includes the programming statements that are used to perform some tasks.
The method body is enclosed inside the curly braces {}.
There are two types of methods:
1. User-defined Method: The method written by the user or programmer is known as a user-
defined method. These methods are modified according to the requirement.
public static void findEvenOdd ( int num ){
If (num%2 == 0)
[Link](num+" is even");
else
[Link](num+" is odd");
}
2. Standard library Method: In Java, Method that is already defined in the Java class libraries is
known as standard library method or built-in method. We can directly use these methods just
by calling them in the program at any point. Some pre-defined methods are-
1. length()
2. equals()
3. compareTo()
Other Method:
1. Static Method
2. Instance Method
3. Abstract Method
4. Factory Method
A. Static Method:
1. We can also create a static method by using the keyword static before the method name.
2. Static method is called without creating an object.
3. It is invoked by using the class name.
4. Static method can’t use non static member.
5. “this” and “super” keyword can’t be used here.
6. They are accessed by the class name and a dot (.) followed by the name of a method.
class boy{
int x =10;
static void show() {
[Link](10);
}
}
public class main {
public static void main(String[] args) {
[Link]();
}
}
B. Instance Method/non-static:
1. The simple method of the class is known as an instance method.
2. It is a non-static method defined in the class.
3. Before calling or invoking the instance method, it is necessary to create an object of its class.
Code:
public class ABC {
public static void main(String [] args){
ABC ob = new ABC();
[Link]( [Link](12, 13) );
}
public int add(int a, int b) {
return a + b ;
}
}
1. Accessor/Getter Method: The method(s) that reads the instance variable(s) is known as the
accessor method. We can easily identify it because the method is prefixed with the word get. It
is also known as getters. It returns the value of the private field. It is used to get the value of the
private field.
public int getId(){
return Id;
}
2. Mutator/Setter Method: The method(s) read the instance variable(s) and modify the values. We
can easily identify it because the method is prefixed with the word set. It is also known
as setters or modifiers. It does not return anything. It accepts a parameter of the same data
type that depends on the field. It is used to set the value of the private field.
public void setRoll(int roll){
[Link] = roll;
}
Example of accessor and mutator method,
C. Abstract Method:
1. The method that does not has method body is known as abstract method.
2. There is no need to provide the implementation code while declaring it.
3. It always declares in the abstract class.
4. It declares with abstract key word.
E. Chaining method:
a. Method chaining is the chain of methods being called one after another.
b. For method changing we return “this” variable in method in class.
c. The return type should be class type of the method.
syntax: obj.method1().method2().method3();
code:
class User{
private float b;
User input(float b) {
this.b = b;
return this;
}
void display() {
[Link]("Display=" + b);
}
}
public class Example {
public static void main(String[] args) {
new User().input(10).display();
}
}
2. Changing the data type of parameters: if change function argument type then it also function
overloading.
class MethodOverloading {
private static void display(int a){
[Link]("Got Integer data.");
}
private static void display(String a){
[Link]("Got String object.");
}
private static void display(int a, long b){
[Link]("Arguments: " + a + " and " + b);
}
public static void main(String[] args) {
display(1);
display("Hello");
}
}
Method rules:
1. Method under method not possible.
2. Method should declare under a class.
Class Test {
Static void sum (){
Int x = 10;
Int y = 16;
}
Public static void main (String a[]){
sum (x+y);
}
}
3. Method should call with class. None static method cannot call directly.
Class Test {
Static void sum (){
Int z = 15+ 16;
}
Public static void main (String a[]){
Test t = new Test ();
[Link]()
}
}
Main method in java:
When we write a program, we write multiple code and class in program. But when we run the program,
java do not know from where we run the code. So that we write an identifier class called main. If we
write a main class in java program, java know that from here it run code. So, we write main method, and
JVM run the main method. Main method is not pre-defined or user define. It is a contract between
programmer and programing language.
class Main {
public static void main(String[] args) {
Main obj = new Main();
[Link]("Value of i: " + obj);
}
}
1. We can run java program without main method.
2. We can called main method in every class.
3. We can change the main method name. (For change the main method name we should change the
JVM main method name).
4. main method is static because if we do main method as a non-static then we want to make object of
main method class. So memory consumption we make main method static.
5. main method is public because we can access main method anywhere of code.
6. main method is void because it is not return type. (in java main Method not Return any things. but
in C main method return ending to compiler, so that it need return type . but java did not. )
7. In main method we can pass array type argument. Because in compiler time we pass string type
argument in main method. It is command line argument.
class A{
public static void main(String[] arg){
}
}
class B {
public static void main(String[] p){
[Link]();
}
}
Argument pass in main method:
class A{
public static void main(String[] arg){
}
}
class B {
String ar[] = {“heelo”};
public static void main(String[] p){
[Link]();
[Link](“ar”);
[Link](null);
[Link](p)
}
}
Variable Arguments (Varargs):
The varrags allows the method to accept zero or muliple arguments. Before varargs either we use
overloaded method or take an array as the method parameter but it was not considered good because it
leads to the maintenance problem. If we don't know how many argument we will have to pass in the
method, varargs is the better approach. the Varargs method, we can differentiate arguments by using
Index. A variable-length argument is specified by three periods or dots(…).
Syntax:
CONSTRUCTORS:
1. A constructor in Java is a special method that is used to initialize objects.
2. The constructor is called when an object of a class is created.
3. It can be used to set initial values for object attributes.
4. Java compiler creates a default constructor when object create.
5. The name of the constructor should be the same as the class.
6. A Java constructor must not have a return type.
code:
public class Puppy {
public Puppy() {
}
}
Types of Constructors:
A. No-argument constructor: A constructor that has no parameter is known as the No-argument
or Zero argument constructor.
class Main {
int i ;
private Main() {
i = 5;
[Link]("Constructor is called");
}
public static void main(String[] args) {
Main obj = new Main();
[Link]("Value of i: " + obj.i);
}
}
B. Parameterized Constructor: A constructor that has parameters is known as parameterized
constructor. If we want to initialize fields of the class with our own values, then use a
parameterized constructor.
class Main {
String languages;
Main(String lang) {
languages = lang;
[Link](“Programming Language");
}
public static void main(String[] args) {
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
C. Default Constructor: If we do not create any constructor, the Java compiler automatically
create a no-argument constructor during the execution of the program. This constructor is
called default constructor.
Access modifier of constructor depends on class. If class public then constructor public.
class User{
User(){
}
}
Block /initializer
A block in Java is a set of code enclosed within curly braces { } within any class, method, or constructor.
It begins with an opening brace “{“ and ends with an closing braces “}” .Between the opening and
closing braces, we can write codes which may be a group of one or more statements.
Syntax:
public class{
……. code
}
There are three types of blocks in Java. They are as follows:
1. Local block
2. Static block: - object independent
3. Non static block (init block): -object dependent
A. Static block:
1. static keyword with a block of code that is known as a static block.
2. A static block can have several instructions that always run when a class is loaded into memory.
3. It is also known as java static initializer block because we can initialize the static variables in
the static block at runtime.
4. A class can have any number of static blocks, The JVM executes them in the sequence in which
they have been written.
5. A static block only executes for a single time for the life cycle of the program.
6. The static block in a program is always executed first before any static method, non-static
method, main method, or even instance block.
syntax:
static {
// Body of static block
}
code:
public class MainClass{
static int b;
public static void show(){
[Link]("Static method");
}
static{
b = 5;
show();
}
public static void main(String arg[]){
[Link]("Main method");
}
}
syntax:
{
…. code
}
code:
class User{
{
[Link](“hello “);
}
public static void main (String [] args){
new User ();
}
}
When in a program the name of local variable and the name of instance variable is same, this concept is
called data shadowing. In data shadowing preference goes to local variable.
Code:
class User{
int x = 10;
void show(){
int x = 20;
}
public static void main(String ss[]){
User Shuvo = new User();
[Link]():
}
}
This Keyword:
In data shadowing we face the problem for use intense variable in class. to solve this problem, we use
this key word for reference variable.
For solving the shadowing problem, we pass object reference in method for use instance variable .
class User{
int x = 10;
void show(User ob){
int x = 100;
int ob.x = 20;
}
public static void main(String ss[]){
User Shuvo = new User();
[Link](shuvo):
}
}
But it this very complex in programing . So, remove this complexity java introduced “this” keyword
which is reference variable.
class Use{
int x = 10;
void show(){
int x = 100;
int this.x = 20;
}
public static void main(String ss[]){
User Shuvo = new User();
[Link]():
}
}
uses of this:
a. we use this for object refarance
b. method chaining: we use this in method chaining
class User{
private float b;
User input(float b) {
this.b = b;
return this;
}
void display() {
[Link]("Display=" + b);
}
}
public class Example {
public static void main(String[] args) {
new User().input(10).display();
}
}
c. constructor chaining : We called multiple constructors with “this” keyword. for this we called
this() method and pass argument which constructor want to called. “this” should called first line
in method.
Code:
class User{
void User() {
this(2);
[Link]();
}
void User(int a) {
this(2,3)
[Link](a);
}
void User(int a, int b) {
[Link](a+ b);
}
}
public class Example {
public static void main(String[] args) {
new User()
}
}
d. this can call static and non-static method.
Code:
class User{
int a ;
void input(int a) {
this.a = a;
}
void show() {
[Link](a);
}
}
public class Example {
public static void main(String[] args) {
new User()
}
}
Objects
Let us now look deep into what are objects. If we consider the real-world, we can find many objects
around us, cars, dogs, humans, etc. All these objects have a state and a behavior. If we consider a dog,
then its state is - name, breed, color, and the behavior is - barking, wagging the tail, running. If you
compare the software object with a real-world object, they have very similar characteristics. Software
objects also have a state and a behavior. A software object's state is stored in fields and behavior is
shown via methods. So, in software development, methods operate on the internal state of an object
and the object-to-object communication is done via methods.
1. Creating an Object
1. By new Keyword: The new keyword is used to create objects. new keyword is use for memory
allocation in ram. so that new keyword uses for object keyword.
Syntax:
new classname();
classname variable = new classname();
code:
Public class User{
String name;
Int id;
}
new User();
User shuvo = new User();
2. By Factory Pattern:
3. By Clone Method:
4. newInstance method:
5. Anonymous Object:
1. An anonymous object is basically a value that has been created but has no name.
2. when creating an object in Java, you need to assign a name to the object. But anonymous object
only uses when we create.
Public class User {
String name;
Int id;
public static void main (String [] args) {
new User ();
}
}
3. Every time anonymous object called, every time new object create and new ref value create.
code:
Public class User {
String name;
Int id;
Public function show(){
[Link](name);
}
public static void main (String [] args) {
new User ().name=” shuvo”;
new User (). show ();
new User ().id=12364;
}
}
6. Object Reference:
1. When object create a unique id create for object which is reference id. The reference id stores
those variables called reference variable.
2. if we use null as object reference then garbage collection deletes the memory for object which
do not have ref vary.
3. In java we can give on object Reference to another object. If we change one object value,
another object will change.
Public class User {
public static void main (String [] args) {
User obj1 = new User ();
User obj2 = new User ()
obj2= obj1
}
}
Association/Reusability of class -- 70
1. Association is a relation between two separate classes which establishes through their Objects.
2. Association can be one-to-one, one-to-many, many-to-one, many-to-many.
3. In Object-Oriented programming, an Object communicates to another object to use functionality
and services provided by that object.
Types of Association
1. IS-A Association
2. HAS-A Association
IS-a relationship:
1. Whenever one class inherits another class, it is called an IS-A relationship.
2. it known as inheritance in java.
code:
public class Address {
String city;
int road;
}
public class Person extends Address {
Address add = new Address ();
[Link] = “dhaka”;
}
HAS-A relationship:
a. When an object of one class is created as a data member inside another class, it is called Has-A
relationship.
b. Association is a relation between two separate classes which establishes through their Objects.
c. There are two types of Has-A relationship
a. Composition(Strong)
b. Aggregation(Weak)
code:
public class Address {
String city;
int road;
}
public class Person { // Person has-a Address.
Address add = new Address ();
[Link] = “dhaka”;
}
1. Aggregation(weak):
It represents Has-A’s relationship.
It is a unidirectional association. For example, a department can have students but vice
versa is not possible.
In Aggregation, both the entries can survive individually which means ending one entity will
not affect the other entity.
Example:- a library class extends student’s class. If the library is destroyed, students will
exist without library.
2. Composition(Strong):
It represents part-of relationship.
In composition, both entities are dependent on each other.
When there is a composition between two entities, the composed object cannot exist
without the other entity.
Inheritance ---71
1.
2. Inheritance can be defined as the process where one class acquires the properties (methods and
fields) of another.
3. With the use of inheritance, the information is made manageable in a hierarchical order.
4. The class which inherits the properties of other is known as subclass /Child Class (derived class,
child class) and the class whose properties are inherited is known as superclass /Parent Class
(base class, parent class).
5. Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
6. extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.
Syntax:
class A {
………….
}
class Sub extends A {
………….
}
code:
class Parent {
String name;
public void eat() {
[Link]("I can eat");
}
}
class Child extends Parent {
public void display () {
[Link]( name);
}
public static void main(String[] args) {
Child ob = new Child();
[Link] = "shuvo";
[Link]();
}
}
Types of Inheritance:
Java Hybrid Inheritance
Data Hiding:
1. When in program, the name of parent class data variable and the name of child class data
variable are same, then program take child class data as main variable, this concept is called
data hiding.
2. Whenever data hiding is done always preference goes to child class data.
class Parant {
String name;
}
class Child extends Parant {
String name;
public void show () {
[Link]( name );
}
public static void main(String[] args) {
Child obj = new Child ();
[Link]();
}
}
Parent to child:
class Parent {
int x = 444;
}
class Child extends Parent {
int x = 10
void show(){
[Link](“hello ”);
}
}
class Upcasting{
public static void main(String args[]) {
Parent obj = new Child ();
[Link](obj);
}
}
Grand-parent to child:
class Grandparent{
int x = 9999;
}
class Parent extend Grandparent {
int x = 444;
}
class Child extends Parent {
int x = 10
public void show (Parent objP, Grandparent objG ) {
[Link](x) ;
[Link]( objP.x );
[Link]( objG.x );
}
public static void main(String args[]) {
Child obj = new Child();
[Link](obj, obj );
}
Downcasting:
downcasting is a type of object typecasting in which a Parent object is typecasted to a child class object.
class Parent {
int x = 444;
}
class Child extends Parent {
int x = 10
display(){
[Link](“dkfj”);
}
public static void main(String args[]) {
Parent obj = new Child();
Child ob2 = (Child) obj;
}
}
Super:
1. If we want access the parent class data variable, we can do it by super keyword.
2. The super keyword in java is a reference variable that is used to refer parent class objects.
3. Super only call the immediate parent data not parent of parent.
4. Super cannot use inside static context
class Parant {
String name;
}
class Child extends Parant {
String name;
public void show () {
[Link](name);
[Link]([Link]);
}
public static void main (String [] args) {
Child obj = new Child ();
[Link]();
}
}
Method overriding:
1. if the same method is defined in both the superclass and the subclass, then the method of the
subclass class overrides the method of the superclass. This is known as method overriding.
2. The method must have the same name as in the parent class
3. The method must have the same parameter as in the parent class.
4. There must be an IS-A relationship (inheritance).
5. Method overrides access modifier always weaker to stronger. Public -> protected-> default-
>private
code:
class Vehicle{
void run(){
[Link]("Vehicle is running");
}
}
class Bike2 extends Vehicle{
void run(){
[Link]("Bike is running safely");
}
public static void main(String args[]){
Bike2 obj = new Bike2();
[Link]();
}
}
Covariant Return:
1. we can method override with change return type (it is come in after jdk 1.5). it is called
covariant type.
2. Both class method must have return type is reference type whereas primitive data type not
allowed.
3. The classes which used as return type they also must have relation of parent and child.
class Vehicle{
void run(){
[Link]("Vehicle is running");
}
}
class Bike2 extends Vehicle{
Vehicle run(){
[Link]("Bike is running safely");
}
public static void main(String args[]){
Bike2 obj = new Bike2();
[Link]();
}
}
Method hiding:
When static method, of parent class override in static method of child class is called method hiding.
class Vehicle{
void static run(){
[Link]("Vehicle is running");
}
}
class Bike2 extends Vehicle{
Vehicle static run(){
[Link]("Bike is running safely");
}
public static void main(String args[]){
Bike2 obj = new Bike2();
[Link]();
}
}
Class K{
K(int x){
[Link](“constructor K”);
}
}
Class L extends K{
Super(22);
L(){
[Link](“constructor L”);
}
}
Public class B extends L{
B(){
[Link](“constructor B”);
}
}
Encapsulation ----- 87
OPP Encapsulation: in OOPs is the concept of binding fields (object state) and methods (behavior)
together as a single unit. Another way to think about encapsulation is, that it is a protective shield that
prevents the data from being accessed by the code outside this shield.
JAVA Encapsulation: Programming languages such as Java use encapsulation with help of classes. So
that as aspect of java, Encapsulation is the process of wrapping the data member and member function
within a class and create a protective barrier around them.
1. Data Hiding: it is a way of restricting the access of our data members by hiding the
implementation details. Encapsulation also provides a way for data hiding. The user will have no
idea about the inner implementation of the class. It will not be visible to the user how the class
is storing values in the variables. The user will only know that we are passing the values to a
setter method and variables are getting initialized with that value.
2. Increased Flexibility: We can make the variables of the class read-only or write-only depending
on our requirement. If we wish to make the variables read-only then we have to omit the setter
methods like setName(), setAge(), etc. from the above program or if we wish to make the
variables write-only then we have to omit the get methods like getName(), getAge(), etc. from
the above program
3. Reusability: Encapsulation also improves the re-usability and is easy to change with new
requirements.
4. Testing code is easy: Encapsulated code is easy to test for unit testing
Binding –91
Binding is a mechanism creating link between method call and method actual implementation.
Code:
Class User{
Void show(){ // method implementation
[Link](“ show ”);
}
Public void static main(String ss[]){
User shuvo = new User();
[Link](): //method called.
}
}
class Parent {
int x = 444;
static int y = 20;
}
class Child extends Parent {
int x = 10;
static int y = 20;
static show(){
[Link](x)
}
}
class Dynamic {
public static void main(String args[]) {
Parent obj = new Child();
[Link](); // invoke virtual
}
}
Dynamic Binding (Runtime Binding / late binding):
1. When member call getting/linking their member definition at runtime it called runtime binding.
2. Run time building do JVM.
3. Runtime binding done on type of object.
4. Non-static/virtual method is bind in dynamic.
Polymorphism ---96
1. Polymorphism means more than one form. The same entity (method or operator or object) can
perform different operations in different scenarios.
2. A person at the same time can have different characteristics. Like a man at the same time is a father,
a husband, an employee. So, the same person possesses different behavior in different situations.
This is called polymorphism.
3. Polymorphism always achieve on method not on data member.
4. We can perform polymorphism in java by method overloading and method overriding.
Compile-time Polymorphism:
1. Compile Time Polymorphism is also known as Static Polymorphism.
2. Furthermore, the call to the method is resolved at compile-time.
3. Compile-Time polymorphism is achieved through Method Overloading, constructor overloading
Runtime Polymorphism:
1. It is also known as Dynamic Method Dispatch.
2. It is a process in which a function call to the overridden method is resolved at Runtime.
3. This type of polymorphism is achieved by Method Overriding and Upcasting.
class Animal {
public void move() {
[Link]("Animals can move");
}
}
class Dog extends Animal {
public void move() {
[Link]("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
[Link](); // runs the method in Animal class
[Link](); // runs the method in Dog class
}
}
Abstraction ---102
Abstraction:
1. Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
2. it shows only essential things to the user and hides the internal details.
Example: IF sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
Code:
Method:
1. A method which is declared as abstract and does not have implementation is known as an
abstract method.
2. An abstract method contains a method name, but no method body in abstract class.
3. Instead of curly braces, an abstract method will have a semi colon (;)
4. abstract method cannot private.
5. abstract method cannot static. Because abs
6. final.
7. if any method declared in abstract class, then extends class must be override the method.
8. If abstract method declared in class and class is not declared abstract class then, class will be
abstract class.
9. Abstract method can be creating construction.
code:
abstract class Bike {
abstract void run ();
}
Syntax:
interface <interface_name>{
// declare constant fields
}
code:
interface Player {
final int id = 10;
int move ();
}
Modifier / keyword
Access specifier or modifier is the access type of the method. It specifies the visibility of the method.
Java provides four types of access specifier:
Public:
The method is accessible by all classes when we use public specifier in our application.
Private:
When we use a private access specifier, the method is accessible only in the classes in which it is
defined.
Protected:
When we use protected access specifier, the method is accessible within the same package or
subclasses in a different package.
Default:
When we do not use any access specifier in the method declaration, Java uses default access specifier by
default. It is visible only from the same package only.
Static:
1. The static keyword in Java is mainly used for memory management.
2. The static keyword in Java is used to share the same variable or method of a given class.
3. The users can apply static keywords in –
a) variables,
b) methods,
c) blocks, and
d) nested classes.
4. we can use static before class, interface constructor.
5. When a member is declared static, it can be accessed before any objects of its class are created,
and without reference to any object.
A. Java static variable: If you declare any variable as static, it is known as a static variable. The static
variable can be used to refer to the common property of all objects (which is not unique for each
object), for example, the company name of employees, college name of students, [Link] static
variable gets memory only once in the class area at the time of class loading.
class Student{
int roll;
String name;
String college="ITS";
}
B. Java static method: When a method is declared with the static keyword, it is known as the static
method. The most common example of a static method is the main( ) method. Any static member
can be accessed before any objects of its class are created, and without reference to any object.
static method represents the behavior of class. non-static method represent of object.
1. They can only directly call other static methods.
2. They can only directly access static data.
3. They cannot refer to this or super in any way.
class Test{
static int a = 10;
int b = 20;
static void m1(){
a = 20;
[Link]("from m1");
b = 10; // compilation error
m2(); // compilation error
[Link](super.a); // compiler error
}
void m2() {
[Link]("from m2");
}
public static void main(String[] args) {
// main method
}
}
C. Static Classes: A class can be made static only if it is a nested class. We cannot declare a top-level
class with a static modifier but can declare nested classes as static. Such types of classes are called
Nested static classes. Nested static class doesn’t need a reference of Outer class. In this case, a static
class cannot access non-static members of the Outer class.
import [Link].*;
public class GFG {
private static String str = "GeeksforGeeks";
static class MyNestedClass {
public void disp(){
[Link](str);
}
}
public static void main(String args[]) {
[Link] obj = new [Link]();
[Link]();
}
}
Final keyword :
1. It is the keyword that used to restrict the user.
2. It is used in variable method, class.
3. Final method cannot override.
4. Final class cannot inheritance.
5. Final variable cannot change.
A. Final class:
final class A {
// methods and fields
}
class B extends A {
// COMPILE-ERROR! Can't subclass A
}
B. Final method:
class A {
final void m1() {
[Link]("This is a final method.");
}
}
class B extends A {
void m1() {
// Compile-error! We cannot override
[Link]("Illegal!");
}
}
C. Final variable:
1. If you make any variable as final, you cannot change the value of final variable (It will be
constant). This also means that you must initialize a final variable.
2. A final variable that is not initialized at the time of declaration is known as blank final variable.
3. If the final variable is a reference, this means that the variable cannot be re-bound to reference
another object, but the internal state of the object pointed by that reference variable can be
changed i.e. you can add or remove elements from the final array or final collection.
class GFG {
final int THRESHOLD = 5;
final int CAPACITY;
final int MINIMUM;
static final double PI = 3.141592653589793;
static final double EULERCONSTANT;
{
CAPACITY = 25;
}
static {
EULERCONSTANT = 2.3;
}
public GFG () {
MINIMUM = -1;
}
}
Package of java
PACKAGE in Java is a collection of classes, sub-packages, and interfaces. It helps organize your classes
into a folder structure and make it easy to locate and use them. More importantly, it helps improve code
reusability. Each package in Java has its unique name and organizes its classes and interfaces into a
separate namespace, or name group.
Create a package:
package p1;
class c1(){
public void m1(){
[Link]("m1 of c1");
}
public static void main(string args[]){
c1 obj = new c1();
obj.m1();
}
}
Use package :
Sub packages: Packages that are inside another package are the sub packages. These are not imported
by default; they must import explicitly. Also, members of a sub package have no access privileges, i.e.,
they are considered as different package for protected and default access specifiers.
Types of packages:
1. Built-in Packages
2. User-defined packages
B. Exceptions:
Exceptions can be caught and handled by the program. When an exception occurs within a method,
it creates an object. This object is called the exception object. It contains information about the
exception such as the name and description of the exception and state of the program when the
exception occurred.
a) try...catch: The try...catch block in Java is used to handle exceptions and prevents the abnormal
termination of the program.
try {
int divideByZero = 5 / 0;
[Link]("Rest of code in try block");
}
catch (ArithmeticException e) {
[Link]("ArithmeticException => " + [Link]());
}
b) finally block: finally, block is always executed no matter whether there is an exception or not.
The finally block is optional. And, for each try block, there can be only one finally block.
try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}
c) throw and throws: The throw statement allows you to create a custom error.
class ThrowExcep{
static void fun() {
try {
throw new NullPointerException("demo");
}
catch(NullPointerException e) {
[Link]("Caught inside fun().");
throw e; // rethrowing the exception
}
}
public static void main(String args[]) {
try{
fun();
}
catch(NullPointerException e){
[Link]("Caught in main.");
}
}
}
FILE/IO handling
Java I/O (Input and Output) is used to process the input and produce the output.
Stream: A stream can be defined as a sequence of data. There are two kinds of Streams −
1. Byte Stream
2. Character Stream
Byte Stream: Byte stream is used to read and write a single byte (8 bits) of data.
1. Java InputStream Class
2. Java OutputStream Class
Character Stream:
Character stream is used to read and write a single character of data. Java Character streams are used
to perform input and output for 16-bit Unicode.
All the character stream classes are derived from base abstract classes Reader and Writer.
1. FileReader
2. FileWriter
File class :
1. file
2. fileReader
3. fileWrite
4. fileinputstream
5. fileoutputstream
6. bufferinputstream
7. bufferoutputstream
Generics
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined
types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create
classes that work with different data types. An entity such as class, interface, or method that operates
on a parameterized type is a generic entity.
1. We can hold only a single type of objects in generics. It does not allow to store other objects.
2. There is no need to typecast the object.
3. It is checked at compile time so problem will not occur at runtime.
4. We can generic in all interface of collection.
1. T – Type
2. E – Element
3. K – Key
4. N – Number
5. V – Value
class Test {
static <T> void genericDisplay(T element) {
[Link]([Link]().getName() + " = " + element);
}
public static void main(String[] args){
genericDisplay(11);
genericDisplay("GeeksForGeeks");
genericDisplay(1.0);
}
}
B. Generic Classes: A generic class is implemented exactly like a non-generic class. The only
difference is that it contains a type parameter section. There can be more than one type of
parameter, separated by a comma. The classes, which accept one or more parameters, are known
as parameterized classes or parameterized types.
class Test<T> {
T obj;
Test( T obj) { [Link] = obj; }
public T getObject() { return [Link]; }
}
class Main {
public static void main(String[] args) {
Test<Integer> Obj1 = new Test<Integer>(15);
[Link]( [Link]() );
Test<String> Obj2 = new Test<String>("GeeksForGeeks");
[Link]([Link]());
Obj1 = Obj2;
}
}
Lambda Expression
Collections Framework
1. The Collection in Java is a framework that provides an architecture to store and manipulate the
group of objects.
2. Java Collections can achieve all the operations that you perform on a data such as searching, sorting,
insertion, manipulation, and deletion.
1. List Interface
2. Queue Interface
3. Set Interface
List Interface:
1. The List interface is an ordered collection that allows us to store and access elements sequentially.
2. It extends the Collection interface.
3. Since List is an interface, we cannot create objects from it.
4. we must import [Link] package in order to use List.
5. class of List interface ------------
1. ArrayList class
2. LinkedList class
3. Vector class
4. Stack class
ArrayList Class:
1. The ArrayList class of the Java collections framework provides the functionality of resizable-arrays.
2. ArrayList provides us with dynamic arrays in Java
3. Creating an ArrayList Before using ArrayList, we need to import the [Link] package first.
code:
import [Link];
class Main {
public static void main(String[] args) {
ArrayList<String> user= new ArrayList<>();
user. add("shuvo");
[Link]("korim");
for (String p : user) {
[Link](p);
[Link](", ");
}
}
}
Constructor of arrayList :
1. ArrayList(): This constructor is used to build an empty array list.
ArrayList arr = new ArrayList();
2. ArrayList(Collection c): This constructor is used to build an array list initialized with the elements
from the collection c
ArrayList arr = new ArrayList(c);
3. ArrayList(int capacity): This constructor is used to build an array list with initial capacity being
specified.
ArrayList arr = new ArrayList(N);
LinkedList class:
1. LinkedList class is an implementation of the LinkedList data structure which is a linear data structure
where the elements are not stored in contiguous locations and every element is a separate object
with a data part and address part.
2. The elements are linked using pointers and addresses. Each element is known as a node.
3. It consists of 3 fields:
a. Prev - stores an address of the previous element in the list. It is null for the first element
b. Next - stores an address of the next element in the list. It is null for the last element
c. Data - stores the actual data
code :
import [Link];
class Main {
public static void main(String[] args){
LinkedList<String> animals = new LinkedList<>();
[Link]("Dog");
[Link]("Cat");
[Link]("Cow");
[Link]("LinkedList: " + animals);
[Link](1, "Horse");
[Link]("Updated LinkedList: " + animals);
}
}
Vector class:
1. The Vector class is an implementation of the List interface that allows us to create resizable-arrays
like the ArrayList class.
2. Vector is synchronized.
3. Java Vector contains many legacy methods that are not the part of a collection’s framework.
4. In vector capacity increase double.
Example:
class Main {
public static void main(String[] args) {
Vector<String> animals= new Vector<>();
[Link]("Dog");
[Link]("Horse");
[Link]("Cat");
Iterator<String> iterate = [Link]();
while([Link]()) {
[Link]( [Link]() );
[Link](", ");
}
}
}
Constructor of vector :
code:
import [Link].*;
public class GFG {
public static void main(String args[])
{
Stack<String> stack = new Stack<String>();
[Link]("Geeks");
[Link]("For");
[Link]("Geeks");
Iterator<String> itr = [Link]();
while ([Link]()) {
[Link]([Link]() + " ");
}
itr = [Link]();
while ([Link]()) {
[Link]([Link]() + " ");
}
}
}
Stack Methods:
1. empty()
2. push(E item)
3. pop()
4. peek()
5. search(Object o)
Methods of Collection:
The Collection interface includes various methods that can be used to perform different operations on
objects. These methods are available in all its sub interfaces.
1. add() - inserts the specified element to the collection.
2. size() - returns the size of the collection.
3. set() : To change elements of the arraylist.
4. remove() - removes the specified element from the collection.
5. iterator() - returns an iterator to access elements of the collection.
6. addAll() - adds all the elements of a specified collection to the collection.
7. removeAll() - removes all the elements of the specified collection from the collection.
8. clear() - removes all the elements of the collection.
9. isEmpty()- This method returns true if this collection contains no elements.
10. max()--This method is used to return the maximum value present in the collection.
11. toArray() --This method is used to return an array containing all the elements in this collection.
Queue Interface
1. A queue interface maintains the FIFO(First in First Out) order similar to a real-world queue line.
2. This interface is dedicated to storing all the elements where the order of the elements matter.
3. class and interface list in queue interface
1. priority Queue class
2. Deque interface
a. linkedList class
b. ArrayDeque class
PriorityQueue class:
A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is
known that a queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue
are needed to be processed according to the priority and this class is used in these cases. The
PriorityQueue is based on the priority heap. The elements of the priority queue are ordered according to
the natural ordering, or by a Comparator provided at queue construction time, depending on which
constructor is used.
code:
import [Link].*;
class GfG {
public static void main(String args[])
{
PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();
[Link](10);
[Link](20);
[Link](15);
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
}
Deque Interface:
Deque, also known as a double-ended queue, is a data structure where we can add and remove the
elements from both ends of the queue. This interface extends the queue interface. The class which
implements this interface is ArrayDeque. Since ArrayDeque class implements the Deque interface, we
can instantiate a deque object with this class. we can insert and remove elements from both front and
rear.
1. ArrayDeque
2. LinkedList
1. ArrayDeque class: ArrayDeque class which is implemented in the collection framework provides
us with a way to apply resizable-array. This is a special kind of array that grows and allows users to
add or remove an element from both sides of the queue.
code:
import [Link];
class Main {
public static void main(String[] args) {
ArrayDeque<String> animals= new ArrayDeque<>();
[Link]("Dog");
[Link]("Cat");
[Link]("Horse");
[Link]("ArrayDeque: " + animals);
}
}
Methods:
set Interface
A set is an unordered collection of objects in which duplicate values cannot be stored. This collection is
used when we wish to avoid the duplication of the objects and wish to store only the unique objects.
class of set interface :
1. HashSet
2. LinkedHashSet
3. EnumSet
4. TreeSet
A. HashSet: The HashSet class is an inherent implementation of the hash table data structure. The
objects that we insert into the HashSet do not guarantee to be inserted in the same order. The
objects are inserted based on their hash code. This class also allows the insertion of NULL elements.
import [Link].*;
Map Interface:
A map is a data structure that supports the key-value pair for mapping the data. This interface doesn’t
support duplicate keys because the same key cannot have multiple mappings, however it allows
duplicate values in different keys. A map is useful if there is data and we wish to perform operations
based on the key.
1. HashMap
2. EnumMap
3. LinkedHashMap
4. WeakHashMap
5. TreeMap
A. HashMap:
HashMap provides the basic implementation of the Map interface of Java. It stores the data in (Key,
Value) pairs. To access a value in a HashMap, we must know its key. HashMap uses a technique
called Hashing. Hashing is a technique of converting a large String to a small String that represents
the same String so that the indexing and search operations are faster. HashSet also uses HashMap
internally.
import [Link].*;
public class HashMapDemo {
public static void main(String args[]){
HashMap<Integer, String> hm = new HashMap<Integer, String>();
[Link](1, "Geeks");
[Link](2, "For");
[Link](3, "Geeks");
[Link]("Value for 1 is " + [Link](1));
for ([Link]<Integer, String> e : [Link]())
[Link]([Link]() + " " + [Link]());
}
}
B. Treemap:
import [Link];
class Main {
public static void main(String[] args) {
TreeMap<String, Integer> evenNumbers = new TreeMap<>();
[Link]("Two", 2);
[Link]("Four", 4);
[Link]("Six", 6);
[Link]("TreeMap of even numbers: " + evenNumbers);
TreeMap<String, Integer> numbers = new TreeMap<>();
[Link]("One", 1);
[Link](evenNumbers);
[Link]("TreeMap of numbers: " + numbers);
}
}
Methods of Map:
1. put(K, V) - Inserts the association of a key K and a value V into the map. If the key is already
present, the new value replaces the old value.
2. putAll() - Inserts all the entries from the specified map to this map.
3. putIfAbsent(K, V) - Inserts the association if the key K is not already associated with the value V.
4. get(K) - Returns the value associated with the specified key K. If the key is not found, it
returns null.
5. getOrDefault(K, defaultValue) - Returns the value associated with the specified key K. If the key
is not found, it returns the defaultValue.
6. containsKey(K) - Checks if the specified key K is present in the map or not.
7. containsValue(V) - Checks if the specified value V is present in the map or not.
8. replace(K, V) - Replace the value of the key K with the new specified value V.
9. replace(K, oldValue, newValue) - Replaces the value of the key K with the new
value newValue only if the key K is associated with the value oldValue.
10. remove(K) - Removes the entry from the map represented by the key K.
11. remove(K, V) - Removes the entry from the map that has key K associated with value V.
12. keySet() - Returns a set of all the keys present in a map.
13. values() - Returns a set of all the values present in a map.
14. entrySet() - Returns a set of all the key/value mapping present in a map.
Iterator interface
1. The Iterator interface of the Java collections framework allows us to access elements of a collection.
2. Iterators are used to retrieve elements one by one.
3. Iterator is one of the Java cursors.
4. It is a universal iterator as we can apply it to any Collection object.
5. It supports only Forward direction iteration
Enumeration interface
C. Thread:
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
Synchronization ---141
synchronize method safe but not fast . unsynchronize method is fast but not safe.
Java Rule various
1. we cannot use private modifier before class. Only public, abstract and final modifier we can use.
class Main {
public static void main(String[] args) {
[Link]("Command-Line arguments are");
for(String str: args) {
[Link](str);
}
}
}
9. JVM run main method in java.
10. For call non-static method we must create object.
11. [Link]() method not called void method.
Void show();
[Link](show())
12. Static method cannot override.
13. Local variable must be initializer before use;
Void main(){
Int x;
[Link](x); // error
}